#!/bin/bash -i
#
# ZigzagDownLoader (ZDL)
# 
# This program is free software: you can redistribute it and/or modify it 
# under the terms of the GNU General Public License as published 
# by the Free Software Foundation; either version 3 of the License, 
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License 
# along with this program. If not, see http://www.gnu.org/licenses/. 
# 
# Copyright (C) 2011: Gianluca Zoni (zoninoz) <zoninoz@inventati.org>
# 
# For information or to collaborate on the project:
# https://savannah.nongnu.org/projects/zdl
# 
# Gianluca Zoni (author)
# http://inventati.org/zoninoz
# zoninoz@inventati.org
#
#set -x
#

set +o history

path_usr="/usr/local/share/zdl"

source "$path_usr"/source_all.sh

function update_updater {
    ## "...-mirror..." è quello principale (veloce)
    #URL_ROOT="https://download.savannah.nongnu.org/releases/zdl/"
    URL_ROOT="https://download-mirror.savannah.gnu.org/releases/zdl"
    
    get_conf
    
    if [ "$this_mode" != gui ]
    then
	fclear
	header_z
	header_box "$(eval_gettext "Updating \$name_prog")"
    fi    

    [ ! -f $path_conf/version ] &&
	echo "0" >"$path_conf/version"
    
    remote_version=$(curl -s -m 15 "${URL_ROOT}/version")
    [[ ! "$remote_version" =~ ^([0-9]+)$ ]] &&
	remote_version=0
    
    [ -s "$path_conf/version" ] &&
	read local_version < "$path_conf/version"

    [[ ! "$local_version" =~ ^(-1|[0-9]+)$ ]] &&
	local_version='-1'

    updater_log=$(mktemp)
    
    if ((local_version < remote_version)) ||
	   [ "$force_update" == true ]
    then
	if [ "$this_mode" == gui ]
	then
	    if [ "$force_update" != true ]
	    then
		local res
		res=($(yad --title="$(gettext "Updating")"                                                                  \
			   --image="$IMAGE2"                                                                                \
			   --text="$TEXT\n\n$(gettext "A new update is available, choose what to do:")\n\n"                 \
			   --form                                                                                           \
			   --center --on-top                                                                                \
			   --separator=' '                                                                                  \
			   --field="$(gettext "Don't ask for it again in this session")":CHK FALSE                          \
			   --button="$(gettext "Postpone")":0                                                               \
			   --button="$(gettext "Update")":1                                                                 \
			   "${YAD_ZDL[@]}" 2>/dev/null))
		ret=$?
	    else
		ret=1
		unset force_update
	    fi

	    case "$ret" in
		1)
		    sudo_check=$(sudo -H -S -- echo SUDO_OK 2>&1 &)
		    if [[ $sudo_check != "SUDO_OK" ]]
		    then
			while :
			do
			    pass=$(yad --title="Password SUDO"                                  \
				       --text="$(gettext "Enter the user password (sudo):")"    \
				       --image="dialog-password"                                \
				       --entry --hide-text                                      \
				       --center                                                 \
				       --on-top                                                 \
				       "${YAD_ZDL[@]}" 2>/dev/null)
			    
			    [[ -z "$pass" ]] && exit 1
			    
			    echo "$pass" | sudo -S "ls" &>/dev/null

			    if [ "$?" == 0 ]
			    then
				break
			    fi
			done
		    fi
		    
		    real_mode=gui
		    echo > "$gui_log"

		    ## bug di gtk: il riquadro di log per il progress di yad
		    ## non è al momento espandibile senza patch (per gtk o yad)
		    ## finché il bug non sarà sanato da gtk oppure da yad,
		    ## zdl userà la console GUI
		    ##
		    # tail -f "$gui_log" |
		    # 	sed -r 's|^|#|' | tee -a test-log.txt |
		    # 	yad --progress \
		        # 	    --pulsate \
		        # 	    --enable-log \
		        # 	    --log-expanded \
		        # 	    "${YAD_ZDL[@]}" &
		    display_console_gui pid_console_gui
		    ;;
		0)
		    [ "${res[0]}" == TRUE ] &&
			touch /tmp/zdl-skip-update-session
		    return 1
		    ;;
	    esac	    
	fi

	print_c 1 "$(gettext "Downloading")..."

	#wget "$URL_ROOT" -r -l 1 -A gz -np -nd -q
	URL_GIT="http://git.savannah.gnu.org/cgit/zdl.git/snapshot/zdl-2.0.tar.gz"
        
	URL_MIRROR="$URL_ROOT/zdl-2.0.tar.gz"
        #URL_MIRROR="https://download.savannah.nongnu.org/releases/zdl/zdl-2.0.tar.gz"
        
	package="zdl-2.0.tar.gz"        
        dir_dest=$PWD
        mkdir -p /tmp/$prog
        cd /tmp/$prog
        rm -fr *
        
	while [ ! -f "$package" ]
	do
            if [ "$this_mode" == gui ]
            then
                wget "$URL_MIRROR" -O "$package" 2>&1 -o "${gui_log#*\/}"
            else
                rm -rf "$package"
                aria2c "$URL_MIRROR"
            fi
            
	    if [ ! -f "$package" ]
	    then
		if [ "$this_mode" != gui ]
		then
		    print_c 3 "$(gettext "Connection problems: if it does not resolve, close the program with <Control + c>")"
		fi
		sleep 1
	    fi
	done

	print_c 1 "$(gettext "Update %s with %s")" "$PROG" "$package" 

	tar -xzf "$package" 2>/dev/null &&
	    {		
                echo "$remote_version" > "$path_conf/version"
		chmod +rx -R .

                source libs/utils.sh
                source libs/core.sh
                source ui/widgets.sh
                source ui/ui.sh
                source updater.sh

		update
	    } ||
		{
		    print_c 3 "$(gettext "Update failed: package %s cannot be opened")" "$package"
		    if [ "$this_mode" != gui ]
		    then
			pause
		    fi

		    cd - &>/dev/null
		}

    else
	init_msg+="${BGreen}$PROG $(gettext "is already the latest version")\n"
    fi
}

function read_binding {
    read -e -t 1 -n 1 binding_in_loop
}

