#!/bin/bash

	version=0.8

	if [[ $(which avatar-factory) != /usr/local/bin/avatar-factory ]]; then
		cd "${0%/*}"
		avatar_factory_PATH=$(pwd)/Avatar-Factory
		cd "$OLDPWD"
	else
		avatar_factory_PATH=/usr/local/share/avatar-factory
	fi

	OLDIFS=$IFS

	app_config=$HOME/.avatar-factory
	gui_config=$HOME/.avatar-factory/avatar-factory
	app_icon=$avatar_factory_PATH/avatar-factory.png
	save_as=avatars

    #old config:
	if [[ -f $app_config/avatar-launcher ]]; then
		grep 'bookmarks' $app_config/avatar-launcher > $app_config/general
		rm $app_config/avatar-launcher
	fi

	default_secondary_options () {
		case $SOURCE_type in
			bookmarks )
				case $bookmarks in
					firefox | epiphany )
						avatar_title=$(echo "$SOURCE_item" | cut -d\> -f3 | cut -d\< -f1 | sed -e 's/&quot;/"/g' -e 's|/|-|g' -e "s/&#39;/'/g")
						URL=$(echo "$SOURCE_item" | cut -d\" -f2)
					;;
					opera )
						avatar_title=$(echo "$SOURCE_item" | sed -e 's/^.*NAME=//' -e 's/<<<.*$//' -e 's/&quot;/"/g' -e 's|/|-|g' -e "s/&#39;/'/g")
						URL=$(echo "$SOURCE_item" | sed -e 's/^.*<<<//' -e 's/^.*URL=//')
					;;
					disabled )
						avatar_title=$(echo "$SOURCE_item" | sed -e 's/.*|//')
						URL=$(echo "$SOURCE_item" | sed -e 's/|.*//')
				esac
			;;
			folders )
				avatar_title=${SOURCE_item##*/}
				avatar_filename=$(echo $SOURCE_item | sed 's/\//\_/g')
				avatar_name=$index.$avatar_title
				URL=file://$SOURCE_item
				icon_NAME=$avatar_filename
		esac
	}

	set_folder_structure () {
		case $SOURCE_item in
			'<FOLDER>'* | '</FOLDER>'* )
				case $SOURCE_type in
					folders | files )
						folder_node=$(echo "$SOURCE_item" | sed 's/<FOLDER>//')
					;;
					bookmarks )
						case $SOURCE_item in
							'<FOLDER>'* )
								folder_number=$((folder_number+1))
								folder_structure_plus[$folder_number]=$(echo "$SOURCE_item" | cut -d\> -f3 | sed 's|</H3||')
							;;
							'</FOLDER>'* )
								if [[ folder_number -gt 0 ]]; then
									folder_number=$((folder_number-1))
								fi
						esac

						folder_structure=
						for ((i=1;i<=$folder_number;i+=1)); do
							folder_structure=$folder_structure${folder_structure_plus[$i]}/
						done
				esac

				if [[ $folders = 2 ]]; then
					folder_structure=${folder_structure#*/}
				fi

				folder_structure=${folder_structure%/}

				continue
			;;
			* )
				case $SOURCE_type in
					folders | files )
						if [[ $save_as = html ]]; then
							folder_structure=${SOURCE_item%/*}
						else
							folder_structure=$(echo "$SOURCE_item" | sed -e "s|^$folder_node||")
							folder_structure=${folder_structure%/*}
							folder_structure=${folder_structure#/}
						fi
					;;
				esac
		esac
	}

	nautilus_icon_size () {
	    #set folder:
		if [[ $folders ]]; then
			folder2save_backup=$folder2save
			if [[ -n $folder_structure ]]; then
				folder2save=$folder2save/$folder_structure
			fi
		fi

		path_encoded=$(echo "$folder2save/$avatar_filename.desktop" | sed "s|'|\\\'|g")
		path_encoded=$(python -c "import  gnomevfs; print gnomevfs.get_uri_from_local_path('$path_encoded')")

		folder_encoded=$(echo "${path_encoded%/*}" | sed -e 's/%/%25/g' -e 's|/|%2F|g')
		file_encoded=$(echo "${path_encoded##*/}" | sed -e 's/&/%26/g' -e "s/'/%27/g" -e 's/(/%28/g' -e 's/)/%29/g')

	    #save metafile:
		if [[ $previous_folder_encoded && $previous_folder_encoded != $folder_encoded ]]; then
			chmod +w $HOME/.nautilus/metafiles/$previous_folder_encoded.xml
			echo "$nautilus_metafile </directory>" | sed '/^$/d' | tr '\n' ' ' > $HOME/.nautilus/metafiles/$previous_folder_encoded.xml
			chmod -w $HOME/.nautilus/metafiles/$previous_folder_encoded.xml
		fi

	    #load metafile:
		if [[ $previous_folder_encoded != $folder_encoded ]]; then
			if [[ -f "$HOME/.nautilus/metafiles/$folder_encoded.xml" ]]; then
				nautilus_metafile=$(cat "$HOME/.nautilus/metafiles/$folder_encoded.xml" | sed -e 's/<file name="/\n<file name="/g' -e 's|</directory>||g')
			else
				nautilus_metafile='<?xml version="1.0"?><directory>'
			fi
		fi

	    #edit metafile:
		if [[ -f "$folder2save/$avatar_filename.desktop" ]]; then
			nautilus_metafile=$({ echo "$nautilus_metafile" | grep -v "<file name=\"$file_encoded\"" ; echo "<file name=\"$file_encoded\" icon_scale=\"$icon_size\"/>" ; })
		fi

	    #save metafile:
		if [[ $index = $((total_lines+1)) ]]; then
			chmod +w $HOME/.nautilus/metafiles/$folder_encoded.xml
			echo "$nautilus_metafile </directory>" | sed '/^$/d' | tr '\n' ' ' > $HOME/.nautilus/metafiles/$folder_encoded.xml
			chmod -w $HOME/.nautilus/metafiles/$folder_encoded.xml
		fi

		previous_folder_encoded=$folder_encoded

	    #restore folder:
		if [[ $folders ]]; then
			folder2save=$folder2save_backup
		fi
	}

	create_html () {
		#group
		if [[ $folder_structure != $folder_structure_back ]]; then

			if [[ $web_line && $folder_structure != $folder_structure_back ]]; then

				web_sidebar[$web_line]="			<a href=\"$grabber_name.html#$group_num\"><div id=\"sidebarlink\">$group_name ($group_size)</div></a>"
				avatar_web[$((++web_line))]="			</div>"
				group_size=
			fi

			((group_num++))
			[[ $group_id = a ]] && group_id=b || group_id=a

			group_name=${folder_structure##*/}

			avatar_web[$((++web_line))]="			<div id=\"group_content_$group_id\">"
			avatar_web[$((++web_line))]="				<div id=\"group_$group_id\"><a name=\"$group_num\"></a> $group_name</div>"

			folder_structure_back=$folder_structure
		fi

		#build icon view
		((group_size++))
		((total_size++))

		[[ $Link_or_Application = Link ]] && Launcher_or_URL=$URL || Launcher_or_URL=avatar-factory://launch/$grabber_name/$total_size

		avatar_web[$((++web_line))]="				<a href=\"$Launcher_or_URL\"><img class=\"icon\" title=\"$avatar_name\" src=\"file://$icons_PATH/$(echo "$icon_NAME" | sed -f $avatar_factory_PATH/uri_encode).png\"></img></a>"

		#launchers
		web_launcher[$total_size]="$total_size ${Launcher#* }"
	}


################################
#  Launcher
################################

	case $1 in
		avatar-factory://launch/* )

			index=${1##*/}
			grabber_name=${1%/*} grabber_name=${grabber_name##*/}
			Launcher=$(grep "^$index " -m 1 $app_config/web/$grabber_name.launchers) Launcher=${Launcher#* }

			eval avatar-factory $Launcher

			exit
		;;
		-al | --avatar-launcher )

				shift
				if [[ ${1##*.} = desktop || $1 = --launcher ]] ; then
					while [ "$1" != "" ]; do
						case $1 in
							--launcher )
								shift
								set_launcher=$1
							;;
							* )
							    #run & exit:
								eval $(cat "$1" | grep '^Exec=' | cut -d= -f2 | sed 's/--DND//') --launcher "$set_launcher"&
						esac
						shift
					done

					exit
				fi

				launcher_name=$1
				shift

				while [ "$1" != "" ]; do
					case $1 in
						--DND )
							while [ "$1" != "" ]; do
								shift
								DND[$((++num))]=$1
							done

							num=
						;;
						--icon )
							shift
							icon=$1
						;;
						--URL )
							shift
							URL=$1
						;;
						--avatar )
							shift
							avatar_path=$1
						;;
						--name )
							shift
							avatar_name=$1
						;;
						--title )
							shift
							avatar_title=$1
						;;
						--launcher )
							shift
							set_launcher=$1
						;;
						* )
							number=$((number + 1))
							X[$number]=$1
					esac
					shift
				done

			  #set cover:
				case ${DND[1]} in
					*.[jJ][pP][gG] | *.[pP][nN][gG] | *.[gG][iI][fF] )
						grabber_picture=${DND[1]}
						grabber_picture2=${DND[2]}
						grabber_picture3=${DND[3]}
						avatar_filename=${icon##*/}
						avatar_filename=${avatar_filename%.*}
						icons_PATH=${icon%/*}
						theme_name=${icons_PATH##*/}
						icon_NAME=$avatar_filename

					  #create icon:
						if [[ -f $avatar_path ]]; then
							icon_NAME_back=$icon_NAME

							if [[ -f $icons_PATH/$icon_NAME.png ]]; then
								if [[ $(find "$icons_PATH/$icon_NAME._TEMP_"*.png) ]]; then
									num=$(find "$icons_PATH/$icon_NAME._TEMP_"*.png | sed -e 's/.*_//' -e 's/\..*$//' | tail -n 1)
									rm "$icons_PATH/$icon_NAME._TEMP_"*.png
								fi

								icon_NAME=$avatar_filename._TEMP_$((++num))
							fi
						fi

						$avatar_factory_PATH/themes/$theme_name "$icons_PATH/$icon_NAME.png" "$grabber_picture" "$grabber_picture2" "$grabber_picture3"

						if [[ -f $avatar_path ]]; then
							avatar_file=$(sed -e '/^Icon=/d' -e "/Exec=/a\Icon=$icons_PATH/$icon_NAME.png" "$avatar_path")
							echo "$avatar_file" > "$avatar_path"

							cp "$icons_PATH/$icon_NAME.png" "$icons_PATH/$icon_NAME_back.png"
						fi

						exit
					;;
				esac

			  #load launcher:
				. "$avatar_factory_PATH/launchers/$launcher_name"

				launcher_options

			  #user Options
				if [ -f $app_config/grabbers/$launcher_name ]; then
					. $app_config/grabbers/$launcher_name
				fi

			  #avatar Launcher
				if [[ -n $set_launcher ]]; then
					launcher=$set_launcher
				fi

				launcher

				exit
	esac

################################
#  GUI
################################

	. $avatar_factory_PATH/gui

	if [ "$#" = "0" ]; then
		gui --main
		exit
	fi

################################
#  Get Primary Options
################################

	number=0

	while [ "$1" != "" ]; do
		case $1 in
			-g | --grabber | --thumbnailer )
					if [ $2 = --gui ] ; then
						grabber_name=$(gui --grabber)
						if [[ $? = 1 ]]; then
							exit
						fi
					elif [ -f "$avatar_factory_PATH/grabbers/$2" ] ; then
						grabber_name=$2
					else
						echo "$2 grabber does not exist"
						exit 1
					fi

					. "$avatar_factory_PATH/grabbers/$grabber_name"
					grabber_primary_options

				    #user config:
					if [[ -f "$app_config/grabbers/$grabber_name" ]]; then
						eval $(grep '^set_name=|^Link_or_Application=|^theme_name=' "$app_config/grabbers/$grabber_name")
					fi

				    #thumbnailer:
					if [[ $1 = --thumbnailer ]]; then
						shift
						shift

						. $avatar_factory_PATH/thumbnailer

						exit
					else
						shift
					fi

				    #bookmarks:
					if [[ $SOURCE_type = bookmarks ]]; then
						if [[ -f "$app_config/general" ]]; then
							eval $(grep '^bookmarks=' "$app_config/general" | tail -n 1)
						fi

						if [[ -z $bookmarks ]]; then
							bookmarks=firefox
						fi
					fi
			;;
			--config )	shift
					. "$1"
			;;
			-go | --grabber-options )
					shift
					grabber_options=$1
			;;
			-lg | --list-grabbers )
					find -L $avatar_factory_PATH/grabbers/ -maxdepth 1 -type f | sed -e "s|$avatar_factory_PATH/grabbers/||g"  -e /~/d | sort
					exit
			;;
			-t | --theme )
					shift
					if [ $1 = --gui ] ; then
						theme_name=$(gui --theme)
						if [[ $? = 1 ]]; then
							exit
						fi
					elif [ -f "$avatar_factory_PATH/themes/$1" ] ; then
						theme_name=$1
					else
						echo "$1 theme does not exist"
						exit 1
					fi
			;;
			-lt | --list-themes )
					find -L $avatar_factory_PATH/themes/ -maxdepth 1 -type f | sed -e "s|$avatar_factory_PATH/themes/||g"  -e /~/d | sort
					exit
			;;
			-wt | --web-theme )
					shift
					if [ -f $avatar_factory_PATH/web-themes/$1.css ] ; then
						if [[ -f $app_config/web/styles.css ]]; then
							rm $app_config/web/styles.css
						fi
						cp $avatar_factory_PATH/web-themes/$1 $app_config/web/styles.css
					else
						echo "$1 theme does not exist"
						exit 1
					fi

					[[ -z $2 && -z $grabber_name ]] && exit
			;;
			-lwt | --list-web-themes )
					find -L $avatar_factory_PATH/web-themes/ -maxdepth 1 -type f | sed -e "s|$avatar_factory_PATH/web-themes/||g"  -e /~/d | sort
					exit
			;;
			-r | --rating )
					echo 'Rating is not working yet'
					exit
					rating_name=default
					shift
					rating_value=$1
			;;
			-rt | --rating-theme )
					echo 'Rating is not working yet'
					exit
					shift
					if [ $1 = --gui ] ; then
						rating_theme=$(gui --rating)
						if [[ $? = 1 ]]; then
							exit
						fi
					elif [ -f "$avatar_factory_PATH/themes/$1" ] ; then
						rating_theme=$1
					else
						echo "$1 theme does not exist"
						exit 1
					fi
			;;
			-lrt | --list-rating-themes )
					find -L $avatar_factory_PATH/themes/ -maxdepth 1 -type f | sed -e 's|/usr/local/share/avatar-factory/ratings/||g'  -e /~/d | sort
					exit
			;;
			-f | --force )
					force_icon_build=yes
			;;
			--name )
					shift
					if [ $1 = --gui ] ; then
						set_name=$(gui --name)
						if [[ $? = 1 ]]; then
							exit
						fi
					else
						set_name=$1
					fi
			;;
			--type )
					shift
					Link_or_Application=$1
					if [ $1 = --gui ] ; then
						Link_or_Application=$(gui --type)
						if [[ $? = 1 ]]; then
							exit
						fi
					fi
					case $Link_or_Application in
						0 ) Link_or_Application=Link
				       				        ;;
						1 ) Link_or_Application=Application
					       				;;
						* ) echo "invalid type" exit 1
					esac
			;;
			--gui-progress )
					gui_progress=gui_progress
			;;
			--general-progress )
					general_progress=general_progress
			;;
			--widget )
					killall music-widget >& /dev/null
					/usr/local/share/avatar-factory/music-widget&
					exit
			;;
			--widget-quit )
					killall music-widget
					exit
			;;
			--picture-gui )
					picture_gui=picture_gui
			;;
			--comic-bookmark )
					comic_bookmark=comic_bookmark
			;;
			--comic-bookmark=* )
					comic_bookmark=comic_bookmark
					comic_bookmarked_page=${1##*=}
			;;
			--delete )
					delete=yes
			;;
			--folders )
					folders=1

					if [[ -z $grabber_name ]]; then
						echo --folder option must be set after the grabber
						exit 1
					elif [[ $SOURCE_type = bookmarks && $bookmarks != firefox ]]; then
						echo "ERROR: --folder option only works for firefox bookmarks"
						folders=
					fi
			;;
			--folders-2 )
					folders=2

					if [[ -z $grabber_name ]]; then
						echo --folder option must be set after the grabber
						exit 1
					elif [[ $SOURCE_type = bookmarks && $bookmarks != firefox ]]; then
						echo "ERROR: --folder option only works for firefox bookmarks"
						folders=
					fi
			;;
			--icon-size )
					shift
					case $1 in
						[0-9][0-9] | [0-9] )
							icon_size=$1
						;;
						* )	echo "Wrong value: $1"
							exit 1
					esac
			;;
			--web )
					save_as=html
					set_name=2
					folders=1
			;;
			-h | --help )
					{
						if [[ -n $grabber_name ]]; then
							echo ""
							echo "Name:	$grabber_name"
							echo "Theme:	$theme_name"
							echo "Type:	$Link_or_Application"
							echo "Source:	$SOURCE_type"
							echo ""

							if [[ $grabber_name != avatar ]]; then
								echo "Config file:"
								echo "	$app_config/grabbers/$grabber_name"
								echo ""
							fi

							case $SOURCE_type in
								folders )
									echo "Example: avatar-factory -g $grabber_name source destination"
									echo "Example: avatar-factory -g $grabber_name "
									echo "	Source must be one or more folders. If there is no destination it wil try to use the config file."
								;;
								files )
									if [ $grabber_name = avatar ] ; then
										echo "Example: avatar-factory -g $grabber_name source options"
										echo "	Source must be one or more avatars."
									else
										echo "Example: avatar-factory -g $grabber_name source destination"
										echo "Example: avatar-factory -g $grabber_name "
										echo "	Source must be one or more files or folders. If there is no destination it wil try to use the config file."
									fi
								;;
								bookmarks )
									echo "Example: avatar-factory -g $grabber_name source destination"
									echo "Example: avatar-factory -g $grabber_name destination"
									echo "Example: avatar-factory -g $grabber_name "
									echo "	Source can be firefox, epiphany, opera$([[ $grabber_name = anobii ]] && echo \ or ~username). If there is no destination it will try to use the config file. If there is no source the bookmarks for the default browser will be used."
									echo ""
									echo "To change the default bookmark source (firefox) edit:"
									echo "	~/.avatar-factory/general"
									echo ""
									echo "	and add:"
									echo "		bookmarks=\"your-web-browser\""
									echo "		(firefox , epiphany or opera)"
									echo ""
									echo "	For firefox 3 do the following:"
									echo "		In the address bar type \"about:config\" Find the setting \"browser.bookmarks.autoExportHTML\" double click it to change the boolean entry to true."
							esac

							cat "$avatar_factory_PATH/help/$grabber_name"
						else
							cat "$avatar_factory_PATH/help/avatar-factory"
						fi
					} | fmt -s
					exit
			;;
			--version | -v )
					echo $version
					exit
			;;
			* )
					SOURCE_input[$number]=$1
					number=$((number + 1))
		esac
		shift
	done

    #no grabber:
	if [[ -z $grabber_name ]]; then
		echo "you must select a grabber"
		exit 1
	fi

    #no destination folders:
	if [[ -z "${SOURCE_input[*]}" && $save_as != html ]]; then
		if [[ -f "$app_config/grabbers/$grabber_name" ]]; then
			eval $(grep 'SOURCE_input' "$app_config/grabbers/$grabber_name")
			echo "No destination specified: using configuration file"
		else
			echo "No destination specified and no config file for \"$grabber_name\" grabber"
			exit
		fi
	fi

    #set icon size:
	if [[ -n $icon_size ]]; then
		case ${#icon_size} in
			1 )
				if [[ $icon_size = 0 ]]; then
					icon_size=
				else
					icon_size=0.${icon_size:1:1}
				fi
			;;
			2 )
				icon_size=${icon_size:0:1}.${icon_size:1:1}
		esac
	fi

