#!/bin/bash
#
# mk_vmgm - Create Main menu of the DVD (VMGM)
#           for authoring a DVD with dvdauthor >= 0.6
#
# Version   0.4 written by Wolfgang Wershofen (mailto: itconsult at wershofen.de)
#			0.5 - changed whole layout of menu
#				- support for multiple languages (-M)
#				- added subtitle button
#				- code cleanup
#
# See TOOLS in the dvdwizard tarball for info about needed tools and programs
#
usage()
{
 cat <<EOF
Usage:	`basename $0` [options]
	`basename $0` -h|--help

miscellaneous options:
----------------------
-h  | --help		print this lot out

general processing:
-------------------
-C  | --config-file	filename of dvdwizard-configuration file
			[~/.dvdwizard/dvdwizard.conf]
-o  | --output		Path where the created menu mpegs will be stored 
			[\$BASEDIR/vmgm]
-x  | --xml		Print dvdauthor XML-specs into this file
			[$BASEDIR/dvdwizard.xml]

Note: \$BASEDIR defaults to the current directory if not stated otherwise in the config file (either default ~/.dvdwizard/dvdwizard.conf or specified with the -C option)

DVD-specific options:
---------------------
-T  | --vmgm		Title of the DVD to display on menu
			If not specified, no title will be printed on VMGM 
			menu. 
-N  | --tvnorm		Choose from PAL (25fps, 720x576) or NTSC (29.97 fps,
			720x480) [PAL]
-V  | --tvsize		Visible area of frame on TV set. [635x535]
-M  | --menu		Language to use in menu items [en]
			Textelements are defined in config file
-I  | --intro		MPEG-File to be played when inserting the DVD in the
			player
-L  | --loop		Playback mode of the DVD. Possible values:
			 0 - return to vmgm menu after each title
			-1 - display vmgm menu before the first and after 
			     the last title
			-2 - display vmgm menu only before first title and 
			     loop through all titles afterwards
			>0 - suppress vmgm menu and loop all titles 
			     endlessly, starting from specified title
-MS | --vmgmsound	Soundfile to be used as background sound for all 
			menus (may be overwritten for specific titlesets
			with -ms|--vtsmsound). If empty, a silent audio
			track will be produced.
			Can be any format, ffmpeg recognizes and will be
			converted to ac3, if neccessary.

Title-specific options:
-----------------------
-t  | --vts		Titlestring for titleset. repeat for each titleset
			Will be ignored for single-titleset DVDs, if -T is 
			given
-b  | --vtsmbg		Image to use as thumbnail for the vtsm in a 
			Multi-Titleset-DVD
-ms | --vtsmsound	see -MS, but only applies to this title
--hasaudio		Title has multiple audio tracks. A button to jump to
			the audio selection menu will be created
--hassubtitle		Title has at least one Subtitle-Stream which may be
			activated in a subsequent subtitle-menu
--hasinfo		Title has EPG-Informations available. A button to 
			jump to the info panel will be created

Note: Every new "-t" marks a new titleset on the DVD. Subsequent options -b, -ms, --hasaudio, --hassubtitle and --hasinfo apply only to that titleset.

EOF
exit 1
}

# ------------------------------------------
# Initialize constants troughout the whole script
#
init_proc()
{
	for i in HEADER DUMMY ABOUT ABOUT1 ABOUT2; do
		eval txt_$i=\"\$TXT_VMGM_${i}_$MENU\"
	done
	
	#
	# Init sizes
	#
	# offsets of title strings
	offsetX1=20
	offsetX2=40
	
	return 0
}

# -------------------------------------------------------------
# Create the button bar background
#
mk_button_bar()
{
	let maxButtons="$maxAddButtons+2"
	btnbarbg="$(mktemp -t png.XXXXXXXXXX)"
	let pW="pictWidth+10"
	let pH="(($pictHeight+6)*$maxButtons)+6"
	round=20
	convert -size "$(( $pW+$round ))"x"$(( $pH+$round ))" xc:"$transparent" \
			-fill "$TRANSLUCENT" \
			-draw 'gravity NorthWest roundrectangle 0,0,'$(( $pW+$round-1 ))','$(( $pH-1 ))' '$round','$round'' \
			-crop "$pW"x"$(( $pH+$round ))"+"$round" \
		\( -size "$round"x"$round" xc:"$TRANSLUCENT" -fill gray \
			-draw 'gravity NorthWest roundrectangle 0,0,'$(( $round*2 ))','$(( $round*2 ))' '$round','$round'' \
			-transparent gray \
		\) \
		-gravity SouthWest -composite \
		png:"$btnbarbg" || error_out
	barHeight=$(identify -format %h "$btnbarbg")
	
	return 0
}

