#!/bin/bash
#
# mb-obthemes: script to save or restore openbox gui configurations
#
# Written for BunsenLabs by damo <damo@bunsenlabs.org> October 2015
#
# Ported for Manjaro/Mabox by napcok <danieln@maboxlinux.org> March 2016
#
# Save options are for  Conky(s)
#                       Tint2(s)
#                       Openbox theme
#                       GTK theme
#                       Background (uses Nitrogen or feh, depending which
#                                   has the newer saved bg config file)
#                       Terminator config
#
# Paths are assumed to be BunsenLabs defaults
#
# A Screenshot is saved (Windows are hidden briefly so the image
#                        is the bare desktop, with any Tint2s
#                        or Conkys which are running, and a representive
#                        menu and window open)
#
# A time-stamped backup of rc.xml is saved "just in case".
#
# USER VARIABLE: xdotool is used to move the mouse pointer, and assumes the
# root-menu is shown with "Super + Space" keys, and the right mouse button is
# set for "r-click". If you have set these to something else, then edit the
# "MENUMODIFIER" and "MOUSECMD" variables.
# Set the variable "KEYDOWN" to where "Preferences" is in the root-menu (or
# anything else you might want displayed).
# The image viewer is set to be "bl-image-viewer". Edit the "IMGCMD" variable
# to change this.
#
# WARNING: It is assumed that the conkys are not being run via a script, so
# they will appear on all desktops. If you usually use a script, then you
# may have to make your own arrangements! Conkys in non-default directories
# can be saved, but will not be seen when running the bl conky chooser
#
########################################################################
#
# KNOWN ISSUES:
# Virtualbox does not allow the guest to move the host mouse cursor, using xdotool,
# so the screenshot may produce an incorrect theme displayed and/or poor positioning.
# A workaround is to move the cursor to some free space, and use the "Enter" key in the
# "Configurations to be saved:" dialog.
#

# TEMP for update Mabox provided themes
if [[ ! -f "$HOME/.config/blob/.updated" ]];then
mb-reset blobthemes
touch "$HOME/.config/blob/.updated"
fi

#### VARIABLES #########################################################
CONFIGPATH="$HOME/.config/blob"
SETTINGS=""
OBPATH="$HOME/.config/openbox"
CURSESSION="$CONFIGPATH/current"
CONFIGDIR=""
LISTMSG=""
CZEN=0
TZEN=0
NUMDIRS=0
CONKYCMD=""
COLS=1
### CONFIGS VARIABLES
TERMDIR="$HOME/.config/terminator"
TERMFILE="$TERMDIR/config"
FEHFILE="$HOME/.fehbg"
NITRODIR="$HOME/.config/nitrogen"
NITROFILE="$NITRODIR/bg-saved.cfg"
CONKYPATH="$HOME/.config/conky"
CONKYSESSION="$CONKYPATH/conky-sessionfile"
TINTSESSION="$HOME/.config/tint2/tint2-sessionfile"
OBBROWSER_ICON_CACHE="$HOME/.config/obbrowser/icons.db"
GTK2=".gtkrc-2.0"
GTK2MINE=".gtkrc-2.0.mine"
GTK3="$HOME/.config/gtk-3.0"
GTK3x="$HOME/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-notifyd.xml"
PICKOBCFGS="OB menu.xml rc.xml autostart"
PICKCONKY="Conky"
PICKTINT="Tint2"
PICKSCROT="Save screenshot"
### END CONFIGS VARIABLES

