# ---------------------------------------------------------------------------------
#
# What version of dvdwizard are we running?
#
dvdwizard_ver="dvdwizard version 0.5.1"

#
# Set decimal delimiter to '.' instead of ',' - otherwise
# chapters will only be accurate to seconds and not to frames
#
export LC_NUMERIC="C"

#
# Determine version of Image-Magick
#
export IM_VERSION3=$(convert -version | grep ^Version: | cut -d' ' -f 3)
export IM_VERSION2=$(echo $IM_VERSION3 | cut -d. -f1-2)
export IM_VERSION=$(echo $IM_VERSION3 | cut -d. -f1)

#
# The scriptname
#
thisscript=$(basename $0)

# ---------------------------------------------------------------------------------
#
# If something goes wrong....  Default Error-Handling
#
error_out()
{
	cat << EOF

Hey, something went wrong in "$thisscript"! Check for error messages in the log.
The last command returned a Non-Zero Return-Code ($?)
So I guess it's better to stop here and let you analyze the situation
Hope you'll find the error. ;-)
EOF
	if [ -e "$LOGFILE" ]; then
		cat << EOF
Here are the last 10 lines of the log ($LOGFILE):
-------------------------------------------------------
EOF
		tail -n 10 "$LOGFILE"
	fi
	
	exit 1
} >&2