# -------------------------------------------------------------
# Create Title container
#
mk_title_container()
{
	titleBG="$(mktemp -t png.XXXXXXXXXX)"
	let stepY="$MFONTSIZE+($MFONTSIZE/4)"
	let tbgW="$TVWidth/2"
	let tbgH="($vts+2)*$stepY+$HFONTSIZE*2+$stepY/2"
	[ $tbgH -lt $barHeight ] && tbgH=$barHeight
	convert -size $(( $tbgW+$pW ))x$tbgH xc:"$transparent" \
		\( -size "$tbgW"x"$tbgH" xc:"$TRANSLUCENT" \
			$HFONT -pointsize $HFONTSIZE -gravity NorthWest \
			-fill "$shadow" -annotate +12+12 "$txt_HEADER:" \
			-draw 'line 12,'$(( $HFONTSIZE+17 ))','$(( $tbgW-8 ))','$(( $HFONTSIZE+17 ))'' \
			-draw 'line 12,'$(( $HFONTSIZE+18 ))','$(( $tbgW-8 ))','$(( $HFONTSIZE+18 ))'' \
			-fill "$HEADCOLOR" -annotate +10+10 "$txt_HEADER:" \
			-draw 'line 10,'$(( $HFONTSIZE+15 ))','$(( $tbgW-10 ))','$(( $HFONTSIZE+15 ))'' \
			-draw 'line 10,'$(( $HFONTSIZE+16 ))','$(( $tbgW-10 ))','$(( $HFONTSIZE+16 ))'' \
		\) \
		-gravity northwest -composite \
		"$btnbarbg" \
		-gravity northeast -composite \
		\( +clone -bordercolor transparent -border 10 \
			-negate -blur 0x8 \) \
		+swap -gravity center -compose src-atop -composite \
		png:"$titleBG" || error_out
	let offsettbgY="($TVHeight-$tbgH)+$offsetTVY"
#				-stroke "$shadow" -strokewidth 2 \
#			-stroke "$HEADCOLOR" -strokewidth 2 \
	
	#
	# Container for button masks
	#
	btnMasktrans="$(mktemp -t png.XXXXXXXXXX)"
	let bmH="tbgH+10"
	let bmW="tbgW+pW+tWidth+15"
	convert -size "$bmW"x"$bmH" xc:"$transparent" png:"$btnMasktrans" || error_out
	
	return 0
}