### DIALOG VARIABLES
DIALOG="yad --center --undecorated --borders=20 --window-icon=distributor-logo-mabox"
DIALOGDEC="yad --center  --borders=20 --window-icon=distributor-logo-mabox"
case $LANG in
    pl*)
        TITLE="Menedżer Motywów Mabox"
        CANCEL="--button=Anuluj:1"
        EXIT="--button=Wyjdź:1"
        CLOSE="--button=Zamknij:1"
        TXTINTRO="<big><b>Mabox\n\nOpenbox Configuration Manager</b></big>\n\n\n \
<b>Zapisuje i przywraca ustawienia dla:</b>\n\n \
\tmotyw Openbox\n \
\tmotyw GTK\n \
\tConky\n \
\tTint2\n \
\tTapeta pulpitu\n \
\t+ zrzut ekranu\n\n"
        MAIN_TEXT="Aby zastosować wybrany motyw: kliknij podwójnie, wciśnij <b>Enter</b>\nlub użyj przycisku <b>Przywróć</b>. \n"
        RESTORE="Przywróć:0"
        DELETE="Usuń:2"
        VIEW_IMG="Zobacz obrazek:4"
        ADD="Utwórz:3"
        ABOUT="Info:5"
        SAVE_SETTINGS="Zapisz ustawienia:0"
        VIEW_SAVED="Zobacz zapisane:2"
        ACTIVE="Aktywny"
        NAME="Nazwa"
        SCREEN_SHOT="Zrzut ekranu"
        CHOOSE_WHAT_TO_SAVE="Wybierz co zapisać..."
        CHOOSE_ALL="Zaznacz wszystko:2"
        CHOOSE_SELECT="Wybór"
        CHOOSE_CONFIG="Konfiguracja"
        CHOOSE_SOMETHING="\n Wybierz coś..."
        FILES_TO_SAVE="<big><b><u>Pliki konfiguracyjne do zapisania:</u></b></big>\n\n"
        RESTORING_CONF="Przywracanie konfiguracji zapisanej jako <big>$DIR</big>\n\n"
        CHOOSE_BEFORE_DELETE="Wybierz coś przed usunięciem"
        DELETE_FOR_SURE="Usunąć zapisaną konfigurację <b>$FPATH</b>\noraz zrzut ekranu?"
        SETTINGS_SAVED="Ustawienia zapisane jako" 
        CHOOSE_IMAGE="Wybierz obrazek"
        COLLECTION_NAME="Nazwa kolekcji"
        SAVED_ON="Zapisana:"
        OVERWRITE_SESSION="Nadpisać istniejącą sesję?"
        WALLSAVEDBYNITOGEN="Tapeta ustawiona przez Nitrogen"
        RUNNING_CONKY="Działające Conky:"
        RUNNING_TINT2="Działające Tint2:"
        NO_CONKY_RUNNING="Wybrano zapisanie Conky\nale żaden Conky nie jest uruchomiony"
        NO_TINT2_RUNNING="Wybrano zapisanie panelu Tint2\nale żaden nie jest uruchomiony"
        PICKBG="Tapeta pulpitu"
        PICKOB="Motyw Openbox"
        PICKGTK="Wystrój GTK"
        ;;
    es*)
        TITLE="Gestor de Temas"
        CANCEL="--button=Cancelar:1"
        EXIT="--button=Salir:1"
        CLOSE="--button=Cerrar:1"
        TXTINTRO="<big><b>BunsenLabs\n\nGestor de Configuración Openbox</b></big>\n\n\n \
<b>Guardar o Restaurar Ajustes para:</b>\n\n \
\tTemas Openbox\n \
\tTemas GTK\n \
\tRecuadros Conky\n \
\tPaneles Tint2\n \
\tFondos de pantalla\n \
\t+ Captura Pantalla\n\n"
        MAIN_TEXT="Haz doble clic, o presiona <b>Enter</b>, o usa el botón de <b>Restaurar</b> para recuperar los ajustes\n"
        RESTORE="Restaurar:0"
        DELETE="Borrar:2"
        VIEW_IMG="Ver imagen:4"
        ADD="Agregar uno nuevo:3"
        ABOUT="Acerca de:5"
        SAVE_SETTINGS="Guardar ajustes:0"
        VIEW_SAVED="Vistas guardadas:2"
        ACTIVE="Último ajuste"
        NAME="Guardar ajuste"
        SCREEN_SHOT="Capturar Pantalla"
        CHOOSE_WHAT_TO_SAVE="Elige los ajustes a guardar..."
        CHOOSE_ALL="Selecciona todos:2"
        CHOOSE_SELECT="Seleccionar"
        CHOOSE_CONFIG="Elige ajuste"
        CHOOSE_SOMETHING="\n  Haz una selección...."
        FILES_TO_SAVE="<big><b><u>Ajustes en Openbox a guardar:</u></b></big>\n\n"
        RESTORING_CONF="Recuperando ajustes guardados como <big>$DIR</big>\n\n"
        CHOOSE_BEFORE_DELETE="Elige un ajuste antes de intentar borrar"
        DELETE_FOR_SURE="Elimina ajustes ya guardados <b>$FPATH</b>\nand screenshot?"
        SETTINGS_SAVED="Los cambios fueron guardados como"
        CHOOSE_IMAGE="Elige una imagen"
        COLLECTION_NAME="Nombrar una colección"
        OVERWRITE_SESSION="Overwrite existing?"
        SAVED_ON="Guardado:"
        WALLSAVEDBYNITOGEN="Fondo de pantalla guardado por Nitrogen"
        RUNNING_CONKY="Recuadro(s) ejecutándose:"
        RUNNING_TINT2="Panel(es) ejecutándose:"
        NO_CONKY_RUNNING="Elegir guardar un recuadro \npero no uno que está ejecutándose"
        NO_TINT2_RUNNING="Elegir un panel \npero no uno que está ejecutándose"
        PICKBG="Fondos de pantalla"
        PICKOB="Temas OB"
        PICKGTK="Temas GTK"
        ;;
    *)
        TITLE="BLOB Config Manager"
        CANCEL="--button=Cancel:1"
        EXIT="--button=Quit:1"
        CLOSE="--button=Close:1"
        TXTINTRO="<big><b>BunsenLabs\n\nOpenbox Configuration Manager</b></big>\n\n\n \
<b>Save or Restore settings for:</b>\n\n \
\tOpenbox theme\n \
\tGTK theme\n \
\tConkys\n \
\tTint2\n \
\tDesktop Background\n \
\t+ Screenshot\n\n"
        MAIN_TEXT="Double-click selection, or <b>Enter</b>, or use the <b>Restore</b> button to restore settings\n"
        RESTORE="Restore:0"
        DELETE="Delete:2"
        VIEW_IMG="View image:4"
        ADD="Add New:3"
        ABOUT="About:5"
        SAVE_SETTINGS="Save Settings:0"
        VIEW_SAVED="View Saved:2"
        ACTIVE="Last set"
        NAME="Config Name"
        SCREEN_SHOT="Screenshot"
        CHOOSE_WHAT_TO_SAVE="Choose the configs to save..."
        CHOOSE_ALL="Select All:2"
        CHOOSE_SELECT="Select"
        CHOOSE_CONFIG="Config"
        CHOOSE_SOMETHING="\n  Make a selection...."
        FILES_TO_SAVE="<big><b><u>Openbox Configurations to be saved:</u></b></big>\n\n"
        RESTORING_CONF="Restoring Configs saved as <big>$DIR</big>\n\n"
        CHOOSE_BEFORE_DELETE="Make a selection before trying to delete"
        DELETE_FOR_SURE="Delete saved configurations <b>$FPATH</b>\nand screenshot?"
        SETTINGS_SAVED="Settings were saved as"
        CHOOSE_IMAGE="Make a selection"
        COLLECTION_NAME="Collection name"
        OVERWRITE_SESSION="Overwrite existing session?"
        SAVED_ON="Saved:"
        WALLSAVEDBYNITOGEN="Wallpaper saved by Nitrogen"
        RUNNING_CONKY="Runninig Conky:"
        RUNNING_TINT2="Running Tint2s:"
        NO_CONKY_RUNNING="You select to save Conky\nbut no Conky is running"
        NO_TINT2_RUNNING="You select to save Tint2\nbut no Tint2 is running"
        PICKBG="Desktop Background"
        PICKOB="OB theme"
        PICKGTK="GTK theme"
        ;;
esac

IMG="--image=mbs_trans_64"
T="--text="
OK="--button=OK:0"


### END DIALOG VARIABLES

### USER SETTINGS
IMGCMD="viewnior"    # application command to view screenshot
MENUMODIFIER="super+space"  # keybind for show root-menu
MOUSECMD="click 3"          # mouse r-click
KEYDOWN=4           # adjust this for where "Preferences" is in the menu
#### END VARIABLES #####################################################

### FUNCTIONS ##########################################################

function Intro(){
    local INTRO RET
    getSet
    #  If blob/ is empty, then don't display "Save Settings" option in Intro dialog
    if (( $NUMDIRS > 0 ));then
        INTRO=$($DIALOGDEC $IMG "$T$TXTINTRO" \
        --title="$TITLE" \
        --button="$SAVE_SETTINGS" --button="$VIEW_SAVED" $CLOSE \
        --borders=30 \
        2>/dev/null )
    else
        INTRO=$($DIALOGDEC $IMG \
        --title="$TITLE" \
        "$T$TXTINTRO" \
        --button="$SAVE_SETTINGS" $CLOSE \
        --borders=30 \
        2>/dev/null )
    fi
    RET=$?
    case $RET in
        0)  setName
            saveSettings
            getScrot
            if [[ -d $CONFIGDIR-BKP ]];then
                rm -rf "$CONFIGDIR-BKP"
                echo -e "\n  Temporary $CONFIGDIR deleted\n"
            fi
            restoreSettings
            ;;
        1)  echo "CANCELLED..."
            exit 0
            ;;
        2)  getSet
            restoreSettings
            ;;
        *)  echo "RETURN ERROR" 2>&1
            ;;
    esac
}