################################
#  Set Folder to Save
################################

	number=$((${#SOURCE_input[*]}-1))

	if [ $grabber_name = avatar ] ; then
		if [ "${SOURCE_input[$number]}" = --gui ] ; then
			SOURCE_input[$number]=
			max_number=$((number-1))
		else
			max_number=$number
		fi
	elif [[ $save_as = html || $save_as = nautilus_icons ]]; then
		max_number=$number
	elif [ "${SOURCE_input[$number]}" = --gui ] ; then
		folder2save=--gui
		SOURCE_input[$number]=
		max_number=$((number-1))
	elif [ -d "${SOURCE_input[$number]}" ] ; then
		cd "${SOURCE_input[$number]}"
		folder2save=$(pwd)
		cd "$OLDPWD"
		SOURCE_input[$number]=
		max_number=$((number-1))
	else
		echo "${SOURCE_input[$number]} does not exist or it is not a directory"
		exit 1
	fi

################################
#  Make the list of items
################################

	case $SOURCE_type in
		folders )
			if [[ "${SOURCE_input[*]}" = "" ]]; then
				echo "There is no source folder"
				exit 1
			fi

			for number in $(seq 0 "$max_number"); do
				if [ "${SOURCE_input[$number]}" = --gui ] ; then
					SOURCE_input[$number]=$(gui --select-folders)
					if [[ $? = 1 ]]; then
						exit
					fi
				elif ! [ -d "${SOURCE_input[$number]}" ] ; then
					echo "${SOURCE_input[$number]} is invalid"
					exit 1
				fi
			done

		;;
		files )
			if [[ "${SOURCE_input[*]}" = "" ]]; then
				echo "There is no source file"
				exit 1
			fi

			for number in $(seq 0 "$max_number"); do
			    #gui:
				if [ "${SOURCE_input[$number]}" = --gui ] ; then
					SOURCE_list[$number]=$(gui --select-files)
					if [[ $? = 1 ]]; then
						exit
					fi
			    #file input:
				elif [[ -f "${SOURCE_input[$number]}" ]] ; then
					if [[ "${SOURCE_input[$number]}" = */* ]]; then
						cd "${SOURCE_input[$number]%/*}"
						SOURCE_list[$number]=$(pwd)/${SOURCE_input[$number]##*/}
						cd "$OLDPWD"
					else
						SOURCE_list[$number]=$(pwd)/${SOURCE_input[$number]}
					fi

			    #folder input:
				elif [ -d "${SOURCE_input[$number]}" ] ; then
					cd "${SOURCE_input[$number]}"
					SOURCE_input=$(pwd)
					cd "$OLDPWD"

					echo "Building list of files to process..."
					SOURCE_list[$number]="<FOLDER>$SOURCE_input
$(find -L "$SOURCE_input" -type f ! -path "$SOURCE_input*/.*" -print | sort)"

			    #invalid input:
				else
					echo "${SOURCE_input[$number]} is invalid"
					exit 1
				fi

			    #apply filter:
				SOURCE_filter=$(echo $SOURCE_filter | sed -e s/,$// -e 's/,/\$|/g' -e s/$/\$/)
				SOURCE_list[$number]=$(echo "${SOURCE_list[$number]}" | egrep -i $SOURCE_filter)

			    #insert a blank line:
				if [[ "$number" != "$max_number" && -n ${SOURCE_list[$number]} ]]; then
					SOURCE_list[$number]="${SOURCE_list[$number]}
"
				fi
				shift
			done
		;;
		bookmarks )
			case "$SOURCE_input" in
				~[!/]* )
					account=${SOURCE_input#\~}

					[[ $account_password ]] && read -sp "Password: " password

					echo "Building list of links to process..."

					SOURCE_list=$(grabber_account_grabber $account $password)
					bookmarks=disabled
				;;
				"" | --gui | firefox | epiphany | opera )
					if [[ $SOURCE_input = --gui ]]; then
						SOURCE_input[$number]=
					elif [[ $SOURCE_input ]]; then
						bookmarks=$SOURCE_input
					fi

					echo "Building list of links to process..."

					SOURCE_filter=$(echo $SOURCE_filter | sed -e 's/,$//' -e 's/,/|/g')

					case $bookmarks in
						firefox )
							SOURCE_list=$(egrep -i "<DT><H3|</DL>|$SOURCE_filter" "$(find $HOME/.mozilla/firefox/ -maxdepth 2 -name 'bookmarks.html')" | sed -e 's/.*<DT><H3/<FOLDER>/' -e 's|.*</DL>|</FOLDER>|')
						;;
						epiphany )
							SOURCE_list=$(grep -A1 '<item rdf:about="http' $HOME/.gnome2/epiphany/bookmarks.rdf  | grep -v ^--$ | sed '/">.*/N;s/\n */ /' | egrep -i "$SOURCE_filter")
						;;
						opera )
							SOURCE_list=$(grep -B1 'URL=' $HOME/.opera/opera6.adr | grep -v ^--$ | sed -e 's/\(NAME=.*\)/\1<<</' -e '/<<<$/N;s/\n */ /' | egrep -i "$SOURCE_filter")
						;;
						* )
							echo "invalid web browser: $bookmarks"
							exit 1
					esac
				;;
				* )
					echo "$1 is invalid"
					exit
			esac
		;;
		* )
			echo "invalid source type: $1"
	esac