# -------------------------------------------------------------
# Create the VTS-Tile with thumbnail, buttons and titlestring
#
place_buttons()
{
	indx=$1
	#
	# Create Button-Bar, Highlighted and Selected Masks
	#
	defList=( "1" "1" )
	eval defList[2]=\$VTSAUDIO_$indx
	eval defList[3]=\$VTSSUB_$indx
	eval defList[4]=\$VTSINFO_$indx
	btnDef=( "Play" "Chapter root" "Audio audio" "Subs subtitle" "Info ptt" )
	
	for s in 0 1; do
		pictDef=( "${pictPlay[s]}" "${pictMenu[s]}" "${pictAudio[s]}" "${pictSubs[s]}" "${pictInfo[s]}" )
		pictList=( "${pictDef[0]}" "${pictDef[1]}" )
		btnList=( "${btnDef[0]}" "${btnDef[1]}" )
		pnum=2
		for n in 2 3 4; do
			if [ "${defList[n]}" == "1" ]; then
				pictList[$pnum]="${pictDef[n]}"
				btnList[$pnum]="${btnDef[n]}"
				let "pnum+=1"
			fi
		done
		bbar[s]="$(mktemp -t png.XXXXXXXXXX)"
		tileSize=$(identify -format %wx%h "${pictPlay[s]}") || error_out
		montage \
			-background none -geometry ${tileSize}+3+3 -tile 1x$pnum \
			"${pictList[@]}" png:"${bbar[s]}"
		if [ $s -eq 0 ]; then
			convert "$thistbg" \
				-gravity northeast -draw 'image over 13,13 0,0 "'"${bbar[s]}"'"' \
				png:"$thistbg" || error_out
		else
			convert "${thisbmt[s]}" \
				-gravity northeast -draw 'image copy 10,13 0,0 "'"${bbar[s]}"'"' \
				png:"${thisbmt[s]}" || error_out
		fi
	done
	
	#
	# Write xml-Definition of used buttons
	#
	let "pnum-=1"
	for b in $(seq 0 $pnum); do
		set -- ${btnList[b]}
		bname=$1
		if [ -z "$2" ]; then
			target="title $indx"
		else
			target="titleset $indx menu entry $2"
		fi
		echo -e "\t\t\t\t<button name=\"$bname\"> { g0=button; jump "$target"; } </button>" >> "$XMLFILE"
		[ $b -eq 0 ] && p=$b || let "p=$b-1"
		[ $b -eq $pnum ] && n=$b || let "n=$b+1"
		pname=$(echo "${btnList[p]}" | cut -d' ' -f1)
		nname=$(echo "${btnList[n]}" | cut -d' ' -f1)
		echo -e "\t\t\t<button name=\"$bname\" up=\"$pname\" down=\"$nname\" left=\"Title_$indx\" right=\"$bname\" />" >> "$thisspuxml"
	done
	
	return 0
}

# -------------------------------------------------------------
# Place VTS-Pic and title container onto background image
#
place_vtspic()
{
	let otvx="offsetTVX-10"
	let otvy="offsetTVY-10"
	[ $otvx -ge 0 ] && geoX="+$otvx" || geoX=$otvx
	[ $otvy -ge 0 ] && geoY="+$otvy" || geoY=$otvy
	geoparm=${geoX}${geoY}
	bgpic="$TMPDIR/common_objects/menubg_$i".png
	convert \
		"$bgpic" \
		"$logoPic" \
		-gravity Center -composite \
		"$thistbg" \
		-gravity Southwest -geometry $geoparm -composite \
		-depth 8 -density $normDensity -units PixelsPerInch \
		ppm:"$thisppm" || error_out

	convert \
		-size "$normSize"! xc:transparent \
		"${thisbmt[s]}" \
		-gravity Southwest -geometry +$(( $offsetTVX+2 ))+$(( $offsetTVY )) -composite \
		-depth 8 -density $normDensity -units PixelsPerInch \
		png:"$maskPic" || error_out
	ccount=$(identify -format %k "$maskPic")
	if [ $ccount -ge 2 ]; then
		replColorLine=$(identify -verbose "$maskPic" | sed -e 1,/Histogram/d | head -n2 | \
				tail -n1)
		[ "$IM_VERSION3" \< "6.2.3" ] && replColor=$(echo "$replColorLine" | cut -d')' -f2) \
									  || replColor=$(echo "$replColorLine" | cut -d':' -f2 | cut -d' ' -f2)
		for s in 1 2; do
			convert "$maskPic" -fill "${hiColor[s]}" -opaque "$replColor" "${thisMask[s]}" || error_out
		done
	else
		for s in 1 2; do
			cp "$maskPic" "${thisMask[s]}"
		done
	fi
	
	return 0
}

# -------------------------------------------------------------
# Print DVD-Title onto Menu
#
print_title()
{
	titleDim=$(convert -size $TVSIZE xc:"$transparent" \
				-fill black $TFONT -pointsize $TFONTSIZE -gravity center \
				-annotate +0+0 "$VMGMTITLE" -trim -border 20 png:- | \
				identify -format %wx%h -)
	convert "$thisppm" \
		\(	-size $titleDim xc:"$transparent" -fill "$TRANSLUCENT" \
			-draw 'roundrectangle 0,0 '"$(echo $titleDim | tr 'x' ',')"' 20,20' \
			-bordercolor "$transparent" -border 20 \
			\(	+clone -negate -blur 0x8 \) \
			+swap -gravity center -compose src-atop -composite \
			$TFONT -pointsize $TFONTSIZE -gravity center \
			-fill black -annotate +2+2 "$VMGMTITLE" \
			-fill "$TITLECOLOR" -annotate +0+0 "$VMGMTITLE" \
		\) \
		-gravity northwest -geometry +$(( $offsetTVX+10 ))+$(( $offsetTVY+10 )) -composite \
		-depth 8 -density $normDensity -units PixelsPerInch \
		ppm:"$thisppm" || error_out
			
	return 0
}

