#!/bin/bash
#pMusic - func_add
#GPL - Copyright Sigmund Berglund

[ "$PTR_BTN" = "3" ] && exit #right-click menu

$APPDIR/func -reset_gtk
export TEXTDOMAIN=pmusic

check_source (){
	#check if exist
	if [ ! -s "$SOURCE" ]; then
		LC_ALL=C grep -F "$(basename "$SOURCE")|" "$STORAGE_DIR/index_mymusic" | cut -d'|' -f14 | grep -vFm1 "$SOURCE" > $WORKDIR/SOURCE_ALT
		if [ ! -s "$(<$WORKDIR/SOURCE_ALT)" ]; then #if basename is in db, pMusic will search for alternative path.
			echo > $WORKDIR/flag_fix_db #avoid quick_index-msg at next check_source.
			fix_db
			exit
		fi
	elif [ -f $WORKDIR/flag_fix_db ]; then
		rm $WORKDIR/flag_fix_db
	#if not in db, allow update of database
	elif [ ! "`LC_ALL=C grep -F "$SOURCE" "$STORAGE_DIR/index_mymusic"`" ]; then
		echo "$SOURCE" > $WORKDIR/source_checked
		echo 1 > $WORKDIR/maingui_notebook_page
		cp -f "$APPDIR/themes/$THEME/question.svg" $WORKDIR/albumart.jpg
		[ ! -f $WORKDIR/gui_is_running ] && sleep 1
		[ ! -f $WORKDIR/gui_is_running ] && sleep 1
		[ ! -f $WORKDIR/gui_is_running ] && sleep 1
		[ ! -f $WORKDIR/gui_is_running ] && sleep 1
		echo true > $WORKDIR/UPDATE_GUI
	fi
}

export -f check_source