function main_loop {
    local nline nlines loop_url_in url_in_old
    #clean_livestream

    rm -f "$path_tmp"/req_irc
    
    [ -n "$start_file" ] || start_file="$path_tmp"/links_loop.txt
    
    if [ "$this_mode" == "daemon" ] &&
	   [ ! -s "$path_tmp"/links_loop.txt ] &&
	   [ -z "$lite_mode" ] 
    then
    	start_file="$path_tmp"/links_loop.txt
	post_process
   	sleep 1

    elif check_start_file &&
	    ! check_exit
    then
	nline=1
	while :
	do
            unset test_livestream_boolean
            sleep 1
            
            if [ -s "$file_conf" ]
            then
                tcp_port=$(get_item_conf tcp_port)
                udp_port=$(get_item_conf udp_port)
            fi
            
	    test -f "$path_tmp"/max-dl &&
		read max_dl < "$path_tmp"/max-dl
            
	    [ -n "$max_dl" ] &&
		((max_dl < 1)) &&
		zero_dl 

	    post_process
	    #clean_livestream
	    display_livestreams

	    for gui_instance in $(ls "$path_tmp"/yad_multiprogress_pid.* 2>/dev/null)
	    do
		read gui_instance_pid < "$gui_instance"
		if check_pid "$gui_instance_pid"
		then
                    gui_alive=true
		    check_linksloop_livestream
		    break
		fi
	    done
	    unset gui_instance_pid

            if [ "$gui_alive" != true ]
            then
                check_linksloop_livestream_lite
            fi
	    show_downloads
	    
	    if check_in_loop
	    then
		#sleep 2
		continue
	    fi

	    unset break_loop

	    if [ -f "$start_file" ] && [ -n "$(< "$start_file")" ]
	    then
		nlines=$(wc -l < "$start_file")		
		((nline > nlines)) && nline=1

		url_in=$(head -n ${nline} "$start_file" |tail -n1)

		if [ "$url_in_old" == "$url_in" ] &&
		       ((nlines > 1))
		then
		    ((nline++))
		    continue
		fi
		url_in_old="$url_in"

                [[ "$url_in" =~ '*' ]] &&
                    replace_url_in "${url_in//\*/%2A}"
                                
		if ! check_link "$url_in"
		then
		    #sleep 1
		    ((nline++))
		    continue
		fi
	    else
		show_downloads
		break
	    fi

            prioritize_scheduled_livestreams
            
	    if [ -n "$no_url_regex" ] && [[ "${url_in}" =~ $no_url_regex ]]
	    then
		set_link - "$url_in"
		_log 15 "$url_in"
	    fi

	    if [ -n "$url_regex" ] && [[ ! "${url_in}" =~ $url_regex ]]
	    then
		set_link - "$url_in"
		_log 16 "$url_in"
	    fi

	    unset pid_in file_in url_in_file
	    unset_temp_proxy
	    
	    if [ -f "$path_tmp/downloader" ]
	    then
		read downloader_in < "$path_tmp/downloader"
	    fi

	    print_c 4 "Checking link: %s" "$url_in"

	    if check_link "$url_in"
	    then
		axel_parts=$axel_parts_conf
		url_in="${url_in## }"
		url_in="${url_in%% }"

		check_captcha "$url_in" ||
		    continue

		print_c 0
		header_box "$(gettext "Processing link:")"
		print_c 0 "%s" "$url_in"

		print_c 1 "\n$(gettext "Connecting")..."

		check_ip
		
		check_link_timer "$url_in" ||
		    {
			show_downloads
			((nline++))

			continue
		    }

		## se ancora presenti redirezioni fantasma:
		if [ -f "$path_tmp"/pid_redirects ]
		then
		    while read pid_redirect
		    do
			kill -9 $pid_redirect &>/dev/null
		    done <  "$path_tmp"/pid_redirects 
		    rm -f "$path_tmp/redirect"
		fi
		###################

                source "$path_usr"/extensions/zzzzzzzz-m3u8.sh
                
		try_end=$try_end_default
		## extensions
		if [ -d "$path_usr/extensions/" ]
		then
		    shopt -s nullglob		    
		    for srcfile in "$path_usr"/extensions/*.sh
		    do
                        if [ -n "$no_url_regex" ] && [[ "${url_in}" =~ $no_url_regex ]]
	                then
		            set_link - "$url_in"
		            _log 15 "$url_in"
                            break
	                fi
                        
	                if [ -n "$url_regex" ] && [[ ! "${url_in}" =~ $url_regex ]]
	                then
		            set_link - "$url_in"
		            _log 16 "$url_in"
                            break
	                fi

			if [ -f "$srcfile" ]
			then                            
			    get_language_prog

                            source "$srcfile"

			    get_language
			fi

                        url "$url_in_file" &&
                            [ -n "$file_in" ] &&
                            break
		    done
    		    shopt -u nullglob
		fi

		## se ancora presenti redirezioni fantasma:
		if [ -s "$path_tmp"/pid_redirects ]
		then
		    while read pid_redirect
		    do
			kill -9 $pid_redirect &>/dev/null
		    done < "$path_tmp"/pid_redirects
		    rm -f "$path_tmp/redirect"
		fi
		###################

                if [ -n "$no_url_regex" ] && [[ "${url_in}" =~ $no_url_regex ]]
	        then
		    set_link - "$url_in"
		    _log 15 "$url_in"
	        fi
                
	        if [ -n "$url_regex" ] && [[ ! "${url_in}" =~ $url_regex ]]
	        then
		    set_link - "$url_in"
		    _log 16 "$url_in"
	        fi

		check_exit && return 1

		if [ "$break_loop" == "true" ]
		then
		    unset break_loop
		    show_downloads
		    #sleep 1
		    continue
		fi
                
		if [ -z "$file_in" ] || [ -z "$url_in_file" ]
		then
		    
		    ## streaming downloader
		    items=( $(ls "$path_tmp"/filename_* 2>/dev/null) )
		    for item in ${items[*]}
		    do
			unset __url
			[ -f "$item" ] && read __url < "$item"

			if [ "${__url%% }" == "$url_in" ]
			then
			    item="${item// /_}"
			    file_in="${item#*filename_}"
			    file_in="${file_in%.txt}"
			    break
			fi
		    done

		    ## universal downloader
		    if [ -z "$file_in" ] #&& ! url "$url_in_file"
		    then
			file_in="${url_in##*'/'}"
			file_in="${file_in%%'&'*}"
			file_in="${file_in%'?'*}"
		    fi

                    if [ -z "$url_in_file" ]
                    then
		        url_in_file="${url_in%% }"
		        url_in_file="${url_in_file## }"
                    fi
		fi

		sanitize_file_in

		if ! check_freespace
		then
		    break_loop="true"
		    set_exit
		fi

		if [ -z "$file_filtered" ]
		then
		    file_filter "$file_in"
		else
		    unset file_filtered
		fi

		if ! url "$url_in_file" && 
			[[ "$downloader_in" =~ (Aria2|Wget|Axel|FFMpeg) ]] ||
 			    [ "$break_loop" == "true" ]
		then

		    unset break_loop
		    show_downloads
		    #sleep 1
		    continue
		fi

		#### DOWNLOAD ####
		if [ -z "$premium" ] &&                                                 
		       check_in_file &&                                                         
		       check_freespace &&
		       file_filter "$file_in"
		then
		    check_dler_forcing

		    if [[ "$downloader_in" =~ (RTMPDump|cURL) ]]
		    then
			print_c 4 "Streamer: %s\nPlaypath: %s\n" "$streamer" "$playpath"
		    else
			print_c 4 "$(gettext "File URL"): %s" "$url_in_file"
		    fi

		    if [ -n "$file_in" ] && download
		    then
			print_c 1 "downloading --> $file_in ..."
		    fi		    
		    rm -f "$path_tmp/cookies.zdl"
		    unset no_newip
		fi

		newip_add_host
		from_loop=true

		[ "$ch_dler" == "1" ] &&
		    downloader_in=$dler &&
		    unset ch_dler

		noproxy
	    fi	    

	    show_downloads
	    pipe_files
	    #[ ! -s "$start_file" ] && sleeping_pause=0 
	    #sleeping "$sleeping_pause"
	    unset break_loop post_data not_available exceeded
	done 

	if [ "$this_mode" != "daemon" ]
	then
	    touch "$path_tmp"/stop-binding
	    while [ -f "$path_tmp"/stop-binding ]
	    do
		sleep 0.1
	    done
	fi
    fi
}

#### INPUT:

args=( "$@" )

tags=( $(ps ax |head -n1) )
for ((i=0; i<${#tags[*]}; i++))
do
    j=$(( $i+1 ))
    [ "${tags[i]}" == "PID" ] && ps_ax_pid="\$$j"
    [ "${tags[i]}" == "TTY" ] && ps_ax_tty="\$$j"
done


#### PIPE:
#
# stdin="$(ls -l /dev/fd/0)"
# stdin="${stdin/*-> /}"
# if [ "${stdin}" != "${stdin//'pipe:['}" ]
if [ -p /dev/fd/0 ]
then
    read -d '' pipe < /dev/fd/0
    exec 0< /dev/$(ps ax | grep ^[\ ]*$$ | awk "{print $ps_ax_tty}")
    args+=( "$pipe" )
    
    unset pipe
fi


#### OPTIONS:

max_args=$(( ${#args[*]}-1 ))

if [[ "${args[*]}" =~ \-[a-zA-Z0-9]{2} ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^-[a-zA-Z0-9]+$ ]] &&
	       [[ "${args[i]}" =~ m([0-9]+) ]]
	then
	    args[i]="${args[i]//m${BASH_REMATCH[1]}}"
	    [ "${args[i]}" == '-' ] &&
		unset args[i]
	    
	    args[++max_args]="-m"
	    args[++max_args]="${BASH_REMATCH[1]}"
	fi

	if [[ "${args[i]}" =~ ^-[a-zA-Z0-9]{2}$ ]]
	then
	    for ((j=1; j<${#args[i]}; j++))
	    do
	        args[++max_args]="-${args[i]:$j:1}"
	    done
	    unset args[i]
	fi
    done
fi


# if [[ "${args[@]}" =~ \-\-get\-title ]]
# then
#     for ((i=0; i<=$max_args; i++))
#     do
#         if [[ "${args[i]}" =~ \-\-get\-title=[\"\']*(http.+)[\"\']*$ ]]
#         then
#             url_in_title="${BASH_REMATCH[1]}"
            
#             if [ -z "$file_in" ] &&
#                    url "$url_in_title"
#             then
#                 html=$(curl -s "$url_in_title")
#                 file_in=$(get_title "$html")
#                 sanitize_file_in
#             fi

#             unset args[i]
#             break
#         fi
#     done
# fi

# if [[ "${args[@]}" =~ \-\-set\-title ]]
# then
#     for ((i=0; i<=$max_args; i++))
#     do
#         if [[ "${args[i]}" =~ \-\-set\-title=[\"\']*(.+)[\"\']*$ ]]
#         then
#             file_in_title="${BASH_REMATCH[1]}"

#             if [ -z "$file_in" ] &&
#                    [ -n "$file_in_title" ]
#             then
#                 file_in="$file_in_title"
#                 sanitize_file_in
#             fi

#             unset args[i]
#             break
#         fi
#     done
# fi

if [[ "${args[@]}" =~ \-\-open\-relink ]]
then
    init
    for ((i=0; i<=$max_args; i++))
    do
        if [[ "${args[i]}" =~ \-\-open\-relink\=[\"\']*(http.+)[\"\']*$ ]]
        then
            mkdir -p "$HOME"/tmp
            cd "$HOME"/tmp
            url_in="${BASH_REMATCH[1]}"
            break
        fi
    done
    open_relink
    exit
fi



#### PATH:

for ((i=0; i<"${#args[@]}"; i++)) 
do
    if [ -d "${args[i]}" ]
    then
	cd "${args[i]}"
	mkdir -p "$HOME"/tmp
	echo "${args[i]}" >"$HOME"/tmp/zigzagdownloader-dirbase
	unset args[i]
	break
    fi
done

if [[ "${args[@]}" =~ (--path-gui) ]]
then
    for ((i=0; i<${#args[@]}; i++))
    do
	if [[ "${args[i]}" =~ ^(--path-gui)$ ]]
	then
	    mkdir -p "$HOME"/tmp
	    test -s "$HOME"/tmp/zigzagdownloader-dirbase &&
		cd $(cat "$HOME"/tmp/zigzagdownloader-dirbase) ||
		    cd "$HOME"
	    
	    path_gui=$(get_download_path)
	    [ ! -d "$path_gui" ] && exit 

	    echo "$path_gui" >"$HOME"/tmp/zigzagdownloader-dirbase
	    cd "$path_gui"

	    unset args[i] path_gui
	fi
    done
fi

if [ "${args[*]}" == "${args[*]//--silent}" ] &&
       [ "${args[*]}" == "${args[*]//--stream}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ -d "${args[i]}" ]
	then
	    BASE_DIR="$PWD/"
	    cd "${args[i]}"
	    unset args[i]
	fi
    done
fi

for ((i=0; i<=$max_args; i++))
do
    if [ -d "${args[i]}" ]
    then
	BASE_DIR="$PWD/"
	cd "${args[i]}"
	unset args[i]
    fi
done


add_path4server "$(realpath "$PWD")"
mkdir -p "$path_tmp"
echo > "$gui_log"

if [[ "${args[*]}" =~ (--gui|-g) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--gui|-g)$ ]]
	then
	    unset args[i]
	    touch "$gui_log"	    
	    run_gui &>/dev/null &
	    disown
	    exit 0
	fi
    done
fi



##############################
if [[ "${args[*]}" =~ (--no-stop) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--no-stop)$ ]]
	then
	    unset args[i]
	    no_stop=true
	    unset autoupdate
	fi
    done
fi    
###############################



if [[ "${args[*]}" =~ (-g|-s|--no-update) ]] ## silent - sockets - gui
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(-u|--update|--no-update)$ ]]
	then
	    unset args[i]
	fi
    done
    unset autoupdate
fi

if [ "${args[*]}" != "${args[*]//--update}" ] ||
       [ "${args[*]}" != "${args[*]//-u}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--force' ] ||
	       [ "${args[i]}" == '-f' ]
	then
	    unset args[i]
	    echo '-1' >"$path_conf/version"
	fi
    done
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--update' ] ||
	       [ "${args[i]}" == '-u' ]
	then
	    unset args[i]
	    update_updater
	fi
    done

elif [ "$autoupdate" == "enabled" ] &&
	 [ "${args[*]}" == "${args[*]//--interactive}" ] &&
	 [ "${args[*]}" == "${args[*]//-i}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--force' ] ||
	       [ "${args[i]}" == '-f' ]
	then
	    unset args[i]
	    echo '-1' >"$path_conf/version"
	fi
    done
    update_updater
fi


if [ "${args[*]}" != "${args[*]//--live}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--live' ]
	then
	    live_streaming=true
	    unset args[i]
	fi
    done
fi


if [ "${args[*]}" != "${args[*]//--web-ui}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--web-ui' ]
	then
	    unset args[i]
	    run_web_client "${args[@]}"
	    exit
	fi
    done
fi

if [ "${args[*]}" != "${args[*]//--clean}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--clean' ]
	then
	    unset args[i]
	    rm -r ".zdl_tmp"/* 2>/dev/null &&
		init_msg+="$(sprint_c 1 "$(gettext "Temporary file deleted")\n")" ||
		    init_msg+="$(sprint_c 3 "$(gettext "Cleaning of temporary files not carried out (non-existent files)")\n")"
	fi
    done
fi


#### INIT:
init



if [ "${args[*]}" != "${args[*]//--list-extensions}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--list-extensions" ]
	then
	    unset args[i]
	    this_mode=list
	    services_box
	    xterm_stop force
            stty sane
            cursor on
	    exit
	fi
    done
fi

if [ "${args[*]}" != "${args[*]//--help-bindings}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--help-bindings" ]
	then
	    unset args[i]
	    this_mode=help
            header_z
	    standard_box
	    xterm_stop force
	    exit
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-(mg|nano|mcedit|vi|vim|emacs|emacs-nw|jed|zile|jupp) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^\-\-(mg|nano|mcedit|vi|vim|emacs|emacs-nw|jed|zile|jupp)$ ]]
	then
	    [[ $(command -v "${BASH_REMATCH[1]//-*}" 2>/dev/null) ]] && editor="${BASH_REMATCH[1]//-/ -}"
	    unset args[i]
	    from_editor=true
	fi
    done
fi

if [[ "${args[*]}" =~ (--editor|-e) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--editor|-e)$ ]]
	then
	    unset args[i]
	    from_editor=true
	fi
    done
fi


if [ "${args[*]}" != "${args[*]//--silent}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--silent" ]
	then
	    unset args[i]
	    this_mode="daemon"
	    ## this_tty= importato da zdl --daemon
	    sleeping_pause=0

	    if [ "$(urldecode ${args[i+1]})" == "$PWD" ]
	    then
		unset args[i+1]
	    fi
	fi
    done
fi

## external application button (firefox/chrome/opera extension)
#### usage:
## option "Arguments": --external-application-button [HREF] [zdl parameters...] 
## option "Quotation": "Surround arguments with quote characters" enabled
if [ "${args[*]}" != "${args[*]//--external-application-button}" ]
then
    if [ "$this_mode" != "daemon" ]
    then 
	if [ -z "$DISPLAY" ]
	then
	    export DISPLAY=":0"
	fi

        url=$(sanitize_url "${args[1]}") #"${args[1]}"
        unset args[0] args[1]
	parameters="${args[*]}"
        parameters="${parameters//= /=}"

        test -s /tmp/zigzagdownloader-dirbase &&
	    cd $(cat /tmp/zigzagdownloader-dirbase) ||
		cd "$HOME"
	
	if [ ! -d "$directory" ]
	then
	    get_download_path directory || exit 0
	    [ ! -d "$directory" ] && exit 0
	fi
        
	echo "$directory" >/tmp/zigzagdownloader-dirbase
	cd "$directory"
	mkdir -p "$path_tmp"

	if [ -e "/cygdrive" ]
	then
	    #dest_dir="${args[*]#*'--cwd'}"
	    #dest_dir=$(cygpath -u "$dest_dir")
	    #[ -n "$dest_dir" ] && cd "$dest_dir"
	    $prog "$url" $parameters --stop
	else
            #-fa
            #"XTerm*faceName: xft:Dejavu Sans Mono:size=9:antialiasing=true:hinting=true:hintstyle=hintsfull"                                \
	    xterm -tn "xterm-256color"                                                                      \
                  -u8                                                                                       \
		  -xrm "$xterm_facename"                                                                    \
		  +bdc -fg grey -bg black -title "ZigzagDownLoader in $PWD"                                 \
		  -e "/bin/bash -i -c \"export pid_prog=\$$ ;zdl $parameters \\\"$url\\\" --stop \""
	fi
	exit
    else
	unset args
    fi
fi


## conkeror
if [ "${args[*]}" != "${args[*]//--zigzag-xterm}" ]
then
    if [ "$this_mode" != "daemon" ]
    then 
	if [ -z "$DISPLAY" ]
	then
	    export DISPLAY=":0"
	fi

	url="${args[*]%'--zigzag-xterm'*}"
	parameters="${args[*]#*'--zigzag-xterm'}"
	parameters="${parameters%'--cwd'*}"

	if [ -e "/cygdrive" ]
	then
	    dest_dir="${args[*]#*'--cwd'}"
	    dest_dir=$(cygpath -u "$dest_dir")
	    [ -n "$dest_dir" ] && cd "$dest_dir"
	    $prog "$url" $parameters --stop
	else
	    xterm -tn "xterm-256color"                                                                      \
		  -xrm "$xterm_facename" \
		  +bdc -fg grey -bg black -title "ZigzagDownLoader in $PWD"                                 \
		  -e "/bin/bash -i -c \"export pid_prog=\$$ ; zdl $parameters \\\"$url\\\" --stop \"" &
	fi
	exit
    else
	unset args
    fi
fi


if [ "${args[*]}" != "${args[*]//--stream}" ]
then
    for ((i=0; i<=$max_args; i++)) 
    do
	if [ "${args[i]}" == "--stream" ]
	then 
	    ## zdl --stream [URL] [FNAME] [FOLDER] [CFILE] [COOKIE] [REFERER]
	    ## zdl --stream [URL] [FNAME] --noXterm
	    unset args[i]
	    if [ -z "$DISPLAY" ]
	    then
		export DISPLAY=":0"
	    fi

	    url_in="$2"
	    url_in="${url_in// /20%}"	    
	    test_dir_3="$3"
	    test_dir_4="$4"
	    if [ -e "/cygdrive" ]
	    then
		test_dir_3=$(cygpath -u "$test_dir_3")
		test_dir_4=$(cygpath -u "$test_dir_4")
	    fi 

	    if [ -d "$test_dir_3" ]
	    then
		directory="$test_dir_3"
		unset file_in
		
	    else
                [ -n "$test_dir_3" ] &&	file_in="${test_dir_3#--set-title=}"

                if [ "$test_dir_4" != "--noXterm" ] &&
		       [ -d "$test_dir_4" ]
		then
		    directory="$test_dir_4"
		fi
	    fi

	    if [ "$file_in" != "${file_in//'/'/}" ]
	    then
		if [ -z "$directory" ]
		then
		    directory="${file_in%/*}"
		fi
		file_in="${file_in##*/}"
	    fi
	    file_in="${file_in// /_}"
	    file_in="${file_in##*/}"
	    file_in="${file_in::240}"

            if [ -d "$4" ]
            then
	        cfile="$5"
	        cookie="$6"
	        referer="$7"

            elif [ -n "$4" ] &&
                     [[ ! "$4" =~ ^\-\- ]]
            then
                cookie="$4"
            fi
            
	    if [ "$url_in" != "${url_in//nowvideo.}" ] &&
		   [ ! -e "/cygdrive" ]
	    then
		referer="$6"
		ext="${file_in##*.}"
		file_in2=$(curl "$referer" | grep "&amp;title=")
		file_in2="${file_in2#*'&amp;title='}"
		file_in2="${file_in2::240}"
		[ -n "$file_in2" ] &&
		    file_in2="${file_in2// /_}" &&
		    file_in="${file_in2%%\"*}.$ext"
	    fi

	    test -s /tmp/zigzagdownloader-dirbase &&
		cd $(cat /tmp/zigzagdownloader-dirbase) ||
		    cd "$HOME"
	    
	    if [ ! -d "$directory" ]
	    then
		get_download_path directory || exit 0
		[ ! -d "$directory" ] && exit 0
	    fi

	    echo "$directory" >/tmp/zigzagdownloader-dirbase
	    cd "$directory"
	    mkdir -p "$path_tmp"
	    
	    if [ -e "$cfile" ]
	    then
		cat "$cfile" >> "$path_tmp/flashgot_cfile.zdl"
	    fi

            if [ -n "$cookie" ]
            then
	        echo -e "$cookie" >> "$path_tmp/flashgot_cookie.zdl"
                echo -e "$cookie" >> "$path_tmp/cookies.zdl"
            fi
            
	    url_in="${url_in%%'#20%'}"

            [ "$file_in" == undefined ] && unset file_in

            if [ -n "${file_in}" ]
            then
                sanitize_file_in
	        echo "$url_in" > "${path_tmp}/filename_${file_in}.txt"
	    fi
            
	    if [ "$4" == "--noXterm" ] ||
		   [ -e "/cygdrive" ]
	    then
		export pid_prog=$$
		if check_instance_prog
		then
		    set_link + "$url_in"
		    xterm_stop_checked=true
		    links="$url_in"
		    redirect_links
		else
		    $prog "$url_in" $stream_params --stop
		fi

	    elif [[ "${args[*]}" =~ '--gui' ]]
	    then
	    	#export pid_prog=$$
	    	nohup $prog "${args[@]}" &>/dev/null &
		
	    else
		xterm -tn "xterm-256color"                                                                          \
                      -u8                                                                                           \
		      -xrm "$xterm_facename"                                                                        \
		      +bdc -fg grey -bg black -title "ZigzagDownLoader in $PWD"                                     \
		      -e "/bin/bash -i -c \"export pid_prog=\$$ ; $prog \\\"$url_in\\\" $stream_params --stop\"" &
	    fi
	    exit
	fi
    done 