# -------------------------------------------------------------
# Create the "about" message
#
mk_about()
{
	let about="vts+1"
	aboutTxt="$(mktemp -t txt.XXXXXXXXXX)"
	aboutPic="$TMPDIR/common_objects/menubg_$about".png
	echo -e "$txt_ABOUT1 \n $verStr \n \n http://dvdwizard.sf.net \n \n $txt_ABOUT2." > "$aboutTxt"
	aboutDim=$(convert -size "$maxpW"x"$maxpH" xc:"$transparent" \
				-fill black $MFONT -pointsize $MFONTSIZE -gravity center \
				-annotate 0,0  "@$aboutTxt"\
				-trim -bordercolor "$transparent" -border 20 \
				png:- | identify -format %wx%h -)
	convert -size $normSize $MENU_CANVAS -scale $normX'!'x$normY'!' \
		\(	-size $aboutDim xc:"$transparent" -fill "$TRANSLUCENT" \
			-draw 'roundrectangle 0,0 '"$(echo $aboutDim | tr 'x' ',')"' 20,20' \
			-bordercolor "$transparent" -border 20 \
			\(	+clone -negate -blur 0x8 \) \
			+swap -gravity center -compose src-atop -composite \
			-fill "$TEXTCOLOR" $MFONT -pointsize $MFONTSIZE -gravity north \
			-annotate +0+30 "@$aboutTxt" \
		\) \
		-gravity East -geometry +"$(( $offsetTVX+50 ))"+0 \
		-composite -depth 8 -density $normDensity -units PixelsPerInch \
		png:"$aboutPic" || error_out

	return 0
}