fix_db (){
SOURCE="`echo "$SOURCE" | cut -d':' -f2-`"
export box='
<window title="pMusic" icon-name="pmusic" window_position="2">
 <vbox space-expand="false" space-fill="false">
  <frame>
   <pixmap icon_size="6" space-expand="false" space-fill="false"><input file stock="gtk-dialog-question"></input></pixmap>
   <text use-markup="true" space-expand="false" space-fill="false"><label>"<b>'$(gettext 'Database Mismatch - File does not exist')':</b>"</label></text>
   <text use-markup="true" space-expand="false" space-fill="false"><label>"<small><small>'${SOURCE}'</small></small>



'$(gettext 'What occurred?')'"</label></text>
  </frame>
  <vbox space-expand="true" space-fill="true">
   <hbox space-expand="false" space-fill="false">
	<entry accept="file" fs-title="Pmusic" space-expand="true" space-fill="true">
	 <variable>MOVE_FILE</variable>
	 <input>echo "'$SOURCE'"</input>
	</entry>
	<button space-expand="false" space-fill="false">
	 <input file stock="gtk-open"></input>
	 <action type="fileselect">MOVE_FILE</action>
	 <variable>BUTTON_MOVE_FILE</variable>
	</button>
	<sensitive>false</sensitive>
	<variable>HBOX_MOVE_FILE</variable>
   </hbox>
   <hbox visible="false" space-expand="false" space-fill="false">
	<entry accept="directory" fs-title="Pmusic" space-expand="true" space-fill="true">
	 <variable>MOVE_DIR</variable>
	 <input>dirname "'$SOURCE'"</input>
	</entry>
	<button space-expand="false" space-fill="false">
	 <input file stock="gtk-open"></input>
	 <action type="fileselect">MOVE_DIR</action>
	 <variable>BUTTON_MOVE_DIR</variable>
	</button>
	<sensitive>false</sensitive>
	<variable>HBOX_MOVE_DIR</variable>
   </hbox>
   
   
	<radiobutton visible="false"></radiobutton>
	<radiobutton space-expand="false" space-fill="false">
	 <variable>RADIO_MOVE_FILE</variable>
	 <label>"'$(gettext 'File has been moved to')'..."</label>
	 <action>if true enable:HBOX_MOVE_FILE</action>
	 <action>hide:HBOX_MOVE_DIR</action>
	 <action>show:HBOX_MOVE_FILE</action>
	 <action>enable:BUTTON_FIX</action>
	</radiobutton>
	<radiobutton space-expand="false" space-fill="false">
	 <variable>RADIO_MOVE_DIR</variable>
	 <label>"'$(gettext 'Complete directory has been moved to')'..."</label>
	 <action>if true enable:HBOX_MOVE_DIR</action>
	 <action>hide:HBOX_MOVE_FILE</action>
	 <action>show:HBOX_MOVE_DIR</action>
	 <action>enable:BUTTON_FIX</action>
	</radiobutton>
	<radiobutton space-expand="false" space-fill="false">
	 <variable>RADIO_DELETE</variable>
	 <label>"'$(gettext 'File has been deleted')'"</label>
	 <action>if true disable:HBOX_MOVE_FILE</action>
	 <action>if true disable:HBOX_MOVE_DIR</action>
	 <action>enable:BUTTON_FIX</action>
	</radiobutton>
   </vbox>
   
   <hbox>
	<vbox space-expand="false" space-fill="false">
	 <text space-expand="true" space-fill="true"><label>""</label></text>
	 <hbox space-expand="false" space-fill="false">
	  <button cancel></button>
	  <button space-expand="false" space-fill="false">
	   <input file icon="gtk-refresh"></input>
	   <label>" '$(gettext 'Update the entire pMusic database')'"</label>
	   <action>'$APPDIR'/func_index -update_index &</action>
	   <action type="exit">EXIT</action>
	  </button>
	 </hbox>
	</vbox>
	<text space-expand="true" space-fill="true"><label>""</label></text>
	<button image-position="2" height-request="70" space-expand="false" space-fill="false">
	 <variable>BUTTON_FIX</variable>
	 <input file icon="gtk-apply"></input>
	 <label>"     '$(gettext 'Fix it')'     "</label>
	 <sensitive>false</sensitive>
	 <action type="exit">update_db</action>
	</button>
	
   </hbox>
 </vbox>
</window>'
I=$IFS; IFS=""
for STATEMENTS in  $($GTKDIALOG -p box); do
	eval $STATEMENTS
done
IFS=$I

if [ $RADIO_MOVE_FILE = true ]; then
	if [ -f "$MOVE_FILE" ]; then
		( flock -e 200
			grep -F "$SOURCE" "$STORAGE_DIR/index_mymusic" | awk -F'|' -v VAR1="$MOVE_FILE" '{print VAR1 "|" $2 "|" $3 "|" $4 "|" $5 "|" $6 "|" $7 "|" $8 "|" $9 "|" $10 "|" $11 "|" $12 "|" $13 "|" VAR1 "|" $15 "|" $16 "|" $17 "|" $18 "|" $19 "|" $20 "|" $21}' > $WORKDIR/tmp_update_db
			grep -Fv "$SOURCE" "$STORAGE_DIR/index_mymusic" >> $WORKDIR/tmp_update_db
			mv $WORKDIR/tmp_update_db "$STORAGE_DIR/index_mymusic"
		) 200>$WORKDIR/mymusic_db.lockfile 
		#update sourcelist
		echo "sed -i \"s%$SOURCE%$MOVE_FILE%\" $WORKDIR/sourcelist" > $WORKDIR/exec
		echo "sed -i \"s%$SOURCE%$MOVE_FILE%\" \"$STORAGE_DIR/favorites\"" > $WORKDIR/exec
		sed -i -e 's/\&/\\\&/g' -e 's/\[/\\\[/g' -e 's/\]/\\\]/g' -e s/\`/\\\\\`/g $WORKDIR/exec
		chmod 722 $WORKDIR/exec
		$WORKDIR/exec
	else
		TXT1="$(gettext 'File does not exist')"
		. $APPDIR/box_ok
	fi
elif [ $RADIO_MOVE_DIR = true ]; then
	if [ -d "$MOVE_DIR" ]; then
		OLD_DIR="`dirname "$SOURCE"`"
		grep -F "$OLD_DIR" "$STORAGE_DIR/index_mymusic" > $WORKDIR/tmp_update_db1
		#check if target sounds logical
		TMP="`basename "$SOURCE"`"
		if [ ! -f "${MOVE_DIR}/${TMP}" ]; then
			TXT1="$(gettext "Nope, this can't be the correct directory, No such files found.")" #'
			. $APPDIR/box_ok
			exit
		fi
		#---
		echo "$(gettext 'Redefining database')." > $WORKDIR/splashtext
		$APPDIR/box_splash &

		( flock -e 200
			grep -Fv "$OLD_DIR" "$STORAGE_DIR/index_mymusic" > $WORKDIR/tmp_update_db
			while read I; do
				TMP="`echo "$I" | cut -d'|' -f1`"
				FILENAME="`basename "$TMP"`"
				echo "$I" | awk -F'|' -v VAR1="${MOVE_DIR}/${FILENAME}" '{print VAR1 "|" $2 "|" $3 "|" $4 "|" $5 "|" $6 "|" $7 "|" $8 "|" $9 "|" $10 "|" $11 "|" $12 "|" $13 "|" VAR1 "|" $15 "|" $16 "|" $17 "|" $18 "|" $19 "|" $20 "|" $21}' >> $WORKDIR/tmp_update_db
				
			done < $WORKDIR/tmp_update_db1
			sort -ust'|' -k1,1 -o $WORKDIR/tmp_update_db2 $WORKDIR/tmp_update_db

		    mv "$STORAGE_DIR/index_mymusic" "$STORAGE_DIR/index_mymusic.bak"
			mv $WORKDIR/tmp_update_db2 "$STORAGE_DIR/index_mymusic"
		) 200>$WORKDIR/mymusic_db.lockfile
		echo 100 > $WORKDIR/splash #reset progress bar
		#update gui
		echo "sed -i \"s%$OLD_DIR%$MOVE_DIR%g\" $WORKDIR/sourcelist" > $WORKDIR/exec
		echo "sed -i \"s%$OLD_DIR%$MOVE_DIR%g\" \"$STORAGE_DIR/favorites\"" > $WORKDIR/exec
		echo "sed -i \"s%$OLD_DIR%$MOVE_DIR%g\" $WORKDIR/trackinfo_album" > $WORKDIR/exec #album-tab
		sed -i -e 's/\&/\\\&/g' -e 's/\[/\\\[/g' -e 's/\]/\\\]/g' -e s/\`/\\\\\`/g $WORKDIR/exec
		chmod 722 $WORKDIR/exec
		$WORKDIR/exec
	else
		TXT1="$(gettext 'Directory does not exist')"
		. $APPDIR/box_ok
	fi
elif [ $RADIO_DELETE = true ]; then
	#remove from db
	( flock -e 200
		grep -vF "$SOURCE" "$STORAGE_DIR/index_mymusic" > $WORKDIR/tmp_radio_del
		mv $WORKDIR/tmp_radio_del "$STORAGE_DIR/index_mymusic"
	) 200>$WORKDIR/mymusic_db.lockfile 
	#remove from sourcelist
	grep -vF "$SOURCE" $WORKDIR/sourcelist > $WORKDIR/tmp
	mv $WORKDIR/tmp $WORKDIR/sourcelist
	#remove from bookmarks
	grep -v "|$SOURCE$" "$STORAGE_DIR/favorites" > $WORKDIR/tmp
	mv -f $WORKDIR/tmp "$STORAGE_DIR/favorites"
	#remove from playqueue
	grep -v "|${SOURCE}|" $WORKDIR/playlist > $WORKDIR/tmp
	mv -f $WORKDIR/tmp $WORKDIR/playlist
	echo true > $WORKDIR/UPDATE_GUI
fi
echo true > $WORKDIR/UPDATE_SOURCELIST
echo true > $WORKDIR/UPDATE_TRACKINFO
}

export -f fix_db




case "$1" in
-check_source)
	check_source
	;;
-fix_db)
	fix_db
	;;
-smartadd)
	echo "$(gettext 'Add more')..." > $WORKDIR/splashtext
	$APPDIR/box_splash progress &
	SMARTADD_NR=$2
	SMARTADD_RANDOM=$3
	SMARTADD_RATE=$4
	SMARTADD_SOURCE=$5
	AUDIO_FORMATS2="`echo "$AUDIO_FORMATS" | sed 's/\\$/\\\|/g'`" #example: |/path/file.mp3|
	#what is add source
	if [ "$SMARTADD_SOURCE" = "$(gettext 'My local music (DB)')" ]; then
		if [ $SMARTADD_RATE -ge 1 ]; then #rating is set
			echo "$(gettext 'Search rated tracks in DB')" > $WORKDIR/splashtext
			$APPDIR/func_rating -buildlist 1 "$STORAGE_DIR/index_mymusic" 0 $SMARTADD_RATE > $WORKDIR/tmp_smartadd_input
		else
			ln -s "$STORAGE_DIR/index_mymusic" $WORKDIR/tmp_smartadd_input
		fi
	else #sourcelist
		if [ $SMARTADD_RATE -ge 1 ]; then #rating is set 
			#sourcelist may not have rating info (ie. when browsing). If so, we use db
			if [ ! "`grep -iE "$AUDIO_FORMATS2|cdda:|://" $WORKDIR/sourcelist | sort -rnst'|' -k 9,9 | head -n1 | cut -d'|' -f9`" ] ; then
				cut -d'|' -f1 $WORKDIR/sourcelist | cut -d: -f2- | grep -iE "$AUDIO_FORMATS|cdda:|://" > $WORKDIR/tmp_smartadd
				while read I; do
					if [ $UTF8 = false ]; then
						LC_ALL=C grep -Fm1 "$I" "$STORAGE_DIR/index_mymusic" >> $WORKDIR/tmp_smartadd2
					else
						grep -Fm1 "$I" "$STORAGE_DIR/index_mymusic" >> $WORKDIR/tmp_smartadd2
					fi
				done < $WORKDIR/tmp_smartadd
				$APPDIR/func_rating -buildlist 1 $WORKDIR/tmp_smartadd2 0 $SMARTADD_RATE > $WORKDIR/tmp_smartadd_input
			else #rating exist in sourcelist
				grep -iE "$AUDIO_FORMATS2|cdda:|://" $WORKDIR/sourcelist | sort -rnst'|' -k 9,9 > $WORKDIR/tmp_smartadd
				while read I; do
					if [ "`cut -d'|' -f9 <<< "$I"`" -lt $SMARTADD_RATE ]; then
						break
					else
						echo "$I" >> $WORKDIR/tmp_smartadd_input
					fi
				done < $WORKDIR/tmp_smartadd
			fi
		else
			ln -s $WORKDIR/sourcelist $WORKDIR/tmp_smartadd_input
		fi
	fi
	#specify total numbers in list
	n=`grep -c ^ $WORKDIR/tmp_smartadd_input` #also used in random seed
	if [ $SMARTADD_NR -gt $n ] && [ $SMARTADD_RANDOM = false ]; then SMARTADD_NR=$n; fi
	[ "$SMARTADD_NR" = "$(gettext 'All')" ] && SMARTADD_NR=$n
	[ ! $SMARTADD_NR -gt 0 ] && SMARTADD_NR=1 #in case no valid number
	#What limits the number of tracks to add
	if [ $SMARTADD_RANDOM = true ]; then #if adding randomly, only $SMARTADD_NR is the limit
		echo -n > $WORKDIR/tmp_smartadd_input2
		for I in $(seq 1 $SMARTADD_NR); do echo hello >> $WORKDIR/tmp_smartadd_input2; done
	else #if adding by sort order, the input file is the limitation
		ln -s $WORKDIR/tmp_smartadd_input $WORKDIR/tmp_smartadd_input2
	fi
	#---
	COUNT=1
	echo -n > $WORKDIR/pmusic.add
	while read J; do
		if [ $SMARTADD_RANDOM = true ]; then
			r=$((RANDOM % n))
			r=$(($r+1))
			I="`cut -d'|' -f1 $WORKDIR/tmp_smartadd_input | head -n $r | tail -n 1`"
		else
			I="`cut -d'|' -f1 <<< "$J"`"
		fi
		[ "$(grep "^[0-9]" <<< "$I")" ] && I="$(cut -d: -f2- <<< "$I")" #remove unique source-nr before adding
		case $I in
			*://*)
				ARTIST="`grep -Fm1 "$I" $WORKDIR/tmp_smartadd_input | cut -d'|' -f2`"
				TITLE="`grep -Fm1 "$I" $WORKDIR/tmp_smartadd_input | cut -d'|' -f3`"
				LENGTH="`grep -Fm1 "$I" $WORKDIR/tmp_smartadd_input | cut -d'|' -f12`"
				#jamendo is a bit out of standard
				if [ ! "$LENGTH" ]; then
					TMP="`grep -Fm1 "$I" $WORKDIR/tmp_smartadd_input | cut -d'|' -f8`"
					LENGTH="`$APPDIR/func -sec2time $TMP`"
				fi
				;;
			*) #look in index for extra info
				ARTIST="`grep -Fm1 "$I" $WORKDIR/tmp_smartadd_input | cut -d'|' -f2 | sed 's/    //'`"
				TITLE="`grep -Fm1 "$I" $WORKDIR/tmp_smartadd_input | cut -d'|' -f3`"
				LENGTH="`grep -Fm1 "$I" $WORKDIR/tmp_smartadd_input | cut -d'|' -f12`"
				;;
		esac
		#add only if valid item
		if [ "`grep -E "^/|^http:|^https:|^cdda:" <<< "$I"`" ] && [ ! -d "$I" ]; then
			if [ "$TITLE" ]; then
				echo "$LENGTH|$ARTIST - $TITLE|$I" >> $WORKDIR/pmusic.add
			else
				echo "$LENGTH|$ARTIST|$I" >> $WORKDIR/pmusic.add
			fi
			[ $COUNT -ge $SMARTADD_NR ] && break
			COUNT=$(($COUNT+1))
		fi
	done < $WORKDIR/tmp_smartadd_input2
	rm $WORKDIR/tmp_smartadd*
	echo 100 > $WORKDIR/splash #reset progress bar
	$APPDIR/func_add -add $WORKDIR/pmusic.add
	$APPDIR/func_config -write_config #save smartadd settings
	;;
-add)
	[ "$2" ] && SOURCE="$2"
	[ -d "${SOURCE}" ] && exit #directory - browse instead of add
	rm -f $WORKDIR/history #reset undo/redo function
	#check for timestamp from bookmark
	TMP="$(grep -E "?:??] /" <<< "$SOURCE")"
	if [ "$TMP" ]; then
		SOURCE="`echo "$TMP" | awk -F ']' '{print $2}' | cut -c2-`"
		TIME="`echo "$TMP" | awk -F ']' '{print $1}' | cut -d'[' -f2`"
		MIN=`echo $TIME | cut -d':' -f1`
		SEC=`echo $TIME | cut -d':' -f2`
		echo "$[($MIN*60)+$SEC]" > $WORKDIR/SS
		echo true > $WORKDIR/TIMESTAMP
		ENSURE_PLAY=true #playlist has no internal structure to handle timestamps. --> must play imediatly
	fi
	#ENSURE_PLAY is also defined by the -P switch. 
	if [ "$ENSURE_PLAY" = "true" ]; then
		$APPDIR/func_store_playlist
		$APPDIR/func -new
	fi

	#if nothing is playing, play added song. NOTE!, this also happens if track is paused.
	if [ ! -s $WORKDIR/AUTOPLAY ]; then #if exist, another add-instance is working as well as this one
		ps -eo pid,s,command > $WORKDIR/tmp_add
		if [ ! "`grep aplay $WORKDIR/tmp_add`" ] || [ "`grep aplay $WORKDIR/tmp_add | grep ' T '`" ]; then
			echo true > $WORKDIR/AUTOPLAY
		elif [ ! -s $WORKDIR/playlist ]; then #if nothing in playlist, play added song
			echo true > $WORKDIR/AUTOPLAY
		fi
	fi
	#read input
	case $SOURCE in
	pmusicbrowse_*)	exit ;; #these will be executed in -func -browse. The difference is that refresh of sourcelist is made at once. Not via timer as for actions here in func_add.
	pmusic_*) #redirect all navigations here for speed reasons
		case $SOURCE in 
			pmusic_history)					$APPDIR/func -index_history;					;;
			pmusic_history:*)				SEARCH="`echo "$SOURCE" | cut -d: -f2- | cut -d'|' -f1`"
											cp -f "$STORAGE_DIR"/history_files/$SEARCH $WORKDIR/sourcelist
											echo true > $WORKDIR/UPDATE_SOURCELIST
																							;;
			pmusic_file_search)				$APPDIR/func -pfilesearch;						;;
			pmusic_index)					$APPDIR/func_index -update_index;				;;
			pmusic_songs)					$APPDIR/func -index_songs;						;;
			pmusic_collections)				$APPDIR/func -index_playlists;					;;
			pmusic_radiohits)				$APPDIR/func_radiohits;							;; 
			pmusic_radiohits:*)				SOURCE="`echo "$SOURCE" | cut -d: -f2-`"
											$APPDIR/func -browse_radiohits "$SOURCE"		;; 
			pmusic_radio)					$APPDIR/func_radio;								;;
			pmusic_radio_country)			$APPDIR/func -radio -country;					;;
			pmusic_radio_genre)				$APPDIR/func -radio -genre;						;;
			pmusic_rating)					$APPDIR/func_rating -custom;					;;
			pmusic_rating_month)			echo "|$(gettext 'Searching last month')..." > $WORKDIR/sourcelist
											echo true > $WORKDIR/UPDATE_SOURCELIST
											$APPDIR/func_rating -buildlist "$(($(date +%s)-2592000))" "$STORAGE_DIR/index_mymusic" > $WORKDIR/tmp
											sort -rnst"|" -k9,9 $WORKDIR/tmp | grep -vF "|0|" > $WORKDIR/sourcelist
											echo true > $WORKDIR/UPDATE_SOURCELIST			;;
			pmusic_recent)					$APPDIR/func -index_recent;						;;
			pmusic_podcast)					$APPDIR/func_podcast;							;;
			pmusic_cd_audio)				$APPDIR/func_cd -read_cd;						;;
			pmusic_bookmarks)				$APPDIR/func_bookmarks -manage_bookmarks;		;;
			pmusic_webmusic_manager)		$APPDIR/func_webmusic -webmusic_manager;		;;
			pmusic_webmusic)				$APPDIR/func_webmusic -webmusic;				;; 
			pmusic_webmusic_back)			$APPDIR/func_webmusic -webmusic_back;			;; 
			pmusic_webmusic_artist*)		SOURCE="`echo "$SOURCE" | cut -d: -f2`"
											$APPDIR/func_webmusic -webmusic_artist "$SOURCE"
				;; 
			pmusic_webmusic_album*)
				SOURCE="`echo "$SOURCE" | cut -d: -f2`"
				if [ "$SOURCE" = "youtube" ]; then #go back
					$APPDIR/func_webmusic -webmusic
				else
					$APPDIR/func_webmusic -webmusic_album "$SOURCE"
				fi
				;;
			pmusic_top100*)
				TMP="`echo "$SOURCE" | cut -d_ -f3`"
				$APPDIR/func_webmusic -jamendo_top100 $TMP
				;;
		esac
		exit
		;;
	*cdda:*)
		[ "$(grep "^[0-9]" <<< "$SOURCE")" ] && SOURCE="$(cut -c 21- <<< "$SOURCE")" #remove unique source-nr before adding
		echo "||$SOURCE" > $WORKDIR/songs_in_list
		;;
	*://*|*:+[0-9]*) #streaming
		SOURCE_ORG="$SOURCE" #working with jamendo index, SOURCE is getting full length URL, and is not existing in webmusic_index_jamendo
		[ "$(grep "^[0-9]" <<< "$SOURCE_ORG")" ] && SOURCE="$(cut -d: -f2- <<< "$SOURCE_ORG")" #remove unique source-nr before adding
		#if taken from jamendo index, URL is stripped
		if [ "$(grep "^+[0-9]" <<< "$SOURCE")" ]; then
			SOURCE="$(sed "s%+%https://storage-new.newjamendo.com/tracks/%" <<< "$SOURCE")_96.mp3"
		fi
		#---
		if [ "`echo $SOURCE | grep -E "youtube.com|jamendo.com"`" ] && [ ! "`grep -F "$SOURCE" $WORKDIR/sourcelist | cut -d'|' -f2 | grep -F 'http'`" ]; then #tags exist either from webmusic index or from jamendo.com
			TITLE="`grep -Fm1 "$SOURCE_ORG" $WORKDIR/sourcelist | cut -d'|' -f3`"
			[ "`echo "$TITLE" | grep -E "?:??]http"`" ] && TITLE="`echo "$TITLE" | cut -d']' -f2`" #if add bookmark with timestamp from sourcelist
			if [ ! "`grep -Fm1 "$SOURCE_ORG" $WORKDIR/sourcelist | cut -d'|' -f2`" ]; then 
				[ ! "$TITLE" ] && TITLE="$ARTIST" #if adding from recent index, there is no more than 2 coloumns
				echo "|$TITLE|$SOURCE" > $WORKDIR/songs_in_list
			else
				ARTIST="`grep -Fm1 "$SOURCE_ORG" $WORKDIR/sourcelist | cut -d'|' -f2 | sed "s/^    //"`" #expanded lists has 4 spaces in front
				LENGTH="`grep -Fm1 "$SOURCE_ORG" $WORKDIR/sourcelist | cut -d'|' -f12`" #youtube requires length set. For jamendo it is not strictly reqired, but a lot faster than ffmpeg -i
				[ ! "$LENGTH" ] && LENGTH="`grep -Fm1 "$SOURCE_ORG" $WORKDIR/sourcelist | cut -d'|' -f8`" #jamendo Top100 doesn't follow the standard fully, and places length in column 6 (because no option of blank columns at download). 
				[ "$LENGTH" -gt "1" ] && LENGTH=`$APPDIR/func -sec2time $LENGTH` #transform seconds into a human readable length
				if [ "$TITLE" ]; then
					echo "$LENGTH|$ARTIST - $TITLE|$SOURCE" > $WORKDIR/songs_in_list
				else
					echo "$LENGTH|$ARTIST|$SOURCE" > $WORKDIR/songs_in_list
				fi
			fi
		else
			#if we are inside the radio frontend we want to play the stream straight away
			if [ "`grep -F '/.Radio' <<< "$PMUSIC_FRONTEND"`" ]; then
#				$APPDIR/func_store_playlist &
				sleep 0.2; $APPDIR/func -new
				echo true > $WORKDIR/AUTOPLAY
			fi
			echo "00:00||$SOURCE|" > $WORKDIR/songs_in_list
		fi
		USE_META=false
		;;
	*.m3u)
		check_source &
		#splash if playlist contains more than 1 entries --> A m3u could be one single url
		if [ `grep -vE "#EXT|#M3U" "$SOURCE" | wc -l | cut -d' ' -f1` -ge 3 ]; then
			echo "$(gettext 'Importing playlist')..." > $WORKDIR/splashtext
			$APPDIR/box_splash progress &
		fi
		#---
		echo "$SOURCE" > $WORKDIR/last_added_playlist
		#check if path is valid in playlist
		echo -n > $WORKDIR/songs_in_list
		while read I; do
			[ "`echo "$I" | grep -E '#EXTM3U|#M3U'`" ] && continue #header info. We don't use this
			if [ "`echo "$I" | grep '#EXT'`" ]; then
				#we use #EXT info in m3u if available
				LENGTH="`echo "$I" | cut -d: -f2- | cut -d, -f1`"
				if [ "$LENGTH" -gt 0 ]; then
					LENGTH=`$APPDIR/func -sec2time $LENGTH` #m3u stores length in seconds, we want a human readable length
				else
					LENGTH=""
				fi
				NAME="`echo "$I" | cut -d, -f2-`"
				continue #if EXT line, go to next line...
			fi
			#Adress (path/URL)
			case $I in
				cdda:*) #CD-audio
					ADR="$I"
					;;
				*://*) #streaming
					ADR="$I"
					;;
				*/*) #path is defined in playlist
					if [ -s "$I" ]; then #path exist, use path in playlist
						ADR="$I"
					else #Use current dir
						TMP="`dirname "$I"`"
						TMP2="`basename "$I"`"
						ADR="$TMP/$TMP2"
					fi
					;;
				*) #no path for files in list. Use current dir
					TMP="`dirname "$SOURCE"`"
					ADR="$TMP/$I"
					;;
			esac
			echo "$LENGTH|$NAME|$ADR" | tr -d '\r' >> $WORKDIR/songs_in_list #tr is removing carriage return
		done < "$SOURCE"
		;;
	*.pls)
		check_source &
		#splash if playlist contains more than 1 entries
		if [ `grep "^File" "$SOURCE" | wc -l` -ge 3 ]; then
			echo "$(gettext 'Importing playlist')..." > $WORKDIR/splashtext
			$APPDIR/box_splash progress &
		fi
		#---
		echo "$SOURCE" > $WORKDIR/last_added_playlist
		echo -n > $WORKDIR/songs_in_list
		while read I; do
			[ ! "`grep -i "^File" <<< "$I"`" ] && continue
			NR="`cut -d= -f1 <<< "$I" | cut -d'e' -f2`"
			ADR="`cut -d= -f2 <<< "$I" | sed 's|file://||'`"
			#length
			TMP="`grep -Fi "Length${NR}=" "$SOURCE" | cut -d= -f2`"
			if [ "$TMP" -gt 0 ]; then
				LENGTH=`$APPDIR/func -sec2time $TMP` #pls stores length in seconds, we want a human readable length
			else
				LENGTH=""
			fi
			#---
			NAME="`grep -Fi "Title${NR}=" "$SOURCE" | cut -d= -f2`"
			[ ! "$NAME" ] && NAME="`basename "$ADR"`"
			echo "$LENGTH|$NAME|$ADR" | tr -d '\r' >> $WORKDIR/songs_in_list #tr is removing carriage return
		done < "$SOURCE"
		;;
	*.asx)
		check_source &
		#splash if playlist contains more than 1 entries
		if [ `grep -Fi 'href=' "$SOURCE" | wc -l` -ge 3 ]; then
			echo "$(gettext 'Importing playlist')..." > $WORKDIR/splashtext
			$APPDIR/box_splash progress &
		fi
		#---
		echo "$SOURCE" > $WORKDIR/last_added_playlist
		echo -n > $WORKDIR/songs_in_list
		while read I; do
			[ ! "`grep -Fi 'href=' <<< "$I"`" ] && continue
			ADR="`cut -d'"' -f2 <<< "$I" | awk -F 'file://' '{print $2}'`"
			echo "||$ADR" | tr -d '\r' >> $WORKDIR/songs_in_list #tr is removing carriage return
		done < "$SOURCE"
		;;
	*.add) #internal (ie. add directory from cli)
		grep -E "\|/|cdda:" "$SOURCE" > $WORKDIR/songs_in_list
		;;
	*.pmd)
		$APPDIR/func -check_playlist "$SOURCE" & #check paths of tracks in list
		echo -n > $WORKDIR/songs_in_list
		while read I; do
			LENGTH="`echo "$I" | cut -d'|' -f12`"
			ARTIST="`echo "$I" | cut -d'|' -f2`"
			TITLE="`echo "$I" | cut -d'|' -f3`"
			NAME="$ARTIST - $TITLE"
			ADR="`echo "$I" | cut -d'|' -f1`"
			echo "$LENGTH|$NAME|$ADR" >> $WORKDIR/songs_in_list
		done < "$SOURCE"
		;;
	*.pmu)
		check_source & #check if pmu exist in db
		$APPDIR/func -check_playlist "$SOURCE" & #check paths of tracks in list
		echo "$SOURCE" > $WORKDIR/last_added_playlist
		#since *.pmu is the native format, we just drop directly into list 
		if [ "$(<$WORKDIR/ADDMODE)" = "next" ] && [ "$(<$WORKDIR/PLAYLIST)" ]; then #add the song after selection. This is slower, so do not use for multiple adds.
			( flock -e 201
				LINE_SELECTED="`grep -m1 "$(<$WORKDIR/PLAYLIST)" $WORKDIR/playlist`"
				grep -w -B100000 "$LINE_SELECTED" $WORKDIR/playlist > $WORKDIR/tmp_add
				cat "$SOURCE" >> $WORKDIR/tmp_add
				grep -w -A100000 "$LINE_SELECTED" $WORKDIR/playlist | tac | head -n -1 | tac >> $WORKDIR/tmp_add
				mv $WORKDIR/tmp_add $WORKDIR/playlist
			) 201>$WORKDIR/playlist.lockfile 
		else #add at the end of list
			( flock -e 201
				cat "$SOURCE" >> $WORKDIR/playlist
			) 201>$WORKDIR/playlist.lockfile
		fi
		#play added song if marked earlier in this script.
		if [ -s $WORKDIR/AUTOPLAY ]; then
			$APPDIR/func_player -play -autoplay &
		fi
		$APPDIR/func -statusbar_playlist & #update statusbar
		echo -n > $WORKDIR/songs_in_list #no more to add
		#we need a delay here to update play/pause icon correctly
		sleep 1
		echo true > $WORKDIR/UPDATE_GUI
		;;
	*/*.mid|*/*.kar) #internal 
		[ "$(grep "^[0-9]" <<< "$SOURCE")" ] && SOURCE="$(cut -d: -f2- <<< "$SOURCE")" #remove unique source-nr before adding
		check_source &
		#length
		LENGTH="`grep -Fm1 "$SOURCE" "$STORAGE_DIR"/index_mymusic | cut -d'|' -f12`"
		if [ ! "$LENGTH" ]; then
			TMP="`timidity -OuM8 -o $WORKDIR/tmp_midi.au "$SOURCE" | grep -F 'Playing time' | cut -d'~' -f2 | cut -d' ' -f1`" #seconds
			LENGTH=`$APPDIR/func -sec2time $TMP`
		fi
		echo "$LENGTH|`baseanme $SOURCE`|$SOURCE|`date +%s%N` $SOURCE" > $WORKDIR/songs_in_list
		;;
	*/*) #single file
		[ "$(grep "^[0-9]" <<< "$SOURCE")" ] && SOURCE="$(cut -d: -f2- <<< "$SOURCE")" #remove unique source-nr before adding
		#if source is not valid, it is enough if name is found in DB - if so, pMusic will detect an alternative path 
		check_source &
		if [ ! -s "$SOURCE" ] && [ -s "$(<$WORKDIR/SOURCE_ALT)" ]; then #$WORKDIR/SOURCE_ALT is set in check_source
			SOURCE="$(<$WORKDIR/SOURCE_ALT)"
		fi
		LENGTH="`grep -Fm1 "$SOURCE" "$STORAGE_DIR"/index_mymusic | cut -d'|' -f12`"
		echo "$LENGTH||$SOURCE" > $WORKDIR/songs_in_list
		;;
	*) #search string
		SEARCH="$SOURCE"
		. $APPDIR/func -search_refresh
		exit
		;;
	esac
	#for progress bar
	COUNT=1
	TOTAL=`grep -c '^' $WORKDIR/songs_in_list`
	#---
	cp -f $WORKDIR/playlist $WORKDIR/tmp_playlist
	#add
	while read I; do
		ADR="`cut -d'|' -f3 <<< "$I"`"
		#is adr valid?
		#if length is present we are dealing with a moved file in pmd so this one is ok
		if [ ! "`cut -d'|' -f1 <<< "$I"`" ] && [ ! -s "$ADR" ] && [ ! "`grep -E "^http://|^cdda:|^https://" <<< "$ADR"`" ]; then
			echo "||$(basename "$ADR")|$ADR|0 $ADR" >> $WORKDIR/tmp_playlist
			continue
		fi
		### N A M E ###
		NAME="`echo "$I" | cut -d'|' -f2`"
		if [ ! "$NAME" ]; then
			#use metatag or filename in playlist
			if [ "$USE_META" = "true" ]; then
				case $ADR in
					*cdda:*) NAME="`echo "$ADR" | cut -d':' -f5-`" ;; #CD audio
					*)
						#first see if index already has some info
						ID3_ARTIST="`grep -Fm1 "$ADR" "$STORAGE_DIR"/index_mymusic | awk -F'|' '{print $2}'`"
						ID3_TITLE="`grep -Fm1 "$ADR" "$STORAGE_DIR"/index_mymusic | awk -F'|' '{print $3}'`"
						if [ ! "$ID3_ARTIST" ] && [ ! "$ID3_TITLE" ]; then
							if [ -s "$DB" ]; then
								. $APPDIR/func_id3io "$ADR" -read
								ID3_ARTIST="`grep "$ADR" "$STORAGE_DIR"/index_mymusic | awk -F'|' '{print $2}'`"
								ID3_TITLE="`grep "$ADR" "$STORAGE_DIR"/index_mymusic | awk -F'|' '{print $3}'`"
							fi
							if [ ! "$ID3_ARTIST" ] || [ "`grep -iE "^ $|unknown" <<< "$ID3_ARTIST"`" ]; then 
								NAME="`basename "$ADR" | sed -e 's/\.[^\.]*$//'`"
							else
								[ "$ID3_TITLE" ] && NAME="$ID3_ARTIST - $ID3_TITLE" || NAME="$ID3_ARTIST"
							fi
						elif [ "$ID3_ARTIST" ] && [ ! "$ID3_TITLE" ]; then
							NAME="$ID3_ARTIST"
						elif [ ! "$ID3_ARTIST" ] && [ "$ID3_TITLE" ]; then
							NAME="$ID3_TITLE"
						elif [ "$ID3_ARTIST" ] && [ "$ID3_TITLE" ]; then
							NAME="$ID3_ARTIST - $ID3_TITLE"
						fi
						;;
				esac
			else #use filename
				case $ADR in
					/*) NAME="`basename "$ADR" | sed -e 's/\.[^\.]*$//'`";; #file
					*://*) #URL
						NAME="$ADR"
						[ "`grep "$ADR" "$STORAGE_DIR/favorites"`" ] && NAME="`grep "$ADR" "$STORAGE_DIR/favorites" | cut -d'|' -f1 | awk '{print $2}'`"
						[ "`grep "$ADR" "$STORAGE_DIR/index_radio" 2> /dev/null`" ] && NAME="`grep -m1 "$ADR" "$STORAGE_DIR/index_radio" | cut -d'|' -f2`"
						;;
					*cdda:*) NAME="`echo "$ADR" | cut -d':' -f5-`" #CD-audio
				esac
			fi
		fi
		#convert underscores and %20 --- index_recent may contain (CD) or (www) - remove
		NAME="`echo "$NAME" | tr '_' ' ' | sed -e 's/ (CD)//g' -e 's/ (www)//g' -e 's/%20/ /g'`"
		### L E N G T H ###
		LENGTH="`echo "$I" | cut -d'|' -f1`" #let's try
		if [ ! "$LENGTH" ]; then
			case $I in 
				*cdda:*)
					LENGTH="`echo "$I" | cut -d: -f3-4 | tr -d ' '`";;
				*)
					ffmpeg -i "$ADR" 2> $WORKDIR/tmp_add
					grep -F Duration $WORKDIR/tmp_add | awk '{print $2}' | cut -d"." -f1 > $WORKDIR/tmp_add2
					if [ ! "`cut -d":" -f1 $WORKDIR/tmp_add2`" ]; then
						LENGTH=""
					elif [ "`cut -d":" -f1 $WORKDIR/tmp_add2`" != "00" ] && [ "`cut -d":" -f1 $WORKDIR/tmp_add2`" != 'N/A,' ]; then #time is above 59:59
						HOUR=`cut -d":" -f1 $WORKDIR/tmp_add2 | sed "s/^0//"`
						MIN=`cut -d":" -f2 $WORKDIR/tmp_add2 | sed "s/^0//"`
						SEC=`cut -d":" -f3 $WORKDIR/tmp_add2`
						LENGTH=$((($HOUR*60)+$MIN)):$SEC
					else
						LENGTH=`cut -d":" -f2- $WORKDIR/tmp_add2`
					fi
					;;
			esac
		fi
		### E X E C ###
		EXEC="`echo "$I" | cut -d'|' -f4`" #let's try
		[ ! "$EXEC" ] && EXEC="`date +%s%N` $ADR"
		#---
		if [ "$(<$WORKDIR/ADDMODE)" = "next" ] && [ "$(<$WORKDIR/PLAYLIST_ALL)" ]; then #add the song after playing track
			LINE_SELECTED="$(<$WORKDIR/PLAYLIST_ALL)"
			LINE_NEW="|$LENGTH|$NAME|$ADR|$EXEC"
			grep -F -B 10000 "$LINE_SELECTED" $WORKDIR/tmp_playlist > $WORKDIR/tmp_add
			echo "$LINE_NEW" >> $WORKDIR/tmp_add
			grep -F -A 10000 "$LINE_SELECTED" $WORKDIR/tmp_playlist | tac | head -n -1 | tac >> $WORKDIR/tmp_add
			mv $WORKDIR/tmp_add $WORKDIR/tmp_playlist
		else #add at the end of list
			echo "|$LENGTH|$NAME|$ADR|$EXEC" >> $WORKDIR/tmp_playlist
		fi

		if [ -s $WORKDIR/AUTOPLAY ] && [ $COUNT = 1 ]; then AUTOPLAY_ADR="$ADR"; fi

		#update progressbar
		echo $(($COUNT*100/$TOTAL)) > $WORKDIR/splash
		COUNT=$(($COUNT+1))
	done < $WORKDIR/songs_in_list

	( flock -e 201
		mv $WORKDIR/tmp_playlist $WORKDIR/playlist
	) 201>$WORKDIR/playlist.lockfile 

	[ "$AUTOPLAY_ADR" ] && $APPDIR/func_player -play -autoplay "$AUTOPLAY_ADR" #play first added track
	[ -f $WORKDIR/gui_is_running ] && echo true > $WORKDIR/UPDATE_GUI
	echo tail > $WORKDIR/ADDMODE  #add next track at the end of playqueue
	echo 100 > $WORKDIR/splash #be sure to close progress dialog
	$APPDIR/func -statusbar_playlist & #update statusbar
	;;
esac