fi


if [[ "${args[*]}" =~ \-\-scrape-url=[^\ ]+ ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--scrape-url=[^\ ]+)$ ]]
	then
	    url_page=$(sed -r 's|--scrape-url=["]*(.+)["]*$|\1|g' <<< "${args[i]}")
	    scrape_url "$url_page"
            scraped=true	    
	    unset args[i]
	fi
    done
fi


if [ "${args[*]}" != "${args[*]//--scrape-url}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--scrape-url" ]
	then
	    scrapeURL=true
	    unset args[i]
	fi
    done
fi



## --stop deve precedere --mp3|--flac
if [ "${args[*]}" != "${args[*]//--stop}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--stop" ]
	then 
	    unset args[i]
	    xterm_stop_checked=true
	fi
    done
fi


if [[ "${args[*]}" =~ (--mp3|--flac) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--mp3|--flac)$ ]]
	then 
	    if [ -z "$(command -v ffmpeg 2>/dev/null)$(command -v avconv 2>/dev/null)" ]
	    then
		print_c 3 "$(gettext "The format conversion function depends on ffmpeg or avconv, not found")" 
		exit
	    fi
	    echo ${args[i]##*-} > "$path_tmp"/format-post_processor
	    echo "$downloaded_by_zdl" >"$path_tmp"/print_out-post_processor 2>/dev/null
	    unset args[i]
	fi
    done
fi


if [ "${args[*]}" != "${args[*]//--daemon}" ] ||
       [ "${args[*]}" != "${args[*]//-d}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--daemon" ] ||
	       [ "${args[i]}" == "-d" ]
	then
	    unset args[i]
	    already_clean=true
	    if ! check_instance_daemon
	    then
		mkdir -p "$path_tmp"
		export this_tty
		this_mode=stdout
		start_mode_in_tty "$this_mode" "$this_tty"
		
		date +%s >"$path_tmp"/.date_daemon

		#nohup /bin/bash zdl ${args[*]} --silent "$PWD" & #>/dev/null &

		/bin/bash zdl ${args[*]} --silent "$PWD" &>/dev/null &
		disown
		
		print_c 4 "${name_prog}:       "
		print_c 1 "$(gettext "Started in daemon mode in %s")\n" "$PWD"
		print_c 4 "$(gettext "You can control it with:") ${Color_Off}$prog -i \"$PWD\"\n"

		[ -n "$xterm_stop_checked" ] && xterm_stop
		exit 0

	    else
		start_mode_in_tty stdout "$this_tty"
		
		print_c 4 "${name_prog}:       "
		print_c 3 "$(gettext "An active instance of daemon mode already exists in %s")\n" "$PWD" 
		print_c 4 "$(gettext  "You can control it with:") ${Color_Off}$prog -i \"$PWD\"\n"

		already_daemon=true
		this_mode=daemon
	    fi
	fi
    done
fi

export pid_prog=$$

if [[ "${args[*]}" =~ \-s ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^\-\-socket(\=[0-9]+)$ ]]
	then	    
	    socket_port="${BASH_REMATCH[1]#'='}"
	    unset args[i]
	    start_socket=true 
	fi

	if [ "${args[i]}" == '-s' ]
	then
	    [[ "${args[i+1]}" =~ ^[0-9]+$ ]] &&
		socket_port="${args[i+1]}"
	    unset args[i] args[i+1]
	    start_socket=true 
	fi

	if [ "$start_socket" == true ] &&
	       [ -n "$socket_port" ]
	then
	    if ! check_instance_server $socket_port &>/dev/null
	    then
		unset start_socket
		if run_zdl_server $socket_port
		then
		    msg_server="$(gettext "New socket started at the port") $socket_port"
		    init_msg+="$(sprint_c 1 "$msg_server\n")"
		    echo 0 >"$path_server"/zdl-sockets-exit
		fi
		
	    elif ! check_port "$socket_port"
	    then
		msg_server="$(gettext "Socket already in use at the port") $socket_port (you can specify a new port with: -s PORTA or --socket=PORTA)"
		init_msg+="$(sprint_c 3 "$msg_server\n")"
		echo 1 >"$path_server"/zdl-sockets-exit
		
	    else
		msg_server="$(gettext "Socket not started at the port") $socket_port"
		init_msg+="$(sprint_c 3 "$msg_server\n")"
		echo 2 >"$path_server"/zdl-sockets-exit
	    fi
	fi
    done
fi

if [ "${args[*]}" != "${args[*]//--help}" ] ||
       [ "${args[*]}" != "${args[*]//-h}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--help" ] ||
	       [ "${args[i]}" == "-h" ]
	then 
	    unset args[i]
	    usage
	fi
    done
fi


if [ "${args[*]}" != "${args[*]//--configure}" ] ||
       [ "${args[*]}" != "${args[*]//-c}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(\-\-configure|\-c)$ ]]
	then
	    unset args[i]
	    configure
	fi
    done
fi


if [ "${args[*]}" != "${args[*]//--interactive}" ] ||
       [ "${args[*]}" != "${args[*]//-i}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--interactive' ] ||
	       [ "${args[i]}" == '-i' ]
	then 
	    unset args[i]
	    interactive
	fi
    done
fi
## se non è modalità interattiva, allora sono validi i comandi "standard"
#bindings

if [[ "${args[*]}" =~ (--lite|-l) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--lite|-l)$ ]]
	then
	    this_mode=lite
	    lite_mode=true
	    unset args[i]
	fi
    done
fi


if ! check_instance_prog &&
	! check_instance_daemon
then
    rm -f "$path_tmp"/reconnect "$path_tmp"/proxy*
fi




###
## change_mode di avvio: dopo list-extensions, lite, daemon, interactive, configure
## (tutte le modalità output che assegnano un valore a $this_mode)
###
start_mode_in_tty "$this_mode" "$this_tty"

##########
fclear
header_z
##########


if [ "${args[*]}" != "${args[*]//--reconnect}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--reconnect" ]
	then
	    unset args[i]
	    touch "$path_tmp"/reconnect
	fi
    done
fi

################################################# IRC-XDCC
## 1) link "irc://[host]/[chan]/msg\ [privmsg]"
## 2) -x, --xdcc //-->interattivo: 1) /connect irc://irc.host; 2) /join #channel; 3) /msg ...
## 3) da fare: --irc=[host], --chan=[chan], --msg=[privmsg] (se manca un parametro: input_xdcc)

if [[ "${args[*]}" =~ \-(x|X) ]]
then
    #start_file="$path_tmp/links_loop.txt"
    no_stop=true
    
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(-x|--xdcc)$ ]]
	then
	    declare -A irc
	    if input_xdcc
	    then
		irc[host]="${irc[host]#'irc://'}"
		irc[host]="${irc[host]%%'/'*}"

		irc[chan]="${irc[chan]##*'#'}"

		irc[msg]="${irc[msg]#'/msg'}"
		irc[msg]="${irc[msg]#'/ctcp'}"
		irc[msg]="${irc[msg]## }"
		
		args+=( "$(sanitize_url "irc://${irc[host]}/${irc[chan]}/msg ${irc[msg]}")" )
		(( max_args++ ))
	    fi
	    unset args[i] irc
	fi
        
        if [[ "${args[i]}" =~ ^(\-X|\-\-xdcc-search\=.+)$ ]]
        then
            if [ "${args[i]}" == '-X' ]
            then
                XDCC_PATTERN="${args[i+1]}"
                unset args[i+1] args[i]
            else
                XDCC_PATTERN="${BASH_REMATCH[1]}"
                XDCC_PATTERN="${XDCC_PATTERN#*=}"
                unset args[i]
            fi
            display_xdcc_eu_gui "$XDCC_PATTERN"
        fi
                                                    
    done
fi


## -T | --torrent-file=
if [[ "${args[*]}" =~ \-(T|\-torrent-file=) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "-T" ]
	then
	    if [[ "${args[i+1]}" =~ (^[^-]+.*) ]]
	    then
		ftorrent="$BASE_DIR${BASH_REMATCH[1]}"
		if [ -f "${ftorrent}" ]
		then
		    [ "${ftorrent}" == "${ftorrent%.torrent}" ] &&
			mv "${ftorrent}" "${ftorrent}.torrent"
		    set_link + "${ftorrent%.torrent}.torrent"
		fi	
		unset args[i+1]
	    fi
	    unset args[i] 
	fi
	
	if [[ "${args[i]}" =~ ^\-\-torrent-file=(.+)$ ]]
	then
	    ftorrent="$BASE_DIR${BASH_REMATCH[1]}"
	    if [ -f "${ftorrent}" ]
	    then
		[ "${ftorrent}" == "${ftorrent%.torrent}" ] &&
		    mv "${ftorrent}" "${ftorrent}.torrent"
		set_link + "${ftorrent%.torrent}.torrent"
	    fi	
	    unset args[i]
	fi
	
    done
    
fi

## --(tcp|udp)-port=
if [[ "${args[*]}" =~ \-\-(tcp|udp)\-port= ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^\-\-(tcp|udp)-port=([0-9]+)$ ]]
	then
	    eval ${BASH_REMATCH[1]}_port="${BASH_REMATCH[2]}"
	    unset args[i]
	fi
    done
fi


if [[ "${args[*]}" =~ \-(m|\-max\-downloads=|\-multi=) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	unset max_dl
	
	if [ "${args[i]}" == "-m" ]
	then
	    if [[ "${args[i+1]}" =~ ^([0-9]+)$ ]]
	    then
		max_dl="${BASH_REMATCH[1]}"
		unset args[i+1]
	    fi
	    echo $max_dl >"$path_tmp/max-dl"
	    #unlock_fifo max-downloads "$PWD" &
	    unset args[i]
	fi
	
	if [[ "${args[i]}" =~ ^\-\-max\-downloads=([0-9]+)$ ]] ||
	       [[ "${args[i]}" =~ ^\-\-multi=([0-9]+)$ ]]
	then
	    max_dl="${BASH_REMATCH[1]}"
	    
	    [[ "${args[i]}" =~ ^\-\-multi ]] &&
		init_msg+="${BRed}$(gettext "Deprecated option: '--multi = [NUMBER]' is replaced by '--max-downloads = [NUMBER]'. The short option remains unchanged: '-m [NUMERO]'\n")"

	    echo $max_dl >"$path_tmp/max-dl"
	    #unlock_fifo max-downloads "$PWD" &
	    unset args[i]
	fi

    done
fi


if [ "${args[*]}" != "${args[*]//--ip}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--ip' ]
	then 
	    unset args[i]
	    get_ip myip
	    print_c 0 "\n"
	    separator-
	    if [ -n "$http_proxy" ]
	    then
		print_c 1 "$(gettext "HTTP proxy detected: %s")" "$http_proxy"
	    fi
	    
	    if [ -n "$myip" ]
	    then
		print_c 1 "$(gettext "IP address: %s")" "$myip"

	    else
		print_c 3 "$(gettext "IP address not detected")"
	    fi

	    separator-
	    print_c 0 "\n"
	fi
    done
fi


if [ "${args[*]}" != "${args[*]//--login}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--login' ]
	then 
	    unset args[i]
	    login=1
	fi
    done
fi


if [[ "${args[*]}" =~ '--'(wget|aria2|axel) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^'--'(aria2|axel|wget)$ ]]
	then 
	    unset args[i]
	    
	    set_downloader $(tr [:lower:] [:upper:] <<< ${BASH_REMATCH[1]:0:1})${BASH_REMATCH[1]:1}
	fi
    done
fi


if [ "${args[*]}" != "${args[*]//--out=}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" != "${args[i]#'--out='}" ]
	then
	    cmd_test=$(awk '{print $1}' <<< ${args[i]#'--out='} | tr -d \")
	    
	    if hash $cmd_test 2>/dev/null
	    then
		pipe_out_str="${args[i]#'--out='}"
		pipe_out=( ${pipe_out_str#\"} )

	    else
		file_output=$downloaded_by_zdl
		print_out="${args[i]#'--out='}"

		if [ -e "$print_out" ] 
		then
		    init_msg+=$(sprint_c 3 "$(gettext "A file already exists with the same name as") ${print_out}\n")
		    print_out="$file_output"
		    
		elif [ -z "$print_out" ]
		then
		    print_out="$file_output"
		fi
		init_msg+=$(sprint_c 1 "$(eval_gettext "The file list will be saved in \$print_out\n(you can also use it to communicate the files being downloaded to another program)\n")")
		
		touch "$print_out"
	    fi
	    unset args[i]
	fi
    done
fi

if [ "${args[*]}" != "${args[*]//--proxy}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" != "${args[i]#'--proxy'}" ]
	then
	    if [ "${args[i]}" == '--proxy' ]
	    then
		echo > "$path_tmp"/proxy
		
	    elif [ "${args[i]}" == '--proxy=t' ]
	    then
		echo "Transparent" >> "$path_tmp"/proxy

	    elif [ "${args[i]}" == '--proxy=a' ]
	    then
		echo "Anonymous" >> "$path_tmp"/proxy

	    elif [ "${args[i]}" == '--proxy=e' ]
	    then
		echo "Elite" >> "$path_tmp"/proxy

	    elif [ "${args[i]}" != "${args[i]%'='*}" ]
	    then
		proxy="${args[i]#'--proxy='}"

		if [ -z "${proxy//[0-9.:]}" ]
		then
		    echo "$proxy" > "$path_tmp"/proxy
		    export http_proxy=$proxy
		    print_c 1 "$(gettext "Active proxy: %s\n")" "$http_proxy"

		else
		    print_c 3 "$(gettext "%s: invalid argument\n\n")" "${args[i]}"
		    usage
		fi
	    else
		print_c 3 "$(gettext "%s: invalid argument\n\n")" "${args[i]}"

		usage
	    fi
	    unset args[i]
	fi
    done
fi

if [[ "${args[*]}" =~ (-r|--resume) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(-r|--resume)$ ]]
	then 
	    unset args[i]
	    resume=enabled
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-url=[^\ ]+ ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--url=[^\ ]+)$ ]]
	then
	    url_regex=$(sed -r "s|--url=[\"']*(.+)[\"']*$|\1|g" <<< "${args[i]}")
	    unset args[i]
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-no\-url=[^\ ]+ ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--no-url=[^\ ]+)$ ]]
	then
	    no_url_regex=$(sed -r "s|--no-url=[\"']*(.+)[\"']*$|\1|g" <<< "${args[i]}")
	    unset args[i]
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-no-file=[^\ ]+ ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--no-file=[^\ ]+)$ ]]
	then
	    no_file_regex=$(sed -r "s;--no-file=[\"']*(.+)[\"']*$;\1;g" <<< "${args[i]}")
	    unset args[i]
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-file=[^\ ]+ ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--file=[^\ ]+)$ ]]
	then
	    file_regex=$(sed -r "s;--file=[\"']*(.+)[\"']*$;\1;g" <<< "${args[i]}")
	    unset args[i]
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-no-rev ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--no-rev)$ ]]
	then
	    no_file_regex='\.rev$'
	    unset args[i]
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-no-sub ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--no-sub)$ ]]
	then
	    no_file_regex='[Ss]{1}[Uu]{1}[Bb]{1}'
	    unset args[i]
	fi
    done