################################
#  Folder to save GUI:
################################

	if [ "$folder2save" = --gui ] ; then
		folder2save=$(gui --select-destination)
		if [[ $? = 1 ]]; then
			exit
		fi
	fi

	case $SOURCE_type in
		folders )
			echo "Building list of folders to process..."

			for number in $(seq 0 "$max_number"); do
				cd "${SOURCE_input[$number]}"
				SOURCE_input=$(pwd)
				cd "$OLDPWD"

				SOURCE_list[$number]="<FOLDER>$SOURCE_input
"
				if [[ -n $gui_progress ]]; then
					SOURCE_list[$number]=${SOURCE_list[$number]}$(find -L "$SOURCE_input" -type d ! -path "$SOURCE_input*/.*" -print | tee >( gui --progress-folders ) | sed -e 's|\(.*\)/\(.*\)/\(.*\)|\1// 0/\2/\3|' | sort -n | sed 's|// 0/|/|')
					if [[ $? = 1 ]]; then
						exit
					fi
				else
					SOURCE_list[$number]=${SOURCE_list[$number]}$(find -L "$SOURCE_input" -type d ! -path "$SOURCE_input*/.*" -print | sed -e '/~$/d' -e 's|\(.*\)/\(.*\)/\(.*\)|\1// 0/\2/\3|' | sort -n | sed 's|// 0/|/|')
				fi

				if [[ "$number" != "$max_number" ]]; then
					SOURCE_list[$number]="${SOURCE_list[$number]}