function getSet(){      # get name of currently set BLOB config
    NUMDIRS=0
    NUMDIRS=$(ls -l "$CONFIGPATH" | grep -c ^d) # check if any dirs present
    if (( $NUMDIRS == 0 ));then
        if [[ -f $CURSESSION ]];then
            rm $CURSESSION
        fi
    elif (( $NUMDIRS > 0 )) && [[ -f $CURSESSION ]];then
        SET=$(cat $CURSESSION)
    fi
}

function countMonitors(){ #test for more than 2 monitors connected.
    MON=$(xrandr -q | grep -c " connected")
    PRIMARY=$(xrandr -q | awk '/ connected/ {if ($3=="primary") print $4; else print $3}')
    PSIZE=${PRIMARY%%x*}    # Primary monitor width
    case $MON in
        1|2|3)  getScreenDims $MON $PSIZE
                ;;
        * )     W=600
                H=600
                echo -e "\n  Script cannot deal with these monitors.\
                \n  Setting dialog width height = 600 x 600" 2>&1
    esac
}

function getScreenDims(){   # Set width and height for View dialog
    # param $1 = num screens; param $2 = primary screen width
    desktopW=$(xrandr -q | awk '/Screen/ {print $8}')  # total desktop width
    desktopH=$(xrandr -q | awk '/Screen/ {print $10}') # desktop height
    desktopH=${desktopH%%,*}    # remove trailing comma
    if (( $1 == 1 ));then
        W=$(( $desktopW / 3 ))  # 1/3 width
    else
        W=$(( $2 / 3 ))  # 1/3 width primary monitor
    fi
    H=$(( ($desktopH / 3)*2 ))  # 2/3 height
}

function setName(){  # set name of collection, make dir and session settings file
    case $LANG in
    pl*)
    MSG="  Pliki konfiguracyjne zostaną zapisane do nowego katalogu w\
    \n  $CONFIGPATH\n\n  Wpisz nazwę dla nowej kolekcji...  "
    MSG2="  Nie wybrano plików.\n\n  Spróbować ponownie?"
    ;;
    *)
    MSG="  Configurations will be saved to a new directory in  \
    \n  $CONFIGPATH\n\n  Enter name of new collection...  "
    MSG2="  No file specified for new saved session.\n\n  Try again?"
    ;;
    esac
    LOOP=1
    DEL=0
    while [[ $LOOP ]];do  # loop dialog if nothing is selected
        ANS=$($DIALOG --entry \
            $CANCEL --button="OK:0" \
            "$T$MSG" \
            2>/dev/null )
        if (( $? == 1 )) ;then # Cancel was selected
            Intro
        elif [[ ! $ANS ]] ;then     # entry was empty
            $DIALOG --image="dialog-question" \
            "$CANCEL" "$OK" \
            "$T$MSG2" \
            2>/dev/null
            RET=$?
            echo -e "\n  Nie podano nazwy dla kolekcji!" 2>&1
            if (( $RET == 0 ));then
                continue
            else
                Intro
            fi
        else
            ANS=$(echo $ANS | sed -e 's/ /_/g')    # replace any spaces in dir name
            CONFIGDIR="$CONFIGPATH/$ANS"
            if [[ -d $CONFIGDIR ]];then
                echo -e "\n  $CONFIGDIR już istnieje"

                $DIALOG --form --image="dialog-question" \
                --text="$OVERWRITE_SESSION" \
                "$CANCEL" "$OK" \
                --width=300 \
                2>/dev/null

                if (( $? == 0 ));then
                    mv {"$CONFIGDIR","$CONFIGDIR-BKP"} && mkdir -p "$CONFIGDIR"
                    DEL=1
                    SETTINGS="$CONFIGDIR/settings.cfg"
                    > "$SETTINGS"
                    LISTMSG="$CONFIGDIR/LISTMSG.txt"
                    > "$LISTMSG"
                    break
                else
                    continue
                fi
            fi
            mkdir -p "$CONFIGDIR"
            SETTINGS="$CONFIGDIR/settings.cfg"
            LISTMSG="$CONFIGDIR/LISTMSG.txt"
            > "$SETTINGS"
            > "$LISTMSG"
            break
        fi
    done
    setText
}

function setText(){
    TIME=$(date)
    if (( $DEL == 1 ));then
        TXT="  (Existing session overwritten)"
    else
        TXT=""
    fi
    echo -e "\n  Konfiguracja będzie zapisana jako: $ANS$TXT"
    if [[ $1 = repeat ]];then
        > "$LISTMSG"    # reset LISTNSG.txt
    fi
    # Store list in listfile
    echo -e "<b>$COLLECTION_NAME: $ANS</b>\t$TXT\n$SAVED_ON $TIME\n" >> "$LISTMSG"
}

function getBg(){    # find if feh or nitrogen was used. Save config file(s)
    if [[ -e $NITROFILE ]] && [[ -e $FEHFILE ]];then  # see which was last used to set background
        if [[ $NITROFILE -nt $FEHFILE ]];then # use most recent method
            BGSET="NITROGEN"
        else
            #BGSET="FEH"
            BGSET="NITROGEN"
        fi
    elif [[ -e $FEHFILE ]] && [[ ! -e $NITROFILE ]];then  # use feh for background
        #BGSET="FEH" 
        BGSET="NITROGEN" 
    elif [[ -e $NITROFILE ]] &&  [[ ! -e $FEHFILE ]];then    # use nitrogen for background
        BGSET="NITROGEN"
    else
        echo -e "\n  No background-setting application found" 2>&1
        BGSET="None"
    fi
    echo -e "\n  Tapeta ustawiana za pomocą $BGSET"
    case "$BGSET" in
        FEH     )   echo "[BACKGROUND] $BGSET" >> "$SETTINGS"
                    cp "$FEHFILE" "$CONFIGDIR"
                    echo -e "\n  $FEHFILE copied"
                    bgFeh
                    ;;
        NITROGEN)   echo "[BACKGROUND] $BGSET" >> "$SETTINGS"
                    cp "$NITRODIR/nitrogen.cfg" "$CONFIGDIR"
                    cp "$NITROFILE" "$CONFIGDIR"
                    echo -e "\n  Zapisano plik: $NITROFILE"
                    getNitrogen
                    ;;
        None    )   echo -e "\n  No background-setting application found" 2>&1
                    echo "[BACKGROUND] $BGSET" >> "$SETTINGS"
                    ;;
        *       )   echo -e "\n  ERROR: No background config found" 2>&1
                    exit 1
                    ;;
    esac
}