# -------------------------------------------------------------
# Write xml-Definitions (dvdauthor and spumux)
#
write_xml()
{

#
# Start a new xml definition
#
xml_start()
{

#
# Shall an intro mpeg be played? If so, create an fpc tag
#	
fpccmd="jump menu entry title"
if [ ! -z "$INTROMPG" ]; then
	let introvts=$vts+1
	fpccmd="jump title $introvts"
fi

#
# Check Playback mode
#
[ $LOOP -ge 0 ] && loopreg="g8=$LOOP" || loopreg="g8=0"
	
let g6="100+$vts+1"
cat << EOF >> "$XMLFILE"
	<vmgm>
		<fpc> { $loopreg; $fpccmd; } </fpc>
		<menus>
			<pgc entry="title" pause="0">
				<pre> {
						g1=0; g4=101; g6=$g6;
						if (g5 lt g4) g5=g4;
						if (g5 gt g6) g5=g6;
EOF

for i in $(seq 1 $vts); do
	cat << EOF >> "$XMLFILE"
						if (g8 eq $i) jump title $i;
EOF
done

for i in $(seq 1 $(( $vts+1 ))); do
let regi="$i+100"
let nexti="$i+1"
cat << EOF >> "$XMLFILE"
						if (g5 eq $regi) jump menu $nexti;
EOF
done
cat << EOF >> "$XMLFILE"
					  }
				</pre>
				<vob file="$EMPTYMPG" />
			</pgc>
EOF

return 0
}

#
#	Begin new xml-Definition for a pgc
#
xml_begin_pgc()
{
cat << EOF > "$thisspuxml"
<subpictures>
	<stream>
		<spu start="0"
			 highlight="${thisMask[1]}"
			 select="${thisMask[2]}"
			 autoorder="columns" force="yes"
			 autooutline="infer" outlinewidth="2">
EOF

let button="$1*1024"
cat << EOF >> "$XMLFILE"
			<pgc pause="0">
				<pre> { if (g0 lt 1024) g0=$button; button=g0; } </pre>
				<vob file="$thismpg" pause="$TIMEOUT" />
EOF

return 0
}

#
#	Write a new title into xml
#
xml_title()
{
if [ $1 -eq $thisvts ]; then
	if [ $1 -ne $about ]; then
		baction="g0=button; jump title $1;"
	else
		baction="jump menu entry title;"
	fi
else
	baction="g0=button; g5=$(( $1+100 )); jump menu entry title;"
fi 
cat << EOF >> "$XMLFILE"
				<button name="Title_$1"> { $baction } </button>
EOF

x0=$2
y0=$3
let x1="$tbgW+$x0"
let y1="$y0+$stepY-1"
[ $j -ne $about ] && right="Play" || right="Title_$1"
cat << EOF >> "$thisspuxml"
			<button name="Title_$1"
					x0="$x0" y0="$y0" x1="$x1" y1="$y1"
					up="Prev" down="Next"
					right="$right" left="Title_$1" />
EOF

return 0
}
#
#	End pgc definition
#
xml_end_pgc()
{
cat << EOF >> "$XMLFILE"
				<button name="noop"> { jump menu entry title; } </button>
				<button name="Next"> { g5=g5+1; g0=0; jump menu entry title; } </button>
				<button name="Prev"> { g5=g5-1; g0=0; jump menu entry title; } </button>
EOF
[ $1 -ne $about ] && paction="g0=button; jump title $1;" || paction="g5=101; jump menu entry title;"
cat << EOF >> "$XMLFILE"
				<post> { $paction } </post>
			</pgc>
EOF
cat << EOF >> "$thisspuxml"
			<action name="noop" />
			<action name="Prev" />
			<action name="Next" />
		</spu>
	</stream>
</subpictures>
EOF

return 0
}

#
#	Close vmgm xml definition
#
xml_finish()
{
cat << EOF >> "$XMLFILE"
		</menus>
	</vmgm>
EOF

return 0
}

case "$1" in
	start)
		xml_start
	;;
	begin_pgc)
		shift
		xml_begin_pgc $1
	;;
	title)
		shift
		xml_title "$@"
	;;
	end_pgc)
		shift
		xml_end_pgc $1
	;;
	finish)
		xml_finish
	;;
	*)
		error_out
	;;
esac

return 0
}

# ------------------------------
# Main Processing
#
#
# Is help wanted?
#
case "$1" in
  	-h|--help)
   	    usage
  	;;
esac

# We need some sub-routines from dvdwizardrc
# This file must reside in the same directory as the called script
# Should maybe go into a directory like /usr/local/share/dvdwizard
# but this would require an installation procedure - maybe in some
# later version.
#
rcfile="`dirname $0`/dvdwizardrc"
if [ -e "$rcfile" -a -r "$rcfile" ]; then
	. "$rcfile"
else
	echo "dvdwizardrc not found or is not readable. Aborting" >&2
    exit 1
fi

#
# Check, if all needed tools are available
#
check_tools 
#
# Ok, first define some default values
#
set_defaults "$@"
VMGMDIR="$BASEDIR/vmgm"
vts=""
VMGMTITLE=""
pics=0
NOTITLE=1
maxAddButtons=0

#
# Now deal with command line arguments
#
while [ -n "$*" ]; do
    case "$1" in
  	-C|--config-file)
    	shift