"
				fi
			done
	esac

################################
#  Prepare to enter the factory
################################

	number=1
	index=1
	set_index=
	total_lines=$(echo "${SOURCE_list[*]}" | egrep -v '<FOLDER>|</FOLDER>' | wc -l)
	icons_PATH="$HOME/.avatar-factory/icons/$grabber_name/$theme_name"

	if [[ -n $folders ]]; then
		SOURCE_list=$(echo "${SOURCE_list[*]}")
	else
		SOURCE_list=$(echo "${SOURCE_list[*]}" | egrep -v "<FOLDER>|</FOLDER>")
	fi

	exec < <(echo "$SOURCE_list")

################################################################
#                     ENTER THE FACTORY                        #
################################################################

while read -r SOURCE_item ; do

	#################################
	#      Set Folder structure     #
	#################################

	if [[ -n $folders ]]; then
		set_folder_structure
	fi

	#################################
	#   Get info about each avatar  #
	#################################

	default_secondary_options

    #Grabber specific opitons:
	grabber_picture=
	grabber_secondary_options

	[[ $? = 1 ]] && exit

	#################################
	#    User Secondary Options     #
	#################################

	if [ -n "$set_name" ]; then
		case $set_name in
			0 )	avatar_name=
				;;
			1 )	avatar_name=${set_index+$index}
				;;
			2 )	avatar_name=$avatar_title
				;;
			3 )	avatar_name=${set_index+$index}.$avatar_title
				;;
			* )	echo "invalid title"
				exit 1
		esac
	fi

	#################################
	#         CREATE ICON           #
	#################################

	if [[ -n $force_icon_build || ! -f "$icons_PATH/$icon_NAME.png" || $SOURCE_type = folders && "$SOURCE_item" -nt "$icons_PATH/$icon_NAME.png" ]]; then

		if [[ -z $picture_gui ]]; then
			get_grabber_picture
		else
			while [[ -z $grabber_picture ]]; do
				grabber_picture=$(gui --select-picture)
				if [[ $? = 1 ]]; then
					exit
				fi

				grabber_picture=$(echo "$grabber_picture" | head -n 1 | sed -e 's|^file://||g' -e 's|\r$||g' -e 's|%20| |g')

				if ! [[ -f "$grabber_picture" ]]; then
					gui --error-picture
					grabber_picture=
				fi
			done
		fi

		if [ -n "$grabber_picture" ]; then
		    #create icon path:
			if ! [ -d "$icons_PATH" ] ; then
				mkdir -p "$icons_PATH"
			fi

		    #create icon:
			$avatar_factory_PATH/themes/$theme_name "$icons_PATH/$icon_NAME.png" "$grabber_picture" "$grabber_picture2" "$grabber_picture3"

			report_icon_creation=yes
			((report_icon_created++))
		elif [[ -z $temporary_icon ]]; then
			grabber_picture=no
			((report_icon_skiped++))
			((total_lines--))
		fi
	else
		((report_icon_exist++))
	fi

	#################################
	#         APPLY RATING          #
	#################################

	if [ "$grabber_picture" != no ]; then

		#################################
		#        CREATE AVATAR          #
		#################################

		if [[ $save_as = avatars ]]; then

		    #set folder:
			if [[ -n $folders ]]; then
				folder2save_backup=$folder2save
				if [[ -n $folder_structure ]]; then
					folder2save=$folder2save/$folder_structure
				fi

				if ! [[ -d "$folder2save" ]]; then
					mkdir -p "$folder2save"
				fi
			fi

		    #create avatar:
			if [[ ! -f "$folder2save/$avatar_filename.desktop" || "$force_avatar_build" ]]; then
				{
					echo "[Desktop Entry]"
					echo "Encoding=UTF-8"
					echo "Name=$avatar_name"
					echo "X-MultipleArgs=false"
					echo "Type=$Link_or_Application"
					echo "Exec=$Launcher"
					echo "Icon=$icons_PATH/$icon_NAME.png"
					echo "URL=$URL"
					echo "$StartupNotify"
					echo ""
					echo "Title=$avatar_title"
					echo "Index=${set_index+$index}"

				} > "$folder2save/$avatar_filename.desktop"

				chmod +x "$folder2save/$avatar_filename.desktop"

				if [[ " files folders " = *" $SOURCE_type "* ]]; then
					modified_time=$(stat --format=%y "$SOURCE_item")	modified_time=${modified_time%.*}
					touch "$folder2save/$avatar_filename.desktop" -d "$modified_time"
				fi

				report_avatar_creation=yes
				report_avatar_created=$((report_avatar_created+1))
			else
				report_avatar_exist=$((report_avatar_exist+1))
			fi

			[[ $grabber_name = avatar ]] || force_avatar_build=

			created_avatars="$created_avatars$folder2save/$avatar_filename.desktop<NEWLINE>"

		    #restore folder:
			if [[ -n $folders ]]; then
				folder2save=$folder2save_backup
			fi

		#################################
		#         CREATE HTML           #
		#################################

		elif [[ $save_as = html ]]; then
			create_html
		fi
	fi

	#################################
	#            REPORT             #
	#################################

	if [[ -n $report_avatar_creation || -n $report_icon_creation ]]; then
		report_avatar_creation=
		report_icon_creation=

		if [[ -n $gui_progress || -n $general_progress ]]; then
			echo "$((number * 100 / total_lines))"
		elif [[ -n $force_avatar_build ]] ; then
			echo -ne "$number/$total_lines - changed ${avatar_title:0:25}...\r"
		else