fi


if [[ "${args[*]}" =~ \-\-no-complete ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--no-complete)$ ]]
	then
	    no_complete=true
	    unset args[i]
	fi
    done
fi


for ((i=0; i<=$max_args; i++))
do
    if [ "${args[i]}" != "${args[i]#-}" ]
    then
	print_c 3 "$(gettext "%s: invalid argument")\n\n" "${args[i]}"

	usage
    fi
done



#### FILE / CONTAINER / TORRENT / SCRAPE-URL

if [ -n "${args[*]}" ]
then
    COOKIE="$path_tmp/flashgot_cfile.zdl"
    for ((i=0; i<=$max_args; i++))
    do
	[[ "${args[i]}" =~ xweaseldownload.php ]] &&
	    print_c 2 "$(gettext "Connection and extraction from:")\n%s\n" "${args[i]}" 

	if [ -f "${BASE_DIR}${args[i]}" ]
	then
	    if [ "${args[i]}" != "${args[i]%.dlc}" ]
	    then
                file_dlc=true
		add_container "${BASE_DIR}${args[i]}" ## container_file

	    elif [ "${args[i]}" != "${args[i]%.torrent}" ]
	    then
		set_link + "${BASE_DIR}${args[i]}"
		
	    else
		## dos2unix:
		tr -d '\r' < "${BASE_DIR}${args[i]}" > "${BASE_DIR}${args[i]}".unix
		echo >>"${BASE_DIR}${args[i]}".unix
		mv "${BASE_DIR}${args[i]}".unix "${BASE_DIR}${args[i]}"

		while read line
		do
		    sanitize_url "$line" >>"$path_tmp/sanitized_links"

		done <"${BASE_DIR}${args[i]}"

		grep_urls "$path_tmp/sanitized_links" >"$path_tmp"/links_loop.txt
	    fi
	    
	elif [ -n "${args[i]}" ]
	then
	    args[i]=$(sanitize_url "${args[i]}")
            
	    if url "${args[i]}"
	    then
		if [ "$scrapeURL" == "true" ]
		then
		    scrape_url "${args[i]}"
                    scraped=true
		    
		else
		    if [ -z "$links" ]
		    then
			links="${args[i]}"
		    else
			links="${links}\n${args[i]}"
		    fi
		    start_file="$path_tmp/links_loop.txt"

		    set_link + "${args[i]}"
		fi
	    else
		_log 12 "${args[i]}"
	    fi
	fi
    done

    if [ -f "$path_tmp"/links_loop.txt ]
    then 
	start_file="$path_tmp/links_loop.txt"
	clean_file "$start_file"
	echo >> links.txt 2>/dev/null
	date >> links.txt 2>/dev/null
	cat "$start_file" >> links.txt 2>/dev/null
	init_msg+=$(sprint_c 1 "$(gettext "The complete list of links is in links.txt")\n")

	if ! check_instance_prog &&
		[ -z "$from_editor" ] &&
		[ -z "$lite_mode" ] &&
		[ "$this_mode" != lite ]
	then
	    standard_box
	fi
    fi