# -C and it's following parm already processed in set_defaults()
        shift
  	;;
	-o|--output)
 		shift
		VMGMDIR="$1"
	    shift
  	;;
  	-x|--xml)
	    shift
   	    XMLFILE="$1"
   	    shift
  	;;
  	-T|--vmgm)
	    shift
   	    VMGMTITLE="$1"
   	    NOTITLE=0
   	    shift
	;;
  	-N|--tvnorm)
	    shift
   	    TVNORM="$1"
        if [ "$TVNORM" == "PAL" -o "$TVNORM" == "NTSC" ]; then
        	:
        else
        	echo "Incorrect TV-Norm $TVNORM specified, only PAL and NTSC are supported. Aborting"
            echo "See $thisscript -h for more infos"
	        exit 1
		fi >&2
   	    shift
  	;;
  	-V|--tvsize)
	    shift
   	    TVSIZE="$1"
   	    shift
  	;;
  	-M|--menu)
	    shift
		defMenu=$MENU
   	    MENU=$(echo "$1" | tr 'a-z' 'A-Z')
		eval testtxt=\"\$TXT_VMGM_PLAY_$MENU\"
		if [ -z "$testtxt" ]; then
			echo "Text elements for menu language $1 does not seem to be defined correctly. Aborting"
	        echo "See $thisscript -h for more infos"
    	    exit 1
		fi >&2
   	    shift
  	;;
	-I|--intro)
	    shift
		INTROMPG="$1"
   		shift
	;;
	-L|--LOOP)
	    shift
		LOOP="$1"
   		shift
	;;
	-MS|--vmgmsound)
	    shift
		MENUSOUND="$1"
   		shift
	;;
  	-t|--vts)
		shift
        if [ -z "$vts" ]; then
        	vts=1
            eval VTSPIC_$vts=""
            eval VTSINFO_$vts=0
            eval VTSAUDIO_$vts=0
            eval VTSSUB_$vts=0
            eval VTSMSOUND_$vts=""
			vtsAddButtons=0
        else
        	let "vts+=1"
            eval VTSINFO_$vts=0
            eval VTSPIC_$vts=""
            eval VTSAUDIO_$vts=0
            eval VTSSUB_$vts=0
            eval VTSMSOUND_$vts=""
			vtsAddButtons=0
        fi
   	    eval VTSTITLE_$vts=\"\$1\"
   	    shift
  	;;
  	-b|--vtsmbg)
		shift
        if [ -z "$vts" ]; then
        	vts=1
            eval VTSTITLE_$vts=""
            eval VTSINFO_$vts=0
            eval VTSAUDIO_$vts=0
            eval VTSSUB_$vts=0
            eval VTSMSOUND_$vts=""
			vtsAddButtons=0
        fi
   	    eval VTSPIC_$vts=\"\$1\"
        pics=1
   	    shift
  	;;
  	-ms|--vtsmsound)
		shift
        if [ -z "$vts" ]; then
        	vts=1
            eval VTSTITLE_$vts=""
            eval VTSINFO_$vts=0
            eval VTSAUDIO_$vts=0
            eval VTSSUB_$vts=0
            eval VTSPIC_$vts=""
			vtsAddButtons=0
        fi
   	    eval VTSMSOUND_$vts=\"\$1\"
   	    shift
  	;;
  	--hasinfo)
        if [ -z "$vts" ]; then
        	vts=1
            eval VTSTITLE_$vts=""
            eval VTSPIC_$vts=""
            eval VTSAUDIO_$vts=0
            eval VTSSUB_$vts=0
            eval VTSMSOUND_$vts=""
			vtsAddButtons=0
        fi
   	    eval VTSINFO_$vts=1
		let "vtsAddButtons+=1"
		[ $vtsAddButtons -gt $maxAddButtons ] && maxAddButtons=$vtsAddButtons
   	    shift
  	;;
  	--hasaudio)
        if [ -z "$vts" ]; then
        	vts=1
            eval VTSTITLE_$vts=""
            eval VTSPIC_$vts=""
            eval VTSINFO_$vts=0
            eval VTSSUB_$vts=0
            eval VTSMSOUND_$vts=""
			vtsAddButtons=0
        fi
   	    eval VTSAUDIO_$vts=1
		let "vtsAddButtons+=1"
		[ $vtsAddButtons -gt $maxAddButtons ] && maxAddButtons=$vtsAddButtons
   	    shift
  	;;
  	--hassubtitle)
        if [ -z "$vts" ]; then
        	vts=1
            eval VTSTITLE_$vts=""
            eval VTSPIC_$vts=""
            eval VTSINFO_$vts=0
            eval VTSAUDIO_$vts=0
            eval VTSMSOUND_$vts=""
			vtsAddButtons=0
        fi
   	    eval VTSSUB_$vts=1
		let "vtsAddButtons+=1"
		[ $vtsAddButtons -gt $maxAddButtons ] && maxAddButtons=$vtsAddButtons
   	    shift
  	;;
  	*)
   	    echo "Unrecognized command line parameter $1. Aborting" >&2
        echo "See $thisscript -h for more infos" >&2
        exit 1
  	;;
    esac