#			echo -ne "$number/$total_lines - added $avatar_title   \r"
			echo -ne "$number/$total_lines - added ${avatar_title:0:26}...\r"
		fi
		((number++))
		index=$number
	elif [ "$grabber_picture" = no ]; then
		if [[ -n $gui_progress || -n $general_progress ]]; then
			echo "$((number * 100 / total_lines))"
		else
			echo "$number/$total_lines - no cover: ${avatar_title:0:23}..."
		fi
		grabber_picture=
	else
		if [[ -n $gui_progress || -n $general_progress ]]; then
			echo "$((number * 100 / total_lines))"
		else
			echo -ne "$number/$total_lines                                        \r"
		fi
		((number++))
		index=$number
	fi

	#################################
	#          ICONS SIZE           #
	#################################

	if [[ -n $icon_size ]]; then
		nautilus_icon_size
	fi

	if [[ $index = $((total_lines+1)) ]]; then

		#################################
		#       DELETE & REPORT         #
		#################################

	    #Delete:
		if [[ -n $delete ]]; then
			existing_avatars=$(find -L "$folder2save" -name '*.desktop' | sort)
			created_avatars=$(echo "$created_avatars" | sed -e 's/<NEWLINE>$//' -e 's/<NEWLINE>/\n/g' | sort)
			avatars2check=$(diff <(echo "$created_avatars") <(echo "$existing_avatars") | sed -e '/^> /!d' -e 's/^> //')

			remove_avatars () {(
				while read -r line; do
					avatar_path=$line
					avatar_URL=$(cat "$avatar_path" | sed -e '/^URL/!d' -e 's|URL=||')

					if [[ "$avatar_URL" = "http"* ]]; then
						if [[ $SOURCE_type = bookmarks ]]; then
							rm "$avatar_path"
							echo "$avatar_path"
						fi
					else
						source_path=${avatar_URL#*file://}
						if ! [[ -e "$source_path" ]]; then
							rm "$avatar_path"
							echo "$avatar_path"
						fi
					fi
				done
			)}

			if [[ -n "$avatars2check" ]]; then
				removed_avatars=$(echo "$avatars2check" | remove_avatars)
				report_avatar_deleted=$(echo "$removed_avatars" | wc -l)
				folders2check=$(echo "$removed_avatars" | sed -e 's|/[^/]*$||' | sort -r | uniq)

				if [[ -n "$folders2check" ]]; then
					echo "$folders2check" | while read -r line; do
						folder_path=$line
						rmdir "$folder_path" &>/dev/null
					done
				fi
			fi
		fi

	    #Report:
		if [[ -n $general_progress ]]; then
			{
				echo $grabber_name created ${report_avatar_created-0}
				echo $grabber_name existed ${report_avatar_exist-0}
				[[ -n $delete ]] && echo $grabber_name deleted ${report_avatar_deleted-0}
				echo $grabber_name no_cover ${report_icon_skiped-0}
				echo $grabber_name icons_created ${report_icon_created-0}
				echo $grabber_name icons_existed ${report_icon_exist-0}
				#echo $grabber_name total_items $total_lines

			} >> $app_config/report
		else
			echo "Done!                                           "
		fi

		#################################
		#	    SAVE HTML           #
		#################################

		if [[ $save_as = html ]]; then
			if ! [[ -d $app_config/web ]]; then
				mkdir $app_config/web
			fi

			{
				echo "<html>"
				echo "	<head>"
				echo "		<meta content=\"text/html; charset=UTF-8\" http-equiv=\"content-type\">"
				echo "		<title>$grabber_name - Avatar-Factory</title>"
				echo "		<link href=\"styles.css\" type=\"text/css\" rel=\"stylesheet\"></link>"
				echo "	</head>"
				echo "	<body>"
				echo "		<div id=\"sidebar\">"

				IFS=$'\n'

				echo "			<a href=\"$grabber_name.html#1\"><div id=\"sidebarlink\">All ($total_size)</div></a>"
				echo "			<br>"
				echo "${web_sidebar[*]}"

				echo "		</div>"
				echo "		<div id=\"main\">"

				echo "${avatar_web[*]}"

				IFS=$OLDIFS

				echo "			</div>"
				echo "		</div>"

				echo "	</body>"
				echo "</html>"

			} > $app_config/web/$grabber_name.html

			if ! [[ -f $app_config/web/$grabber_name.css ]]; then
		#		cp $avatar_factory_PATH/web_themes/....
				null=
			fi

			if ! [[ -f $app_config/web/styles.css ]]; then
				cp $avatar_factory_PATH/web-themes/brown.css $app_config/web/styles.css
			fi

			IFS=$'\n'
			echo "${web_launcher[*]}" > $app_config/web/$grabber_name.launchers
			IFS=$OLDIFS

			echo file://$app_config/web/$grabber_name.html
		fi
	fi

done |	if [[ -n $gui_progress ]]; then
		gui --progress

		if [[ $? = 1 ]]; then
			exit
		fi
	else
		cat
	fi

    #Cleaning up
	if [[ -f /tmp/thumb$$.??? ]]; then
		rm  /tmp/thumb$$.???
	fi