function bgFeh(){    # get Feh saved backgrounds
    FFILE="$CONFIGDIR/.fehbg"
    if [[ -f $FFILE ]];then
        BG=""
        # get fields between single quotes
        for F in $(grep -o "'.*'" $FFILE | sed "s/'//g" 2>/dev/null);do
            BG="$BG$F;\n\t"
        done
        echo -e "\n  Backgrounds set with Feh, using:\n\
        \t$FEHFILE\n\t$BG"
        echo "Background set with feh:\n\t$BG" >> "$LISTMSG"
    else
        echo "\n Nie odnaleziono $FFILE" 2>&1
    fi
}

function getNitrogen(){  # get Nitrogen saved backgrounds
    NFILE="$CONFIGDIR/bg-saved.cfg"
    if [[ -f $NFILE ]];then
        BG=""
        while read line;do
            BGLINE=$(echo $line | awk -F"file=" '{print $2}')
            if [[ $BGLINE ]];then
                BG="$BG$BGLINE;\n"
            fi
        done < "$NFILE"
        echo -e "\n  Tapeta ustawiona przez Nitrogen, plik:\t$NITROFILE"
        echo -e "$BG"
        echo "$WALLSAVEDBYNITOGEN:\n$BG" >> "$LISTMSG"
    else
        echo "\n Nie odnaleziono $NFILE" 2>&1
    fi
}