done

#
# Set format parameters for PAL or NTSC
#
set_format

#
# Let's see, if all options are correct
# Check output-directories and files
#
mk_check_dir "$VMGMDIR" "NEW" "\$VMGMDIR -o|--output"
mk_check_file "$XMLFILE" "NEW" "\$XMLFILE -x|--xml"
[ ! -z "$MENUSOUND" ] && mk_check_file "$MENUSOUND" "OLD" "\$MENUSOUND -MS|--vmgmsound"
if [ -z "$vts" ]; then
	vts=1
    eval VTSTITLE_$vts=\"- no title specified -\"
    eval VTSPIC_$vts=""
fi

#
# Check Playback-Mode
#
if ! let x=$LOOP+0 ; then
	if [ ! $LOOP -eq 0 ]; then
		echo "Playback mode $LOOP (-L|--loop \$LOOP) is not numeric"
		error_out
	fi
fi
if [ $LOOP -lt -2 -o $LOOP -gt $vts ]; then
	echo "Playback mode $LOOP (-L|--loop \$LOOP) invalid."
	echo "Must be between -2 and number of titles on dvd ($vts)"
	error_out
fi

[ -z "$TIMEOUT" ] && TIMEOUT="inf"

#
# Check given pictures and create background for each titleset
#
lastpic="none of your business"
for i in $(seq 1 $vts); do
	eval vtsmsound=\$VTSMSOUND_$i
	[ ! -z "$vtsmsound" ] && mk_check_file "$vtsmsound" "OLD" "\$vtsmsound -ms|--vtsmsound for titleset #$i"
	eval bgpic=\"\$VTSPIC_$i\"
    [ ! -z "$bgpic" ] && mk_check_file "$bgpic" "OLD" "\$bgpic -b|--vtsmbg for titleset #$i"
	#
	# Create background pictures
	#
    newbg="$TMPDIR/common_objects/menubg_$i".png
    if [ "$bgpic" == "$lastpic" ]; then
    	ln -s "$lastbg" "$newbg"	# simply link to previous background, if pic didn't change
    else
    	prepare_bg $i "$bgpic"
    	lastpic="$bgpic"
    	lastbg="$newbg"
	fi

done
[ -z "$VMGMTITLE" ] && VMGMTITLE=$VTSTITLE_1

#
# Initialize Procedure
#
init_proc

#
# Create common graphic objects for the menu
#
pgmName=$(echo "$dvdwizard_ver" | cut -d' ' -f1)
pgmVer=$(echo "$dvdwizard_ver" | cut -d' ' -f3)
verStr="$pgmName-$pgmVer"
create_overlay "VMGM"
create_common_objects
cp "$emptympg" "$VMGMDIR/$(basename "$emptympg")"
EMPTYMPG="$VMGMDIR/$(basename "$emptympg")"
mk_about
mk_picts
mk_button_bar
mk_title_container

#
# Start the xml-Definition of the VMGM
#
write_xml start

#
# For every title we create its own menu mpg
# First create some temporary files which may be overwritten with each
# titleset
#
thistbg="$(mktemp -t png.XXXXXXXXXX)"
thisbmt=( "dummy" "$(mktemp -t png.XXXXXXXXXX)" "$(mktemp -t png.XXXXXXXXXX)" )
maskPic="$(mktemp -t png.XXXXXXXXXX)"