fi


if [ -f "$path_tmp/downloader" ]
then
    read downloader_in < "$path_tmp/downloader"
else
    echo $downloader_in > "$path_tmp/downloader"
fi

#### EDITOR

if [ -n "$from_editor" ]
then
    start_mode_in_tty editor "$this_tty"

    touch "$path_tmp/links_loop.txt"
    $editor "$path_tmp/links_loop.txt"

    this_mode=stdout
    start_mode_in_tty "$this_mode" "$this_tty"

    clean_file "$path_tmp/links_loop.txt"
    if [ -s "$path_tmp/links_loop.txt" ]
    then
	start_file="$path_tmp/links_loop.txt"
	standard_box
    else
	unset from_editor
    fi
    
    post_readline=true
fi


#### READLINE
{
    if [ -z "$start_file" ]
    then
        start_file="$path_tmp/links_loop.txt"
        if ! check_instance_prog
        then
	    echo "$pid_prog" > "$path_tmp/.pid.zdl"
        fi

        if [ -z "$from_editor" ] &&
	       [ "$no_stop" != true ]
        then
	    if [ "$this_mode" != "daemon" ]
	    then
	        [ "$live_streaming" != true ] &&
		    binding=true
	        standard_box
	        bindings
	        
	        if [ "$live_streaming" == true ]
	        then
		    display_set_livestream 2>&1

	        else
                    readline_links 2>&1
		    # $path_usr/readline_links.sh 2>&1
                    # case "$?" in
                    #     1) bindings_quit;;
                    #     2) bindings_kill;;
                    # esac

                    unset binding
		    post_readline=true
		    cursor off
                    
		    bind -x "\"\ex\":\"\"" 2>/dev/null
		    bind -x "\"\C-x\":\"\"" 2>/dev/null
	        fi
	    fi
        fi
        
        if [ -f "$start_file" ]
        then
	    clean_file "$start_file"
	    echo >> links.txt 2>/dev/null
	    date >> links.txt 2>/dev/null
	    cat "$start_file" >> links.txt 2>/dev/null
	    
        else
	    rm -f "$path_tmp/rewriting"
        fi
    fi


    if check_instance_daemon &&
            ( [ "$already_daemon" == true ] || [ "$this_mode" != daemon ] ) ||
	        check_instance_prog	    
    then
        redirect_links

    else
        echo "$pid_prog" > "$path_tmp/.pid.zdl"
        rm -f "$path_tmp"/livestream_run.txt
    fi


    [ -f "$path_tmp/downloader" ] ||    
        echo "$downloader_in" > "$path_tmp/downloader"


    reset_exit

    check_xdcc_links
    check_linksloop_livestream

    if [ "$this_mode" == "daemon" ]
    then
        while true
        do
	    main_loop &>/dev/null || break
	    test -s "$path_tmp"/links_loop.txt &&
	        clean_livestream
        done 

    else    
        if [ "$lite_mode" == true ] ||
	       [ "$this_mode" == lite ]
        then
	    lite_mode=true
	    this_mode=daemon
	    start_mode_in_tty "lite" "${this_tty}" 
        fi
        
        rm -f "$path_tmp/stop-binding"     

        echo "$COLUMNS" > "$path_tmp"/columns
        (
	    if [[ "$this_mode" =~ ^(daemon|lite)$ ]]
	    then
	        main_loop &>/dev/null 
	    else
	        main_loop 2>/dev/null 
	    fi
        ) &
        disown
        loops_pid=$!
        
        [ "$lite_mode" == true ] &&
	    this_mode=lite

        cursor off

        ## sblocca read_binding, che non si temporizza con "-e" (serve un numero intero: perché?)
        bindings
        read -t 0.1

        #set -m
        
        [ "$this_mode" == "lite" ] && fclear

        while check_pid $loops_pid ||
	        check_start_file
        do
	    echo "$COLUMNS" > "$path_tmp"/columns
	    
	    if [ "$this_mode" == "lite" ]
	    then	    
	        show_downloads_lite
            fi

            if check_start_file 
            then
	        read_binding
            fi
            
	    if [ -f "$path_tmp"/stop-binding ]
	    then
	        rm "$path_tmp"/stop-binding
	        break
	    fi
	    
        done #2>/dev/null 
    fi 

    noproxy

    wait $loops_pid

    if [ "$lite_mode" == true ] ||
           [ "$this_mode" == lite ]
    then
        # kill -9 $loops_pid
        show_downloads_lite no-clear
	this_mode=stdout
	unset lite_mode
	start_mode_in_tty "stdout" "${this_tty}"	
    fi

    post_process

    if [ -n "${pipe_out[*]}" ] && [ "$pipe_done" != 1 ]
    then
        data_stdout
        pipe_files
    fi

    if ! ( check_start_file && ( check_exit || check_instance_gui ) )
    then
        if [ -f "$path_tmp"/.pid.zdl ]
        then
	    read test_pid < "$path_tmp"/.pid.zdl
        fi

        if [ "$test_pid" == "$pid_prog" ] &&
               ! check_start_file
        then
            this_mode=stdout
            print_header
            separator-
            print_c 1 "$(gettext "Download completed")" 
            separator-
            print_header
            
            rm -rf "$path_tmp"
        fi
        
    else
        kill_downloads
    fi

    stty sane
    cursor on

    if [ -f "$file_log" ]
    then
        print_c 0 ""
        print_c 3 "\n$(gettext "In %s there is a file that contains a list of operations of %s.")" "$PWD" "$PROG"
        print_c 4 "$(gettext "To read it, enter:")"
        print_c 0 "${Bold}cat $PWD/$file_log${Color_Off}\n"
    fi


    if [ "$xterm_stop_checked" == "true" ]
    then
        xterm_stop
    fi
    
    set -o history
    echo -en "\e[0m\e[J"
    kill %? &>/dev/null
} 2>/dev/null