function copyConky(){
    if [[ $(pidof conky) ]];then
    mkdir -p "$CONFIGDIR/conky"
    rm "$CONFIGDIR/conky/*conkyrc"
    cp ~/.config/conky/*conkyrc "$CONFIGDIR/conky/"
    cp ~/.config/conky/conky-sessionfile "$CONFIGDIR/conky/"
    fi
}

function getConky(){
    CONKYCMD=""
    LISTMSGTXT=""
    TXT=""
    CONKYTEMP=$(mktemp --tmpdir blob.XXXX)
    if [[ $(pidof conky) ]];then    # get full command of running conkys
        > "$CONKYTEMP"
        copyConky
        pgrep -a conky | while read pid CMD;do
            echo "$CMD;" >> "$CONKYTEMP"
        done
        TXT="Conky:\n\n"
        DEF="Domyślny"
        MSG="$RUNNING_CONKY"
        while read line;do
            LINE=$(echo "$line" | sed 's/;//')
            CONKYCMD="$CONKYCMD $LINE & sleep 1s;"
            if [[ $LINE = "conky" ]] || [[ $LINE = "conky -q" ]];then
                line="$DEF"
            else
                line=${line##*" "}      # get full filepath
            fi
            TXT="$TXT$line"
            LISTMSGTXT="$LISTMSGTXT\n\t$line"
        done < "$CONKYTEMP"
        echo "[CONKY] $CONKYCMD" >> "$SETTINGS"
        rm -f "$CONKYTEMP"
        echo "$MSG\t$LISTMSGTXT\n" >> "$LISTMSG"
        echo -e "\n  Zapisano działające sesje Conky"
    else
        DLG=$($DIALOG --form --image="dialog-warning" \
        --text="$NO_CONKY_RUNNING" \
        "$OK" \
        --width=300) 2>/dev/null
    fi
}

function checkConkyzen(){    # see if mb-conky-manager and session file present
    if type mb-conkyzen &>/dev/null;then
        if [[ -f $CONKYSESSION ]]; then
            CZEN=1  # set flag for Restore choice
        fi
    fi
}

function getTint(){
    TEMPTINT=$(mktemp --tmpdir blob.XXXX) # make blank tempfile, to save running tint2 paths
    if [[ $(pidof tint2) ]];then
        pgrep -a tint2 | while read pid cmd;do
            if [[ ${cmd%% *} = tint2 ]];then
                TPATH=$(echo "$cmd" | awk '{print $NF}')
                echo "$TPATH;" >> "$TEMPTINT"
            fi
        done
        TXT="Tint2:\n\n"
        MSG="$RUNNING_TINT2"
        TINTCMD=""
        LISTMSGTXT=""
        while read line;do
            TXT="$TXT$line"
            LINE=$(echo "$line" | sed 's/;//')
            if [[ $LINE = tint2 ]];then         # default command was used
                TINTCMD="$TINTCMD$LINE;"
                LISTMSGTXT="$LISTMSGTXT\n\tDefault Tint2"
            else
                TINTCMD="$TINTCMD$LINE;"
                LISTMSGTXT="$LISTMSGTXT\n\t$LINE"
            fi
        done < "$TEMPTINT"
        #MY_EDIT
	path=$( echo $TINTCMD | awk -F"/" '{print "/"$(NF-2)"/"$(NF-1)"/"$NF}')
        echo "[TINT2] $path" >> "$SETTINGS"
        rm -f "$TEMPTINT"
        echo "$MSG\t$LISTMSGTXT\n" >> "$LISTMSG"
        echo -e "\n  Zapisano działające panele Tint2"
    else
        DLG=$($DIALOG --form --image="dialog-warning" \
        --text="$NO_TINT2_RUNNING" \
        "$OK" \
        --width=300) 2>/dev/null
    fi
}

function killTints(){
    pgrep -a tint2 | while read pid cmd; do
        if [[ ${cmd%% *} = tint2 ]]; then
            kill "$pid"
        fi
    done
}

function checkTint2zen(){    # see if mb-tint2zen and session file present
    if type mb-tint2zen &>/dev/null;then
        if [[ -f $TINTSESSION ]]; then
            TZEN=1          # set flag for Restore choice
        fi
    fi
}

function getOBtheme(){   # copy <theme> section from rc.xml to obtheme.txt, and copy menu.xml file
    RCFILE="$OBPATH/rc.xml"
    tag="theme"
    sed -n "/<$tag>/,/<\/$tag>/p" "$RCFILE" > "$CONFIGDIR/obtheme.txt"
    echo "[OBTHEME]" >> "$SETTINGS"
    #cp "$OBPATH/menu.xml" "$CONFIGDIR"
    getOBname
}

function getOBname(){    # get OB theme name
    OBFILE="$CONFIGDIR/obtheme.txt"
    OBTHEME=$(awk 'NR==2 {print;exit}' $OBFILE | awk -F'[>|<]' '{print $3}')
    TXT="Openbox theme:  $OBTHEME\n"
    echo -e "\n  Zapisano $TXT"
    echo "$TXT" >> "$LISTMSG"
    if [[ "$OBTHEME" == "MBcolors" ]];then
    mkdir -p $CONFIGDIR/MBcolors
    cp -a ~/.themes/MBcolors/openbox-3/* $CONFIGDIR/MBcolors/
    cp -a ~/.config/mabox/jgobthemes/MBcolors.colorrc $CONFIGDIR
    fi
    theme.sh -l|tail -n1 > "$CONFIGDIR/terminal_theme"
}

function getGTKtheme(){
    GTKTHEMES=( "$HOME/$GTK2" "$HOME/$GTK2MINE" "$GTK3" "$GTK3x" )
    for f in "${GTKTHEMES[@]}";do
        if [[ -f $f ]];then
            cp "$f" "$CONFIGDIR"
        elif [[ -d $f ]];then
            cp -r "$f" "$CONFIGDIR"
        fi
    done
    echo "[GTK]" >> "$SETTINGS"
    getGTKname
}

function getGTKname(){   # get GTK theme name
    GTKFILE="$CONFIGDIR/.gtkrc-2.0"
    while read line;do
        if [[ $(echo $line | grep "gtk-theme-name" ) ]] &>/dev/null;then
            GTKTHEME=$(echo $line | awk -F '"' '{print $2}')
        fi
    done < "$GTKFILE"
    TXT="GTK theme:  $GTKTHEME\n"
    echo -e "\n  Zapisano $TXT"
    echo "$TXT" >> "$LISTMSG"
}
function getMenuPanel() {
. ~/.config/mabox/mabox.conf
	#TODO: save Betterclock vars"
	#echo "configdir: $CONFIGDIR"
	cp "$HOME"/.config/mabox/mabox.conf "$CONFIGDIR"/
	cp "$HOME"/.config/mabox/jgobthemes/MBcolors.colorrc "$CONFIGDIR"/
	cp "$HOME"/.config/mabox/wpicon.png "$CONFIGDIR"/
	cp "$HOME"/.config/mabox/wpicon_wide.png "$CONFIGDIR"/
	
cat << EOF > "$CONFIGDIR/mvars.txt"
jgmenu_use_icons=${jgmenu_use_icons:-true}
jgmenu_use_borders=${jgmenu_use_borders:-false}
jgmenu_icon_theme='${jgmenu_icon_theme:-Numix-Square}'
menu_font_family='${menu_font_family:-Ubuntu Regular}'
menu_font_size=${menu_font_size:-10}
menu_sep_font_family='${menu_sep_font_family:-Ubuntu Bold}'
menu_sep_font_size=${menu_sep_font_size:-11}
arrow_string='${arrow_string:-}'
arrow_string_left='${arrow_string_left:-}'
jgtools_border=${jgtools_border:-0}
jgtools_padding=${jgtools_padding:-8}
jgtools_radius=${jgtools_radius:-2}
submenu_spacing=${submenu_spacing:-4}
panels_topmargin=${panels_topmargin:-40}
panels_heightpos=${panels_heightpos:-full}
item_height_factor=${item_height_factor:-200}
ok_icon=${ok_icon:-󰞑}
ok_fgcolor=${ok_fgcolor:-#008a00}
warn_fgcolor=${warn_fgcolor:-#FFFFFF}
warn_bgcolor=${warn_bgcolor:-#bd1e24}
logo_in_color=${logo_in_color:-#32B557}
logo_out_color=${logo_out_color:-#F8F8FF}
logo_in_opacity=${logo_in_opacity:-0.7}
logo_out_opacity=${logo_out_opacity:-0.7}
EOF
}
function setXsettingsd() {
	mkdir -p $HOME/.config/xsettingsd

gtk_theme="$(grep "^[^#]*gtk-theme-name" "${HOME}/.config/gtk-3.0/settings.ini")"
gtk_theme="${gtk_theme/gtk-theme-name*=}"
echo "Net/ThemeName \"$gtk_theme\"" > "$HOME/.config/xsettingsd/xsettingsd.conf"

gtk_theme_icons="$(grep "^[^#]*gtk-icon-theme-name" "${HOME}/.config/gtk-3.0/settings.ini")"
gtk_theme_icons="${gtk_theme_icons/gtk-icon-theme-name*=}"
echo "Net/IconThemeName \"$gtk_theme_icons\"" >> "$HOME/.config/xsettingsd/xsettingsd.conf"

bl-reload-gtk23
}
function checkTint2(){   # kill or restart tint2s for screenshot, if necessary
    if [[ $1 = stop ]];then
        if ! cat "$SETTINGS" | grep "TINT2" &>/dev/null;then
            tmpTINT=$(mktemp --tmpdir blob.XXXX) # make blank tempfile, to save running tint2 paths
            if [[ $(pidof tint2) ]];then
                pgrep -a tint2 | while read pid cmd;do
                    if [[ ${cmd%% *} = tint2 ]];then
                        echo $cmd >> "$tmpTINT"
                    fi
                done
            fi
            killTints
        fi
    fi
    if [[ $1 = start ]];then
        if [[ -f "$tmpTINT" ]] 2>/dev/null;then
            while read line;do
                ($line &) &>/dev/null
                sleep 1s
            done < "$tmpTINT"
            rm -f "$tmpTINT"
        fi
    fi
}

function getScrot(){
    pid=""
    TMPSCROT=$(mktemp --tmpdir blob.XXXX)
    SCROT="$CONFIGPATH/$ANS"
    CURRDTOP=$(xprop -root _NET_CURRENT_DESKTOP | tail -c -2) # desktop number
    MONS=$(xrandr -q | grep -c " connected")    # number of monitors
    # Set mouse position, for appearance of root-menu
    screenW=$(xrandr -q | awk '/Screen/ {print $8}')
    screenH=$(xrandr -q | awk '/Screen/ {print $10}')
    screenH=${screenH%,}

    if (( $MONS == 1 ));then # single monitor
        appX=$(( (screenW/20)*8 ))
        menuX=$(( screenW/20 ))
    else
        appX=$(( (screenW/20)*4 ))
        menuX=$(( (screenW/20)*1 ))
    fi
    appY=$(( (screenH/20)*4 ))
    menuY=$(( screenH/20 ))

    wmctrl -l -x > "$TMPSCROT"      # store window list in tempfile
    wmctrl -k on                    # hide windows, show desktop
    
    checkTint2 stop     # stop running Tint2s for the scrot,
                        # if not selected to be saved
    #notify-send.sh "X: $menuX" "Y: $menuY"
    xdotool mousemove --sync "$menuX" "$menuY" && xdotool click 3
	sleep 1;
    i=1
    while (( $i <= $KEYDOWN ));do
        xdotool key --delay 100 Down
        i=$(( $i+1 ))
    done
    xdotool key --delay 20 Right && sleep 0.3

    # take scrot
    scrot -t 9 "$SCROT.jpg"    # scrot thumbnail @9% fullsize
    THUMB=$(find $CONFIGPATH -maxdepth 1 -type f -name "*-thumb.jpg" 2>/dev/null)
    mv $THUMB $CONFIGDIR

    # close root menu
    xdotool mousemove_relative --sync --polar 0 10 click 1
    
    # restore hidden windows
    while read line; do
        WINDOW=$(echo $line | awk '{print $1}') # Window_ID is first field
        DTOP=$(echo $line | awk '{print $2}' )  # Desktop number is second field
        if (( $DTOP == $CURRDTOP )) &>/dev/null;then
            xdotool windowactivate "$WINDOW"
        fi
    done < "$TMPSCROT"
    checkTint2 start        # restore any stopped Tint2s
    rm -f "$TMPSCROT"
}

function restoreGTK(){   # $1 is chosen saved config dir
    GTKPATHS=( "$HOME" "$HOME" "$GTK3" "$GTK3x" )
    GTKSAVED=( "$1/$GTK2" "$1/$GTK2MINE" "$1/gtk-3.0" "$1/xfce4-notifyd.xml" )
    i=0
    for f in ${GTKSAVED[@]};do
        if [[ -e $f ]];then     # if destination exists
            if [[ -e ${GTKPATHS[i]} ]];then
                if [[ ${GTKSAVED[i]} = $1/gtk-3.0 ]];then
                    cp -r ${GTKSAVED[i]}/* ${GTKPATHS[i]} # restore contents of gtk-3.0
                fi
                cp ${GTKSAVED[i]} ${GTKPATHS[i]}
                echo -e "\n  Przywrócono: ${GTKSAVED[i]}"
            else
                echo -e "\n  Restore path ${GTKPATHS[i]} not found" 2>&1
            fi
        else
            echo -e "\n  ${GTKSAVED[i]} not found" 2>&1
        fi
        i=$(($i+1))
    done
}
function restoreMenuPanel() {
#. ~/.config/mabox/mabox.conf
cp -a $1/mabox.conf $HOME/.config/mabox/mabox.conf
cp -a $1/wpicon.png $HOME/.config/mabox/wpicon.png
cp -a $1/wpicon_wide.png $HOME/.config/mabox/wpicon_wide.png
cp -a $1/MBcolors.colorrc $HOME/.config/mabox/jgobthemes/MBcolors.colorrc

if [[ -f "${1}/mvars.txt" ]];then
. $1/mvars.txt
mb-setvar jgmenu_use_icons=${jgmenu_use_icons:-true}
mb-setvar jgmenu_use_borders=${jgmenu_use_borders:-false}
mb-setvar jgmenu_icon_theme=\'${jgmenu_icon_theme:-Numix-Square}\'
mb-setvar menu_font_family=\'${menu_font_family:-Ubuntu Regular}\'
mb-setvar menu_font_size=${menu_font_size:-10}
mb-setvar menu_sep_font_family=\'${menu_sep_font_family:-Ubuntu Bold}\'
mb-setvar menu_sep_font_size=${menu_sep_font_size:-11}
mb-setvar arrow_string=\'${arrow_string:-}\'
mb-setvar arrow_string_left=\'${arrow_string_left:-}\'
mb-setvar jgtools_border=${jgtools_border:-0}
mb-setvar jgtools_padding=${jgtools_padding:-8}
mb-setvar jgtools_radius=${jgtools_radius:-2}
mb-setvar submenu_spacing=${submenu_spacing:-4}
mb-setvar panels_topmargin=${panels_topmargin:-40}
mb-setvar panels_heightpos=${panels_heightpos:-full}
mb-setvar item_height_factor=${item_height_factor:-200}
mb-setvar ok_icon=${ok_icon:-󰞑}
mb-setvar ok_fgcolor=${ok_fgcolor:-#008a00}
mb-setvar warn_fgcolor=${warn_fgcolor:-#FFFFFF}
mb-setvar warn_bgcolor=${warn_bgcolor:-#bd1e24}
mb-setvar logo_in_color=${logo_in_color:-#32B557}
mb-setvar logo_out_color=${logo_out_color:-#F8F8FF}
mb-setvar logo_in_opacity=${logo_in_opacity:-0.7}
mb-setvar logo_out_opacity=${logo_out_opacity:-0.7}
fi
# regenerate_logo
mabox-logo io ${logo_in_opacity}
}
function restoreOBrc(){
    # also terminal theme
    RCFILE="$OBPATH/rc.xml"
    THEMEFILE="$1/obtheme.txt"
    FTEMP=$(mktemp --tmpdir blob.XXXX)
    #MENUFILE="$1/menu.xml"
    #cp "$MENUFILE" "$OBPATH"
    MBCOLORS="$1/MBcolors"
    if [[ -d "$MBCOLORS" ]];then
    cp -a $MBCOLORS/* ~/.themes/MBcolors/openbox-3/
    cp -a $1/MBcolors.colorrc ~/.config/mabox/jgobthemes/
    fi
    TERMINAL_THEME="$1/terminal_theme"
    if [[ -f "$TERMINAL_THEME" ]];then
    cat "$TERMINAL_THEME" >> ~/.theme_history
    fi
    rm -f "$OBBROWSER_ICON_CACHE"
    if [[ $(grep "[OBTHEME]" "$1/settings.cfg" ) ]] &>/dev/null;then
        # backup rc.xml first
        NOW=$(date +"%Y%m%d-%H%M%S")
        RCBKP="$RCFILE.blob.$NOW"
        cp "$RCFILE" "$RCBKP"
        # remove older backups
        for f in $(find $OBPATH -type f|grep .blob. );do
            if [[ $f -ot $RCBKP ]];then
                rm "$f"
            fi
        done
        ## put placeholder in place of <theme> section, write to tempfile
        sed -n "/<theme>/{:a;N;/<\/theme>/!ba;N;s/.*\n/THEMESECTION\n/};p" "$RCFILE" > $FTEMP
        # replace placeholder from theme file
        sed -i "/THEMESECTION/{
            s/THEMESECTION//g
            r $THEMEFILE
        }" $FTEMP
        sed -i '/^$/d' $FTEMP   # remove empty lines
        cp $FTEMP "$RCFILE"     # overwrite rc.xml
        echo -e "\n  rc.xml backed up and edited for OB theme"
        rm -f "$FTEMP"
    fi
}

function restoreTint2(){      # write to tint2 session file
    echo "$1" | awk -F';' '{for(i=1; i<=NF; i++) print $i}' >> "$TINTSESSION"
    killTints
    while read tintline;do
        if [[ ! -z "${tintline// }" ]]; then  # if tintline is not empty (by removing all spaces)
        (tint2 -c "$HOME$tintline" &) &>/dev/null
        sleep 1s
        fi
    done < "$TINTSESSION"
}

function reloadGTK(){ # reload gtk theme after restoring saved config
python2 - <<END
import gtk

events=gtk.gdk.Event(gtk.gdk.CLIENT_EVENT)
data=gtk.gdk.atom_intern("_GTK_READ_RCFILES", False)
events.data_format=8
events.send_event=True
events.message_type=data
events.send_clientmessage_toall()

END
}

function cleanup(){
    if [[ $1 = all ]];then
        if [[ -d $CONFIGDIR ]];then
            rm -rf "$CONFIGDIR"
            echo -e "\n  Usunięto $CONFIGDIR"
        fi
        if [[ -d $CONFIGDIR-BKP ]];then
            mv {"$CONFIGDIR-BKP","$CONFIGDIR"}
            echo -e "\n  Anulowano\n..Temporary $CONFIGDIR restored\n"
        fi
        rm -f /tmp/blob.*
    elif [[ $1 = save ]];then
        saveSettings
    fi
}

function saveSettings(){
    SHOW=0
    if (( $COLS == 0 ));then
        SELECT="FALSE"
    else
        SELECT="TRUE"
    fi
    COLUMNS=(\
        $SELECT "$PICKOB" \
        $SELECT "$PICKGTK" \
        $SELECT "$PICKCONKY" \
        $SELECT "$PICKTINT" \
        $SELECT "$PICKBG" \
        )
       # tymczasowo usuniete -> $SELECT "$PICKDMENU" \
    SLOOP=1
    while (( $SLOOP == 1 ));do
        CHOICE=$($DIALOGDEC --list --checklist \
            --title="$CHOOSE_WHAT_TO_SAVE" \
            --button="$CHOOSE_ALL" \
            $CANCEL $OK \
            --height=280 \
            --column="$CHOOSE_SELECT" --column="$CHOOSE_CONFIG" "${COLUMNS[@]}" \
            2>/dev/null )
            ret=$?
        if (( $ret == 1 )); then # cancel button pressed
            COLS=0
            cleanup all
            restoreSettings
        elif (( $ret == 2 ));then
            COLS=1
            saveSettings
            SHOW=1
        else
            if [[ ! $CHOICE ]] ; then # entry field is empty, so try again
                RET=$($DIALOG  --image="dialog-question" \
                --text="$CHOOSE_SOMETHING" \
                $EXIT $OK \
                --width=300 \
                2>/dev/null )
                if (( $? == 1 ));then
                    cleanup all
                fi
            else
                i=0
                retChoice=()
                OIFS=$IFS # save Internal Field Separator
                IFS=$"|" # separator is "|" in returned choices
                # dialog return is in format 'TRUE|value|\nTRUE|value'
                for ret in $CHOICE; do
                    if [[ $(echo $ret | grep TRUE) ]] &>/dev/null;then
                        continue
                    fi
                    retChoice[$i]="$ret"
                    i=$(($i+1))
                done
                IFS=$OIFS # reset IFS back to default
                len=${#retChoice[@]}
                for (( i=0; i<${len}; i++ ));do
                    item="${retChoice[$i-1]}"
                    case "$item" in
                        "$PICKOB"   )   getOBtheme
                                        ;;
                        "$PICKGTK"  )   getGTKtheme
                                        ;;
                        "$PICKCONKY")   getConky
                                        ;;
                        "$PICKTINT" )   getTint
                                        ;;
                        "$PICKBG"   )   getBg
                                        ;;
                        *           )   echo -e "\n  Nieznana wartość!" 2>&1
                                        exit 1
                                        ;;
                    esac
                done
                #save menu/panel settings
                getMenuPanel
                SLOOP=0
            fi
        fi
    done
    if (( $SHOW == 0 ));then
        COLS=0      # reset columns unselected
        TXT="$FILES_TO_SAVE"
        TXT2=$(cat "$LISTMSG")
        NEW=$($DIALOG --text="$TXT$TXT2") 2>/dev/null
        ret=$?
        if (( $ret == 1 ));then
            cleanup all
            restoreSettings
        else
            echo "$ANS" > "$CURSESSION"     # replace entry in saved config flag file
        fi
    fi
}

function ViewRestoreDialog(){  #   Display saved theme collections
    getSet          # get name of latest set BLOB config
    if (( $NUMDIRS == 0 ));then   # no saved configs; go back to Intro dialog
        Intro
    fi
    DLGLIST=""
    setARR=()
    namesARR=()
    thumbsARR=()
    i=0
    for dir in "$CONFIGPATH"/* ;do
        if [[ -d $dir ]];then
            if [[ -e $dir/settings.cfg ]];then
                d=$(echo $dir | sed -e 's/ /_/g')    # replace any spaces in dir name
                namesARR[$i]="<big>$(basename $d)</big>" # add theme collection name to array
                d=${d##*/}  # get directory name
                # Get name of current session, set icon for TRUE/FALSE
                if [[ $SET = $d ]];then
                    setARR[$i]="gtk-yes"
                else
                    setARR[$i]="gtk-no"
                fi
                IMGTHUMB="Brak"     # Placeholder if no thumbnail found
                f="$dir"/*"-thumb.jpg"
                if [[ $f ]];then
                    IMGTHUMB="$f"
                fi
                thumbsARR[$i]="$IMGTHUMB"
                CONFIGS="\""
                while read line;do
                    CONFIGS="$CONFIGS $line\n"
                done < "$dir/LISTMSG.txt"
                CONFIGS="$CONFIGS\""
                configARR[$i]="$CONFIGS" # add saved configs to array
            fi
            i=$(($i+1))
        fi
    done
    for ((j=0; j<${#namesARR[*]}; j++));do
        DLGLIST="$DLGLIST ${setARR[j]} ${namesARR[j]} ${thumbsARR[j]}"
    done
}

function restoreSettings(){
    ViewRestoreDialog
    FPATH=""
    LOOP=1
    while [[ $LOOP ]] ;do
        CONFIG=$($DIALOGDEC --list --title="$TITLE" --image=preferences-desktop-theme\
            --text="$MAIN_TEXT" \
            --separator=" " \
            --button="$ABOUT" \
            --button="$VIEW_IMG" --button="$ADD" \
            --button="$DELETE" --button=$RESTORE $EXIT \
            --always-print-result \
            --width=$W --height=$H --center --image-preview \
            --expand-column=3 \
            --column="$ACTIVE":IMG \
            --column="$NAME":TEXT \
            --column="$SCREEN_SHOT":IMG \
            $DLGLIST \
            2>/dev/null )
        RET=$?
        if [[ $CONFIG ]];then
            DIR=$(echo "$CONFIG" | awk -F'[>|<]' '{print $3}' )
            FPATH="$CONFIGPATH/$DIR"
        fi
        case $RET in
            0)  SAVED="$FPATH/LISTMSG.txt"
                TEXT="$RESTORING_CONF"
                TEXT="$TEXT$(cat $SAVED)"
                $DIALOG "$T$TEXT" "$CANCEL" "$OK" 2>/dev/null
                if (( $? == 0 ));then
                    echo $(basename $FPATH) > "$CURSESSION"
                    break
                fi
                ;;
            1)  exit 0
                ;;
            2)  if [[ ! $CONFIG ]];then
                    $DIALOG --text="$CHOOSE_BEFORE_DELETE" "$EXIT" "$OK" 2>/dev/null
                    if (( $? == 0 ));then
                        continue
                    else
                        exit 0
                    fi
                fi
                TEXT="$DELETE_FOR_SURE"
                $DIALOG "$T$TEXT" "$CANCEL" "$OK" 2>/dev/null

                if (( $? == 0 ));then
                    rm -rf "$FPATH"
                    rm "$FPATH.jpg"
                    echo -e "\n$DIR DELETED"
                    currentsession=$(cat $CURSESSION)
                    fpath=$(basename $FPATH)
                    if [[ $currentsession = $fpath ]];then
                        echo "" > "$CURSESSION"
                    fi
                    restoreSettings
                else
                    continue
                fi
                ;;
            3)  setName
                saveSettings
                getScrot
                $DIALOG --text="$SETTINGS_SAVED <b>$ANS</b>" --image="gtk-save" "$OK" 2>/dev/null
                if [[ -d $CONFIGDIR-BKP ]];then
                    rm -rf "$CONFIGDIR-BKP"
                    echo -e "\n  Temporary $CONFIGDIR deleted\n"
                fi
                restoreSettings
                ;;
            4)  # show screenshot in image viewer
                SEL=$(echo "$CONFIG" | awk -F'[>|<]' '{print $3}' )
                if [[ $SEL ]];then
                    img="$CONFIGPATH/$SEL.jpg"
                    $IMGCMD "$img"
                else
                    $DIALOG --text="$CHOOSE_IMAGE" 2>/dev/null
                fi
                restoreSettings
                ;;
            5)  Intro
                ;;
            *)  if (( $RET == 252 ));then
                    echo -e "\n  Exited with \"ESC\" key"
                else
                    echo -e "\n  Error= $RET" 2>&1
                fi
                exit 1
                ;;
        esac
    done
    SETCFG="$FPATH/settings.cfg"
    # Get chosen saved configs and restore them
    # kill conkys and tint2s, in case saved config doesn't include them
    if [[ $(pidof conky) ]];then
        killall conky
    fi
    if [[ $(pidof tint2) ]];then
        killall tint2
    fi
    #Restore MenuPanels
    restoreMenuPanel "$FPATH"
    while read line;do
        TAG=$(echo $line | awk '{print $1}')
        VAL=$(echo $line | awk '{print $2}')
        case "$TAG" in
            "[TINT2]"       )   checkTint2zen # see if bl-tint2zen installed
                                if (( $TZEN == 1 ));then
                                    > "$TINTSESSION" # overwrite tint2 session file
                                fi
                                TINTCMD=$(echo $line | cut -d ' ' -f2-)
                                restoreTint2 "$TINTCMD"
                                ;;
            "[CONKY]"       )   checkConkyzen # see if bl-conkyzen installed
                                if (( $CZEN == 1 ));then
                                    > "$CONKYSESSION" # overwrite conky session file
                                fi
                                CONKYCMD=$(echo $line | cut -d ' ' -f2-)
                                # write to conky session file...
                                echo $CONKYCMD | awk -F';' '{for(i=1; i<=NF; i++) print $i}' >> "$CONKYSESSION"
                                if [ -d "$FPATH/conky" ];then
                                cp -a $FPATH/conky/* ~/.config/conky/
                                fi
                                killall conky
                                source "$CONKYSESSION"
                                ;;
            "[GTK]"         )   restoreGTK "$FPATH"
                                reloadGTK
                                ;;
            "[OBTHEME]"     )   restoreOBrc "$FPATH"
                                ;;
            "[BACKGROUND]"  )   if [[ $VAL = FEH ]];then
                                    cp "$FPATH/.fehbg" "$HOME"
                                    source "$HOME/.fehbg"
                                else
                                    cp "$FPATH/bg-saved.cfg" "$NITRODIR"
                                    nitrogen --restore
                                fi
                                ;;
            *               )   echo -e "  Unknown value!" 2>&1
                                restoreSettings
                                ;;
        esac
    done < "$SETCFG"
    openbox --reconfigure
    #mb-regenerate-menu
    setXsettingsd
    restoreSettings
    
}

### END FUNCTIONS ######################################################
# test for blobthemes config directory, create if it doesn't exist
mkdir -p "$CONFIGPATH"
# create file to hold most recent saved configuration name
if [[ ! -f $CURSESSION ]] &>/dev/null;then
    touch "$CURSESSION"
fi
countMonitors
getSet
if (( $NUMDIRS == 0 ));then
    Intro
else
    restoreSettings
fi
exit 0