# ---------------------------------------------------------------------------------
#
# Check for needed tools in each script
#
check_tools()
{
#
# We need at least ImageMagick 6.1
#
	if [ "$IM_VERSION2" \< "6.1" ]; then
		echo "dvdwizard needs at least ImageMagick Version 6.1 or higher"
        echo "See $thisscript -h for more infos"
        exit 1
	fi >&2

	commonTools="awk basename cat convert cp cut date dirname dvdauthor grep identify ln mkdir mktemp mplex mv ppmtoy4m rm sed seq tail tee tr wc"
	dvdwizard="chaptercheck dvdcpics dvdtguess ffmpeg mk_vmgm mk_vtsm mk_vtsm_info mk_vtsm_lang mpgprobe nice"
	mk_vmgm="composite ffmpeg montage mpeg2enc spumux"
	mk_vtsm="$mk_vmgm mogrify"
	chaptercheck="bc"
	dvdcpics="display tcprobe transcode"
	dvdtguess=""      
	mpgprobe="tcprobe"
	txt2png="mogrify"
	mk_vtsm_lang="$mk_vtsm"
	mk_vtsm_info="$mk_vtsm txt2png"
	eval tools="\${$thisscript}"
	tools="$commonTools $tools"

	for tool in $tools; do
		type -p "$tool" > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			echo "The program $tool is needed by $thisscript, but could not be located"
	        echo "See $thisscript -h for more infos"
	        exit 1
		fi >&2
	done
	
	return 0
}
# ---------------------------------------------------------------------------------
#
# Set default processing options - either from config-File or from built-in
#
set_defaults()
{
	system_dfltconfFile="/etc/dvdwizard.conf"
	user_dfltconfFile="$HOME/.dvdwizard/dvdwizard.conf"
	confFile=""
	
	#
	# Search CLI-Parms for Config-File Specification
	#
	i=0
	while [  $i -lt $# ]; do
	   	let "i+=1"
	    eval passed_arg=\${$i}
	    if [ "$passed_arg" == "-C" -o "$passed_arg" == "--config-file" ]; then
	    	let "i+=1"
		    eval confFile=\${$i}
	     	if [ -f "$confFile" -a -r "$confFile" ]; then
	      		:
	        else
	        	echo "Specified Config-File $confFile not found or no read permission. Aborting" >&2
	         	exit 1
	        fi
			break 2
	  	fi
	done
	
	#
	# Check, if config file parm is given
	# If not, try, if default config-file exists
	# If it doesn't exist, use built-in defaults
	# User-Config takes precedence over system-wide config
	#
	if [ -z "$confFile" ]; then
	 	[ -f "$system_dfltconfFile" -a -r "$system_dfltconfFile" ] && confFile="$system_dfltconfFile"
	 	[ -f "$user_dfltconfFile" -a -r "$user_dfltconfFile" ] && confFile="$user_dfltconfFile"
	fi
	
	#
	# Ok, set process options
	#
	if [ -z "$confFile" ]; then
		echo "ERROR: No config file for dvdwizard found!"
		echo "dvdwizard needs a config file to run. Use one of the following options:"
		echo "- Create a system-wide config named /etc/dvdwizard.conf"
		echo "- Create a user config named $HOME/.dvdwizard/dvdwizard.conf"
		echo "- Supply a valid config file with the -C option on the command line"
		echo "Look at /usr/local/share/dvdwizard.conf.sample for more informations"
		echo "or consult the manpage dvdwizard.conf(5)"
		exit 1
	fi >&2
		
	#
	# Check, if config file is valid (at least some lines with assignments to
	# Uppercase-Variables
	#
	if [ $(grep -cE "^\ *[[:upper:]]+=" "$confFile") -eq 0 ]; then
		echo "Config file $confFile is not valid. It does not contain any assignment to uppercase variable names."
		exit 1
	fi >&2

	#
	# Ok, set process options
	#
	. "$confFile"	
	
	#
	# if config is incomplete, set defaults for mandatory variables
	#
	[ -z "$BASEDIR" ] && BASEDIR="$(pwd)"
	[ -z "$TVNORM" ] && TVNORM="PAL"
	[ -z "$TVSIZE" ] && TVSIZE=635x535
	[ -z "$MENU_CANVAS" ] && MENU_CANVAS="gradient:white-black"
	[ -z "$DUMMY_CANVAS" ] && DUMMY_CANVAS="xc:none"
	[ -z "$MENU" ] && MENU="EN"
	[ -z "$TMPDIR" ] && export TMPDIR="/tmp" || export TMPDIR="$TMPDIR"
	[ -z "$NICE" ] && NICE="+0"
	[ -z "$VTSTITLE" ] && VTSTITLE="auto"
	[ -z "$THUMBBORDER" ] && THUMBBORDER=3
	[ -z "$THUMBSPACE" ] && THUMBSPACE=5
	[ -z "$CHAPTERSPERROW" ] && CHAPTERSPERROW=3
	[ -z "$PAUSE" ] && PAUSE=2
	[ -z "$LOOP" ] && LOOP=0
	
	#
	# Init and Check Colors
	#
	colorlist="$(convert -list color | sed 1,/^-/d | cut -d' ' -f1)"
	transparent="transparent"		#'rgba(128,192,255,255)'
	shadow="black"
	[ -z "$TRANSLUCENT" ] && TRANSLUCENT='#FFFFFF80'
	[ -z "$TITLECOLOR" ] && TITLECOLOR="white"
	[ -z "$HEADCOLOR" ] && HEADCOLOR="white"
	[ -z "$TEXTCOLOR" ] && TEXTCOLOR="white"
	[ -z "$NORMCOLOR" ] && NORMCOLOR="white"
	[ -z "$HICOLOR" ] && HICOLOR="orange"
	[ -z "$SELCOLOR" ] && SELCOLOR="green"
	[ -z "$ACTCOLOR" ] && ACTCOLOR="green1"
	for c in $TRANSLUCENT $TITLECOLOR $HEADCOLOR $TEXTCOLOR $NORMCOLOR $HICOLOR $SELCOLOR $ACTCOLOR; do
		if [ "${c:0:1}" == "#" -o "${c:0:3}" == "rgb" ]; then
			:
		else
			echo "$colorlist" | grep ^"${c}"$ >/dev/null
			if [ $? -ne 0 ]; then
				echo "Invalid color $c specified. Please check config file."
				exit 1
			fi
		fi 
	done >&2
	hiColor=( "$NORMCOLOR" "$HICOLOR" "$SELCOLOR" )

	#
	# Init and Check Fonts
	#
	fontlist="$(convert -list type | cut -d' ' -f1 | sed 1,/^-/d | sed -e /^$/,/^-/d | sort)"
	maxfl=0
	for t in $(echo $fontlist); do
		[ ${#t} -gt $maxfl ] && maxfl=${#t}
	done
	[ -z "$TFONTSIZE" ] && TFONTSIZE=48
	[ -z "$HFONTSIZE" ] && HFONTSIZE=24
	[ -z "$MFONTSIZE" ] && MFONTSIZE=20
	[ -z "$OFONTSIZE1" ] && OFONTSIZE1=18
	[ -z "$OFONTSIZE2" ] && OFONTSIZE2=48
	for fontvar in TFONTTYPE HFONTTYPE MFONTTYPE OFONTTYPE1 OFONTTYPE2; do
		eval t=\$$fontvar
		fontparm=$(echo $fontvar | sed -e s/TYPE//g)
		if [ -z "$t" ]; then
			eval $fontparm=\"\"
		else
			[ ${#t} -gt $maxfl ] && t=${t:0:$maxfl}
			echo "$fontlist" | grep ^"${t}"$ >/dev/null
			if [ $? -ne 0 ]; then
				echo "Invalid font type $t specified. Please check config file."
				exit 1
			fi
			eval $fontparm=\"-font $t\"
		fi 
	done >&2

	#
	# Create temporary directory for storing all non-permanent work files
	#
	if [ -z "$DVDWIZARD_TMPDIR" ]; then
		# Remove previously created temporary directories where we are owner
		for d in "$TMPDIR/$thisscript"_*; do
			[ -O "$d" ] && rm -R "$d"
		done
		export DVDWIZARD_TMPDIR=$(mktemp -dt "$thisscript"_XXXXXX) || {
			echo "Could not create temporary directory. Aborting"
			echo "Please check your TMPDIR-Settings and permissions on your"
			echo "temporary directory" 
		error_out
		} >&2
		#
		# Create subdirectory for common objects (get reused in various scripts)
		#
		mkdir "$DVDWIZARD_TMPDIR"/common_objects
	fi
	export TMPDIR="$DVDWIZARD_TMPDIR"
	
	return 0
}

# ---------------------------------------------------------------------------------
#
# Check and create Directory if not already present and called with the "New"-Parm
#
mk_check_dir()
{
	chkdir="$1"
	chkmode=$2
	chkdescr="$3"
	
	if [ -z "$chkdir" ]; then
		echo "Directory not specified ($chkdescr, $chkmode). Aborting"
		echo "See $thisscript -h for more infos"
		exit 1
	fi >&2
	
	if [ -e "$chkdir" ]; then
		if [ ! -d "$chkdir" ]; then
	    	echo "Specified directory \"$chkdir\" ($chkdescr) isn't a directory. Aborting"
	        echo "See $thisscript -h for more infos"
	        exit 1
		fi >&2
	    if [ -r "$chkdir" -a -x "$chkdir" ]; then
	    	:
	    else
	    	echo "Insufficient access rights on directory \"$chkdir\" ($chkdescr), must have at least rx. Aborting"
	        echo "See $thisscript -h for more infos"
	        exit 1
		fi >&2
		if [ "$chkmode" == "NEW" ]; then
			dCount=$(ls -1 "$chkdir"/* 2>/dev/null | wc -l)
			# Ask for permission to recreate an existing, non-empty directory
			# if user has not specified -y|--yes on the command line
			if [ $dCount -ne 0 -a "$permission" != "Yes" ]; then
				echo "Directory \"$chkdir\" ($chkdescr) exists and is not empty"
				echo "All files in this directory will be deleted. Okay? [yN]"
				permit=""
				until [ ! -z "$permit" ]; do
					read ANSWER
					case "$ANSWER" in
						""|n|N )
							permit="N"
						;;
						y|Y )
							permit="Y"
						;;
						* )
							echo "Wrong reply. Please answer with a single 'y' or 'n'"
							echo "All files in $chkdir will be deleted. Okay? [yN]"
						;;
					esac
				done
				if [ "$permit" == "N" ]; then
					echo "Sorry, can't work with a non-empty destination directory. Aborting"
					echo "Please clean up $chkdir manually or specify another directory ($chkdescr)"
					exit 1
				fi >&2
			fi
			if rm -R "$chkdir"; then
				if mkdir -p "$chkdir"; then
	    			:
	 			else
					echo "Could not re-create directory \"$chkdir\" ($chkdescr). Aborting"
			        echo "See $thisscript -h for more infos"
	    		    exit 1
				fi
			else
				echo "Could not clean up destination directory \"$chkdir\" ($chkdescr). Check your permissions"
		        echo "See $thisscript -h for more infos"
	    		    exit 1
			fi >&2
		fi
	else
		if [ "$chkmode" == "NEW" ]; then
			if mkdir -p "$chkdir"; then
	    		:
	 		else
				echo "Could not create directory \"$chkdir\" ($chkdescr). Aborting"
		        echo "See $thisscript -h for more infos"
    		    exit 1
			fi
	  	else
	    	echo "Specified input directory \"$chkdir\" ($chkdescr) not found. Aborting"
	        echo "See $thisscript -h for more infos"
   		    exit 1
		fi >&2
	fi
	
	if [ "$chkmode" == "NEW" -a ! -w "$chkdir" ]; then
		echo "No write permission in directory \"$chkdir\" ($chkdescr). Aborting"
        echo "See $thisscript -h for more infos"
        exit 1
	fi >&2
	
	return 0
}

# ---------------------------------------------------------------------------------
#
# Check and create file if not already present and called with "New"
#
mk_check_file()
{
	chkfile="$1"
	chkmode=$2
	chkdescr="$3"
	
	if [ -z "$chkfile" ]; then
		echo "Filename not specified ($chkdescr, $chkmode). Aborting"
		echo "See $thisscript -h for more infos"
		exit 1
	fi >&2
	
	if [ -e "$chkfile" ]; then
		if [ -d "$chkfile" ]; then
	    	echo "Specified file \"$chkfile\" ($chkdescr) is a directory. Aborting"
	        echo "See $thisscript -h for more infos"
	        exit 1
	 	fi
	    if [ -r "$chkfile" ]; then
	    	:
	    else
	    	echo "Insufficient access rights on file \"$chkfile\" ($chkdescr), must have at least read permission. Aborting"
	        echo "See $thisscript -h for more infos"
	        exit 1
	    fi
	    if [ -w "$chkfile" -o "$chkmode" != "NEW" ]; then
	    	:
	    else
	    	echo "Insufficient access rights on file \"$chkfile\" ($chkdescr), must have write permission. Aborting"
	        echo "See $thisscript -h for more infos"
	        exit 1
	    fi
	else
		if [ "$chkmode" == "NEW" ]; then
			if touch "$chkfile"; then
	    		:
	 		else
				echo "Could not create file \"$chkfile\" ($chkdescr). Aborting"
		        echo "See $thisscript -h for more infos"
		        exit 1
			fi
	  	else
	    	echo "Specified input file \"$chkfile\" ($chkdescr) not found. Aborting"
	        echo "See $thisscript -h for more infos"
	        exit 1
	    fi
	fi >&2
	
	if [ "$chkmode" == "NEW" -a ! -w "$chkfile" ]; then
		echo "No write permission on file \"$chkfile\" ($chkdescr). Aborting"
        echo "See $thisscript -h for more infos"
        exit 1
	fi >&2
	
	
	return 0
}
# ---------------------------------------------------------------------------------
#
# PAL and NTSC differ in audiosamples per videoframe and frame rates. Set the appropriate values
# Value $samples is set for 10 video frames.
#
set_format()
{
	if [ "$TVNORM" == "NTSC" ]; then
		encFrameRate="30000:1001"
		encNorm="n"
		samples=16016 
		normX=720
	    normY=480
	    densityX=81
	    densityY=72
	else
		samples=19200  
		encFrameRate="25:1"
		encNorm="p"
		normX=720
	    normY=576
	    densityX=75
	    densityY=80
	fi
	normSize="$normX"x"$normY"
	normDensity="$densityX"x"$densityY"
	TVWidth=$(echo "$TVSIZE" | cut -d'x' -f 1)
	TVHeight=$(echo "$TVSIZE" | cut -d'x' -f 2)
	let offsetTVX="($normX-$TVWidth)/2"
	let offsetTVY="($normY-$TVHeight)/2"
	let maxpH="$TVHeight-20"
	let maxpW="$TVWidth-20"
	
	
	return 0
}

# ---------------------------------------------------------------------------------
#
#  Create common objects needed in various scripts and locations
#
create_common_objects()
{

	#
	# Create empty audio track if not already existing
	#
	silence="$TMPDIR/common_objects/silence.ac3"
	if [ ! -e "$silence" ]; then
		#
		# Create audio track
		#
		echo "Creating empty AC3 Audio-Track..."
		ffmpeg -f s16le -i /dev/zero -ab 224kb -ar 48000 -ac 2 -t 1 "$silence" 1>/dev/null 2>&1 || error_out
		echo "done"
	fi
	
	#
	# Create dummy mpeg stream for menus
	#
	emptympg="$TMPDIR/common_objects/empty.mpg"
	if [ ! -e "$emptympg" ]; then
		echo "Creating dummy MPEG-Stream..."
		#
		# Create dummy mpeg Stream for first dummy menu in vmgm/vtsm
		#
		convert -size "$normSize" xc:transparent -depth 8 ppm:- |\
			ppmtoy4m -S 420mpeg2 -n 1 -F "$encFrameRate" -r /dev/stdin | \
			mpeg2enc -a 2 -n "$encNorm" -f 8 -o /dev/stdout | \
			mplex -f 8 -o /dev/stdout /dev/stdin "$silence" > "$emptympg" || error_out
		echo "done"
	fi
	
	return 0
}

# ---------------------------------------------------------------------------------
#
# Prepare the background picture for the menus
#
prepare_bg()
{
	actvts=$1
	bgPic="$2"
	workbg="$TMPDIR/common_objects/menubg_$actvts".png
	#
	# If picture already exists, no op
	#
	[ -e "$workbg" ] && return 0 
	echo -n "Preparing Background-Picture for titleset $actvts..."

	#
	# If no background picture specified, create one
	#
	if [ -z "$bgPic" ]; then
		bgPic="$DUMMY_CANVAS"
	fi	
	#
	# Ok, create Background picture
	#
	[ "$IM_VERSION2" == "6.1" ] && faktor="180" || faktor="pi"
	convert \
		-size $normSize $MENU_CANVAS -scale $normX'!'x$normY'!' \
		\( "$bgPic" -scale "$maxpW"x"$maxpH" \
			\( +clone -fx 'cos('$faktor'*(i/w-.5))*cos('$faktor'*(j/h-.5))' \
				-bordercolor black -border 10 +matte \
			\) \
				-compose CopyOpacity -composite \
		\) \
		-gravity NorthEast -geometry +"$(( $offsetTVX+50 ))"+"$(( $offsetTVY+10 ))" \
		-composite -depth 8 -density $normDensity -units PixelsPerInch \
		png:"$workbg" || error_out

echo "done"

return 0
}

# ---------------------------------------------------------------------------------
#
# Create overlay container with logo or descriptive text
#	$1 - Identifying part of the name of the text elements from config file
#	     Elements: TXT_OVERLAY_$1_1_$lang - small, opaque text
#	     Elements: TXT_OVERLAY_$1_2_$lang - big, bevelled, translucent text
#	Name and path of resulting image is stored in variable $logoPic
#
create_overlay()
{
	eval text1=\"\$TXT_OVERLAY_$1_1_$MENU\"
	eval text2=\"\$TXT_OVERLAY_$1_2_$MENU\"
	logoPic="$(mktemp -t png.XXXXXXXXXX)"
	fontsize1=45
	fontsize2=18

	#
	# Ok, create overlay picture
	#
	echo -n "Creating Overlay-Picture..."
	convert \
		-size $normSize xc:none \
		\( -size $TVSIZE xc:none \
			$OFONT2 -pointsize $OFONTSIZE2 -gravity center \
			-fill '#00000080' -annotate -2-2 "$text2" \
			-fill '#FFFFFF80' -annotate +2+2 "$text2" \
			-fill gray -annotate +0+0 "$text2" \
			-transparent gray -trim +repage -bordercolor transparent -border 10 \
			$OFONT1 -pointsize $OFONTSIZE1 -gravity northwest \
			-fill black -annotate +0+0 "$text1" \
			-fill white -annotate +2+2 "$text1" \
			-rotate 270 -border 10 \
		\) \
		-gravity SouthEast -geometry +"$(( $offsetTVX+5 ))"+"$(( $offsetTVY+5 ))" \
		-composite -depth 8 -density $normDensity -units PixelsPerInch \
		png:"$logoPic" || error_out

	echo "done"

return 0
}

# ------------------------------------------
# Create Button Pictograms for Menus
#	Buttons are: Play, Chapter, Audio, Subtitle, Info, Previous and Next
#   Each button exists for all three states: normal, hilight, selected
#
mk_picts()
{
	#
	# Init phrases according to language setting 
	# determine longest string and corresponding button width
	#
	echo -n "Creating button pictograms..."
	maxLen=0
	for i in PLAY CHAPTER AUDIO SUBS INFO; do
		eval txt_$i=\"\$TXT_VMGM_${i}_$MENU\"
		eval txtLen=\${#txt_$i}
		if [ $txtLen -gt $maxLen ]; then
			maxLen=$txtLen
			eval maxtxt=\"\$txt_$i\"
		fi
	done

	# Size of button including descriptive text
	tWidth=$(convert -size $TVSIZE xc:black -fill red \
					$MFONT -pointsize $MFONTSIZE \
					-draw 'gravity center text 0,0 "--'"$maxtxt"'--"' -trim png:- | \
					identify -format %w -)

	# Sizes for button pictograms
	pictSize=45x45	
	pictFontsize=34
	circleDef="22,22 22,4"
	polygonDef="14,11 36,22 14,33"
	pictWidth=$(echo $pictSize | cut -d'x' -f1)
	pictHeight=$(echo $pictSize | cut -d'x' -f2)
	let bWidth="$tWidth+$pictWidth+10"
	pictBase="$(mktemp -t png.XXXXXXXXXX)"

	#
	# For every button state, we need one pictogram for each button
	#
	for s in 0 1; do
		pictPlay[s]="$TMPDIR/common_objects/pictPlay_$s.png"
		pictInfo[s]="$TMPDIR/common_objects/pictInfo_$s.png"
		pictAudio[s]="$TMPDIR/common_objects/pictAudio_$s.png"
		pictMenu[s]="$TMPDIR/common_objects/pictMenu_$s.png"
		pictSubs[s]="$TMPDIR/common_objects/pictSubs_$s.png"
		pictPrev[s]="$TMPDIR/common_objects/pictPrev_$s.png"
		pictNext[s]="$TMPDIR/common_objects/pictNext_$s.png"
		pictArrow[s]="$(mktemp -t png.XXXXXXXXXX)"
		fillcolor="${hiColor[s]}"
	
		# Prevent Antialiasing for Highlight and Selected modes
		if [ $s -eq 0 ]; then
			antialias=""
		else
			antialias="+antialias"
		fi
	
		# Create Pictogram-Background (a circle!) and an arrow pictogram
		convert $antialias -size $pictSize xc:"$transparent" -fill "$transparent" \
				-strokewidth 2 -stroke "$fillcolor" -draw 'circle '"$circleDef"'' \
				png:"$pictBase" || error_out
		convert $antialias -fill "$fillcolor" \
				-draw 'polygon '"$polygonDef"'' \
		        "$pictBase" png:"${pictArrow[s]}" || error_out
	
		# Draw Play-Button 
		if [ ! -e "${pictPlay[s]}" ]; then
		    if [ $s -eq 0 ]; then
				cp "${pictArrow[s]}" "${pictPlay[s]}" 
		    else
			    # Add text to highlight and selected buttons
		    	convert $antialias \
		    		\(	-size ${bWidth}x${pictHeight} xc:"$TRANSLUCENT" \
		    			$MFONT -pointsize $MFONTSIZE \
		        		-fill "$fillcolor" -gravity west \
		        		-annotate +$(( $pictWidth+5 ))+0 "$txt_PLAY" \
		        	\) \
					"${pictArrow[s]}" \
		        	-compose over -gravity west -composite \
		        	png:"${pictPlay[s]}" || error_out
			fi
		fi
	
		# Draw Next-Button 
		if [ ! -e "${pictNext[s]}" ]; then
			cp "${pictArrow[s]}" "${pictNext[s]}" 
		fi
	
		# Draw Previous-Button 
		if [ ! -e "${pictPrev[s]}" ]; then
	    	convert "${pictArrow[s]}" -flop "${pictPrev[s]}" 
		fi
	
		# Draw the rest of the buttons
		for btnState in 	"${pictAudio[s]}@a@AUDIO" \
							"${pictMenu[s]}@x@CHAPTER" \
							"${pictSubs[s]}@s@SUBS" \
							"${pictInfo[s]}@i@INFO"; do
			thisPic="$(echo "$btnState" | cut -d'@' -f1)"
			thisChar="$(echo "$btnState" | cut -d'@' -f2)"
			thisText="$(echo "$btnState" | cut -d'@' -f3)"
			[ "$thisChar" == "x" ] && thisChar="?"
			eval thisTxt=\"\$txt_$thisText\"
			if [ ! -e "$thisPic" ]; then
			    convert $antialias -pointsize "$pictFontsize" \
						-fill "$fillcolor" -gravity center \
						-annotate +0+0 "$thisChar" \
		    	    	"$pictBase" png:"$thisPic" || error_out
			    if [ $s -ne 0 ]; then
			    	convert $antialias \
			    		\(	-size ${bWidth}x${pictHeight} xc:"$TRANSLUCENT" \
							$MFONT -pointsize $MFONTSIZE \
			        		-fill "$fillcolor" -gravity west \
			        		-annotate +$(( $pictWidth+5 ))+0 "$thisTxt" \
			        	\) \
						"$thisPic" \
			        	-compose over -gravity west -composite \
			        	png:"$thisPic" || error_out
				fi
			fi
		done
	done
	
	echo "done"
	return 0
}

# ---------------------------------------------------------------------------------
#
# mk_nav_buttons - Create Buttons for Intra-Menu-Navigation
#
mk_nav_buttons()
{
	targets="$*"
	for tgt in $targets $txt_RETURN; do
		if [ ! -e "$TMPDIR/common_objects/navbtn_${tgt}_0.png" ]; then
			btnDim=$(convert \
						-size $TVSIZE xc:transparent \
						$MFONT -pointsize $MFONTSIZE -gravity center \
						-fill black -undercolor black -annotate +0+0 " $tgt " \
						-trim +repage png:- | \
					identify -format %wx%h -)
			fpat="$TMPDIR/common_objects/navbtn_${tgt}_@.png"
			blankpng="$(echo "$fpat" | tr '@' 3)"
			convert \
				-size $btnDim xc:transparent -bordercolor transparent -border 5 \
				png:"$blankpng" || error_out
			fg=( ${hiColor[0]} ${hiColor[1]} $ACTCOLOR )
			bg=( none $TRANSLUCENT none )
			aa=( -antialias +antialias -antialias )
			for i in 0 1 2; do
				tgtpng="$(echo "$fpat" | tr '@' $i)"
				convert -size $btnDim xc:${bg[i]} ${aa[i]} \
					$MFONT -pointsize $MFONTSIZE -gravity center \
					-fill ${fg[i]} -annotate +0+0 " $tgt " \
					-bordercolor transparent -border 5 \
					png:"$tgtpng" || error_out
			done
		fi
	done

	return 0			
}

# ---------------------------------------------------------------------------------
#
# mk_tmpdvd - Create a temporary DVD-structure without menus but with chapters
#
mk_tmpdvd()
{
	#
	# Do some file and directory preparation
	#
	[ -e "$DESTDIR" ] && rm -R "$DESTDIR"
	mkdir -p "$DESTDIR"
	tmpxml="$(mktemp -t xml.XXXXXXXXXX)"
	cat "$XMLFILE" > "$tmpxml"
	echo -e "\t<vmgm>\n\t</vmgm>" >> "$tmpxml"

	#
	# Create a Titleset for each defined title
	#
	for i in $(seq 1 $vts); do
		{
			echo -e "\t<titleset>"
	    	echo -e "\t\t<titles>"
		    echo -e "\t\t\t<pgc pause=\"0\">" 
		} >> "$tmpxml"
	    eval files=\"\$VTSM_"$i"_FILES\"
	    eval cspec=\"\$CHAPTERSPEC_$i\"
	    for j in $(seq 1 $files); do
			eval vtstitle=\"\$VTSM_"$i"_FILE_$j\"
			duration=$(ffmpeg -i $vtstitle 2>&1 | grep Duration | cut -d' ' -f4 | cut -d'.' -f1)
			durHH=$(echo $duration | cut -d':' -f1)
			durMM=$(echo $duration | cut -d':' -f2)
			durSS=$(echo $duration | cut -d':' -f3)
			mpglen=$(echo "$durHH*3600+$durMM*60+$durSS+1" | bc)
		    chapters=$(nice -n $NICE chaptercheck -N $TVNORM -L $mpglen $cspec) || error_out
			eval VTSM_"$i"_CHAPTERS_$j=\"\$chapters\"
	        echo -e "\t\t\t\t<vob file=\"$vtstitle\""
	        echo -e "\t\t\t\t chapters=\"$chapters\""
	        echo -e "\t\t\t\t pause=\"0\" />"
	  	done >> "$tmpxml"
	    {
			echo -e "\t\t\t</pgc>"
	    	echo -e "\t\t</titles>"
			echo -e "\t</titleset>"
		} >> "$tmpxml"
	done

	echo "</dvdauthor>" >> "$tmpxml"
	
	#
	# Now author the temporary DVD
	#
	nice -n $NICE dvdauthor -x "$tmpxml" || error_out
	
	rm "$tmpxml"

	return 0
}

# ---------------------------------------------------------------------------------
#
# trim_title - Cut long title strings down to fit into the title container
#
trim_title()
{
	maxlen=$1
	ft=$2
	fs=$3
	trimText=$4
	[ ! -z "$ft" ] && ft="-font $ft"
	thislen=$(convert -size $normSize xc:black -fill white \
				$ft -pointsize $fs -gravity west \
				-annotate +0+0 "$trimText" -trim +repage miff:- | identify -format %w -)
	while [ $thislen -gt $maxlen ]; do
		twords=$(echo $trimText | wc -w)
		if [ $twords -gt 1 ]; then
			trimText="$(echo $trimText | cut -d' ' -f1-$(( $twords-1 )))..."
		else
			trimText=${trimText%%'...'}
			trimText="${trimText:0:$(( ${#trimText}-1 ))}..."
		fi
		thislen=$(convert -size $normSize xc:black -fill white \
				$ft -pointsize $fs -gravity west \
				-annotate +0+0 "$trimText" -trim +repage miff:- | identify -format %w -)
	done
	
	return 0
}

# ---------------------------------------------------------------------------------
#
# cleanup_tmpdir - Remove scripts temporary directory
#
cleanup_tmpdir()
{
	# Get the basename of the temporary directory and the length of the scriptname
	#
	dirbasename="$(basename "$DVDWIZARD_TMPDIR")"
	scriptnamelen=${#thisscript}
	
	# Extract scriptname from temporare directory
	#
	scriptname="${dirbasename:0:$scriptnamelen}"
	
	# Remove directory if it was created within this script
	#
	[ "$scriptname" == "$thisscript" ] && rm -R "$DVDWIZARD_TMPDIR"
	
	return 0
}

#
#  End of dvdwizard script functions
#