#
# Now loop through all titlesets (including "about")
#
for i in $(seq 1 $about); do
	# init loop
	echo "Now preparing menu for titleset $i..."
	thisppm="$VMGMDIR/vts_${i}_bg.ppm"
	thisspuxml="$VMGMDIR/vts_${i}_spu.xml"
	thisMask=( "dummy" "$VMGMDIR/vts_${i}_hi.png" "$VMGMDIR/vts_${i}_sel.png" )
	thismpg="$VMGMDIR/VTS_$i.mpg"
	cp "$titleBG" "$thistbg"
	cp "$btnMasktrans" "${thisbmt[1]}"
	cp "$btnMasktrans" "${thisbmt[2]}"
	thisvts=$i
	let offsetY="$HFONTSIZE+20+$MFONTSIZE+10"
	let offsetbtn="($stepY-$MFONTSIZE)/2+$MFONTSIZE"
	x0=$offsetTVX
	let y0="$offsetY-$offsetbtn+$offsettbgY-4"
	ord=1
	maxtWidth=$(( $(identify -format %w "$thistbg")-($offsetX2 * 2) -50 ))

	# begin pgc in xml
	write_xml begin_pgc $i
	
	#
	# Write titlestrings onto container
	#
	for j in $(seq 1 $about); do
		eval tstring=\"\$VTSTITLE_$j\"
		if [ $j -eq $thisvts ]; then
			tcolor="${hiColor[1]}"
		else
			tcolor="${hiColor[0]}"
		fi
		if [ $j -ne $about ]; then
			trim_title $maxtWidth "$MFONTTYPE" $MFONTSIZE "$tstring"
			convert "$thistbg" \
				$MFONT -pointsize $MFONTSIZE -fill $tcolor \
				-draw 'text '$offsetX1','$offsetY' "'$ord'."' \
				-draw 'text '$offsetX2','$offsetY' "'"$trimText"'"' \
				png:"$thistbg" || error_out
		else
			trim_title $maxtWidth "$MFONTTYPE" $(( $MFONTSIZE-3 )) "$txt_ABOUT"
			convert "$thistbg" \
				$MFONT -pointsize $(( $MFONTSIZE-3 )) -fill "$tcolor" \
				-draw 'gravity southwest text 20,15 "...'"$trimText"' dvdwizard"' \
				png:"$thistbg" || error_out
			let y0="$offsetTVY+$TVHeight-$stepY+1"
		fi
		write_xml title $j $x0 $y0
		let "ord+=1"
		let "offsetY+=$stepY"
		let y0+="$stepY+1"
	done

	# paint buttons if not "about"	
	[ $i -ne $about ] && place_buttons $i

	# end pgc-definition in xml
	write_xml end_pgc $i

	# place vts picture onto background
	place_vtspic

	[ "$NOTITLE" -ne 1 -a ! -z "$VMGMTITLE" ] && print_title

	#
	# Add a little motion blur to the menu background to eliminate flickering on
	# TV screens (available if IM >= 6.2.5)
	# Thx to Rick Harris for this hint!
	#
	[ ! "$IM_VERSION3" \< "6.2.5" ] && \
	mogrify -density $normDensity -units PixelsPerInch -motion-blur 0x1+90 -depth 8 \
		"$thisppm"
	
	#
	# Select Audio Track for menu and convert to ac3, if neccessary
	#
	eval audiotrack=\"\$VTSMSOUND_$i\"
	[ -z $audiotrack ] && audiotrack="$MENUSOUND"
	[ -z $audiotrack ] && audiotrack="$silence"
	fext="${audiotrack##*.}"
	
	if [ "$fext" != "ac3" ]; then
		audiotrack_ac3="$TMPDIR/common_objects/vts_$i.ac3"
		if [ ! -e "$audiotrack_ac3" ]; then
			ffmpeg -i "$audiotrack" -ab 224kb -ar 48000 -ac 2 "$audiotrack_ac3" 1>/dev/null 2>&1 || error_out
		fi
		audiotrack="$audiotrack_ac3"
	fi
	
	#
	# Create MPEG-Stream from Background-Picture and mux with buttonmasks
	#
	ppmtoy4m -S 420mpeg2 -A 59:54 -n 1 -F "$encFrameRate" -r "$thisppm" | \
		mpeg2enc -a 2 -n "$encNorm" -f 8 -o /dev/stdout | \
		mplex -f 8 -o /dev/stdout /dev/stdin "$audiotrack" | \
  		spumux -v4 "$thisspuxml" > "$thismpg" || error_out
done

# close xml definition
write_xml finish

# Cleanup temporary directory if script was called directly
#
cleanup_tmpdir

#
# Ok, work finished. Hope everything is ok. ;-)
#
echo "done"

exit 0
