#!/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.4.3: Menu multilingual (Stefan Becker) 
#        
# needs the following tools to run:
# - ImageMagick >= 5.5.4
# - toolame >= 0.2l
# - ppmtoy4m, mpeg2enc and mplex from mjpegtools >= 1.6.1
# - spumux from dvdauthor >= 0.6.0
#
usage()
{
 cat <<EOF
Usage: `basename $0` [options]

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 final DVD will be stored [\$BASEDIR/dvd]
-x | --xml		Print dvdauthor XML-specs into this file
			[$BASEDIR/dvdwizard.xml]
--notitle		Suppressed printing of DVD-Title on VMGM-Menu

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, titlestring from the first title on the DVD will be
		used
-B | --vmgmbg	Image to use as background for the menu buttons
		If not specified, mk_vmgm will create one from scratch
-N | --tvnorm	Choose from PAL (25fps, 720x576) or NTSC (29.97 fps, 720x480)
		[PAL]
-V | --tvsize	Visible area of frame on TV set. [635x535]

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
--hasaudio	Title has multiple audio tracks. A button to jump to the audio
		selection menu will be created
--hasinfo	Title has EPG-Informations available. A button to jump to the
		info panel will be created (not yet implemented)

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

EOF
exit 1
}
# ------------------------------------------
# Create Button Pictograms for VMGM-Options
#
mk_picts()
{
tWidth=$(convert -size 300x$pictHeight xc:black -fill red -pointsize $MFONTSIZE \
   				 -draw 'gravity center text 0,0 "--Select Chapter"' -trim png:- | \
        	identify - | cut -d' ' -f3 | cut -d'+' -f1 | cut -d'x' -f1)
color='rgba(128,192,255,255)'
subcolor=white
state=( pict high sel )
fcolor=( white red yellow )
for s in 0 1 2; do
	pictPlay[s]="$workDir"/tmp_${state[s]}_play.png
	pictInfo[s]="$workDir"/tmp_${state[s]}_info.png
	pictAudio[s]="$workDir"/tmp_${state[s]}_audio.png
	pictMenu[s]="$workDir"/tmp_${state[s]}_menu.png
	pictEmpty[s]="$workDir"/tmp_${state[s]}_empty.png
    if [ $s -eq 0 ]; then
		convert -size 45x45 xc:"$color" -strokewidth 2 \
				-fill "$color" -stroke black \
        		-draw 'circle 23,23 23,5' \
        		-draw 'polygon 15,12 37,23 15,34' \
        		-stroke ${fcolor[s]} -draw 'circle 22,22 22,4' \
        		-fill ${fcolor[s]} -draw 'polygon 14,11 36,22 14,33' \
        		-trim "${pictPlay[s]}" || error_out
		pictSize=$(identify "${pictPlay[s]}" | cut -d' ' -f3 | cut -d'+' -f1)
		pictWidth=$(echo $pictSize | cut -d'x' -f1)
		pictHeight=$(echo $pictSize | cut -d'x' -f2)
		convert -size 45x45 xc:"$color" -strokewidth 2 \
				-fill "$color" -stroke black -pointsize 34 \
        		-draw 'circle 23,23 23,5' \
        		-draw 'gravity center text 1,1 "i"' \
        		-stroke ${fcolor[s]} -draw 'circle 22,22 22,4' \
	        	-fill ${fcolor[s]} -draw 'gravity center text 0,0 "i"' \
    	    	-trim "${pictInfo[s]}" || error_out
		convert -size 45x45 xc:"$color" -strokewidth 2 \
				-fill "$color" -stroke black -pointsize 34 \
        		-draw 'circle 23,23 23,5' \
        		-draw 'gravity center text 1,1 "a"' \
	        	-stroke ${fcolor[s]} -draw 'circle 22,22 22,4' \
    	    	-fill ${fcolor[s]} -draw 'gravity center text 0,0 "a"' \
        		-trim "${pictAudio[s]}" || error_out
		convert -size 45x45 xc:"$color" -strokewidth 2 \
				-fill "$color" -stroke black -pointsize 34 \
        		-draw 'circle 23,23 23,5' \
        		-draw 'gravity center text 1,1 "?"' \
	        	-stroke ${fcolor[s]} -draw 'circle 22,22 22,4' \
    	    	-fill ${fcolor[s]} -draw 'gravity center text 0,0 "?"' \
        		-trim "${pictMenu[s]}" || error_out
 	else
  		let bWidth=$tWidth+$pictWidth+10
		convert +antialias -size 45x45 xc:"$color" -strokewidth 2 -fill "$color" \
                -stroke ${fcolor[s]} -draw 'circle 22,22 22,4' \
        		-fill ${fcolor[s]} -draw 'polygon 14,11 36,22 14,33' \
        		-trim "${pictPlay[s]}" || error_out
    	convert +antialias -size ${bWidth}x${pictHeight} xc:"$subcolor" -pointsize $MFONTSIZE \
        		-fill ${fcolor[s]} -draw 'gravity east text '"$(( $pictWidth+5 ))""$TEXT_PLAY_MOVIE" \
                png:- | \
        composite -compose over -gravity east "${pictPlay[s]}" - "${pictPlay[s]}" || error_out
        mogrify -colors 2 "${pictPlay[s]}" || error_out
		convert +antialias -size 45x45 xc:"$color" -strokewidth 2 -fill "$color" \
                -stroke ${fcolor[s]} -draw 'circle 22,22 22,4' -pointsize 34 \
	        	-fill ${fcolor[s]} -draw 'gravity center text 0,0 "i"' \
    	    	-trim "${pictInfo[s]}" || error_out
        convert +antialias -size ${bWidth}x${pictHeight} xc:"$subcolor" -pointsize $MFONTSIZE \
        		-fill ${fcolor[s]} -draw 'gravity east text '"$(( $pictWidth+5 ))""$TEXT_SHOW_INFOS" \
                png:- | \
        composite -compose over -gravity east "${pictInfo[s]}" - "${pictInfo[s]}" || error_out
        mogrify -colors 2 "${pictInfo[s]}" || error_out
		convert +antialias -size 45x45 xc:"$color" -strokewidth 2 -fill "$color" -pointsize 34 \
                -stroke ${fcolor[s]} -draw 'circle 22,22 22,4' \
    	    	-fill ${fcolor[s]} -draw 'gravity center text 0,0 "a"' \
        		-trim "${pictAudio[s]}" || error_out
        convert +antialias -size ${bWidth}x${pictHeight} xc:"$subcolor" -pointsize $MFONTSIZE \
        		-fill ${fcolor[s]} -draw 'gravity east text '"$(( $pictWidth+5 ))""$TEXT_SELECT_AUDIO" \
                png:- | \
        composite -compose over -gravity east "${pictAudio[s]}" - "${pictAudio[s]}" || error_out
        mogrify -colors 2 "${pictAudio[s]}" || error_out
		convert +antialias -size 45x45 xc:"$color" -strokewidth 2 -fill "$color" -pointsize 34 \
                -stroke ${fcolor[s]} -draw 'circle 22,22 22,4' \
    	    	-fill ${fcolor[s]} -draw 'gravity center text 0,0 "?"' \
        		-trim "${pictMenu[s]}" || error_out
        convert +antialias -size ${bWidth}x${pictHeight} xc:"$subcolor" -pointsize $MFONTSIZE \
        		-fill ${fcolor[s]} -draw 'gravity east text '"$(( $pictWidth+5 ))""$TEXT_SELECT_CHAPTER" \
                png:- | \
        composite -compose over -gravity east "${pictMenu[s]}" - "${pictMenu[s]}" || error_out
        mogrify -colors 2 "${pictMenu[s]}" || error_out
    fi
	convert -size $pictSize xc:none "${pictEmpty[s]}" || error_out
done
return 0
}

# -------------------------------------------------------------
# Create the VTS-Tile with thumbnail, buttons and titlestring
#
mk_vts_tile()
{
indx=$1
#
# Create Button-Bar, Highlighted and Selected Masks
#
eval infDisp=\$VTSINFO_$indx
eval audioDisp=\$VTSAUDIO_$indx
for s in 0 1 2; do
	pictList=( "${pictPlay[s]}" "${pictMenu[s]}" )
	if [ "$audioDisp" == "1" ]; then
		pictList[2]="${pictAudio[s]}"
	else
		pictList[2]="${pictEmpty[s]}"
	fi
	if [ "$infDisp" == "1" ]; then
		pictList[3]="${pictInfo[s]}"
	else
		pictList[3]="${pictEmpty[s]}"
	fi
	bbar[s]="$workDir"/tmp_${state[s]}_bar.png
    pictSize=$(identify "${pictPlay[s]}" | cut -d' ' -f3 | cut -d'+' -f1)
	montage -background none -geometry ${pictSize}+5+5 -tile 1x4 \
		${pictList[@]} "${bbar[s]}"
	barSize[s]=$(identify "${bbar[s]}" | cut -d' ' -f3 | cut -d'+' -f1)
	barX[s]=$(echo "${barSize[s]}" | cut -d'x' -f1)
	let barY[s]=$(echo "${barSize[s]}" | cut -d'x' -f2)+10
    [ $s -ne 0 ] && mogrify -colors 3 "${bbar[s]}"
done

#
# Resize Thumbnail
#
convert -trim -geometry 300x${thumbHeight}! "$vtspic" "$workthumb" || error_out
thumbSize=$(identify "$workthumb" | cut -d' ' -f3 | cut -d'+' -f1)
let tileX=$(echo "$thumbSize" | cut -d'x' -f1)+40
let tileY=$(echo "$thumbSize" | cut -d'x' -f2)+40
tbarX=270
let "tbarY=$HFONTSIZE+($HFONTSIZE/2)"
let mintileY=$barY+$tbarY+5
[ $mintileY -gt $tileY ] && let tileY=$mintileY

#
# Take care of the titlestring
#
eval title=\"\$VTSTITLE_$indx\"
[ -z "$title" ] && title="Title $indx"
[ $vts -eq 1 ] && title="$TEXT_SELECT_OPTION"
cutstring="$title"
mintSize=$(convert -size "$TVSIZE" xc:black -pointsize $HFONTSIZE -fill red \
		   -draw 'gravity center text 0,0 "'"$cutstring"'"' \
		   -trim png:- | identify - | cut -d' ' -f3 | cut -dx -f1) || error_out
while [ $mintSize -gt $(( $tbarX-10 )) ]; do
    prev_cutstring="$cutstring"
    if [ $(expr index "$cutstring" ' ') -ne 0 ]; then
	lastw=" ${cutstring##*\ }"
    else
	slen=${#cutstring}
	let ssbeg=$slen-4
	lastw=${cutstring:$ssbeg}
    fi
    cutstring="${cutstring/%$lastw/...}"
    mintSize=$(convert -size "$TVSIZE" xc:black -pointsize $HFONTSIZE -fill red \
			-draw 'gravity center text 0,0 "'"$cutstring"'"' \
			-trim png:- | identify - | cut -d' ' -f3 | cut -dx -f1) || error_out
    if [ "$cutstring" == "$prev_cutstring" ]; then
	echo "Could not reduce Titlestring $title any further to fit into thumbnail header of VMGM"
	echo "Supply a shorter titlestring to solve the problem"
	error_out
    fi
done

#
# Put it all together
#
bgcolor='rgba(255,255,255,48)'
barcolor='rgba(128,192,255,96)'
if [ 0"$IM_VERSION" -lt 6 ]; then
    let tposY=($tbarY-$HFONTSIZE)/2+$HFONTSIZE
else
    let tposY=($tbarY-$HFONTSIZE+5)/2
fi
tile="$workDir"/tmp_tile_$indx.png
convert -size ${tileX}x${tileY} xc:"$bgcolor" png:- | \
	composite -compose copy -gravity center "$workthumb" - png:- | \
	convert -fill "$barcolor" \
			-draw 'roundrectangle 5,5 '"$(( $tbarX+5 )),$(( $tbarY+5 ))"' 10,10' \
			-draw 'roundrectangle '"$(( $tileX-${barX[0]}-5 )),$(( $tileY-${barY[0]}-5 )) $(( $tileX-5 )),$(( $tileY-5 ))"' 10,10' \
	        -fill black -pointsize $HFONTSIZE \
        	-draw 'gravity northwest text 16,'"$(( $tposY+1 ))"' "'"$cutstring"'"' \
	        -fill white -draw 'gravity northwest text 15,'"$tposY"' "'"$cutstring"'"' - png:- | \
	composite -compose atop -gravity southeast -geometry +5+10 "${bbar[0]}" - "$tile" || error_out
eval VTSTILE_$indx[0]=\"\$tile\"

#
# Compose the Masks
#
for s in 1 2; do
	tile="$workDir"/tmp_tile_${state[s]}_$indx.png
	convert +antialias -size ${tileX}x${tileY} xc:none png:- | \
		composite -compose over -gravity southeast -geometry +5+10 "${bbar[s]}" - "$tile" || error_out
    mogrify -colors 3 "$tile" || error_out
	eval VTSTILE_$indx[s]=\"\$tile\"
done

return 0
}

# ------------------------------
# Main Processing
#
# 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

#
# Ok, first define some default values
#
set_defaults "$@"
VMGMDIR="."
vts=""
VMGMTITLE=""
pics=0

#
# Now deal with command line arguments
#
while [ -n "$*" ]; do
    case "$1" in
  	-h|--help)
   	    usage
  	;;
  	-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"
   	    shift
	;;
  	-B|--vmgmbg)
	    shift
   	    VMGMBG="$1"
   	    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" >&2
            usage
        fi
   	    shift
  	;;
  	-V|--tvsize)
	    shift
   	    TVSIZE="$1"
   	    shift
  	;;
  	--notitle)
   	    NOTITLE=1
   	    shift
  	;;
  	-t|--vts)
		shift
        if [ -z "$vts" ]; then
        	vts=1
            eval VTSPIC_$vts=""
            eval VTSINFO_$vts=0
            eval VTSAUDIO_$vts=0
        else
        	let vts+=1
            eval VTSINFO_$vts=0
            eval VTSPIC_$vts=""
            eval VTSAUDIO_$vts=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
        fi
   	    eval VTSPIC_$vts=\"\$1\"
        pics=1
   	    shift
  	;;
  	--hasinfo)
        if [ -z "$vts" ]; then
        	vts=1
            eval VTSTITLE_$vts=""
            eval VTSPIC_$vts=""
            eval VTSAUDIO_$vts=0
        fi
   	    eval VTSINFO_$vts=1
   	    shift
  	;;
  	--hasaudio)
        if [ -z "$vts" ]; then
        	vts=1
            eval VTSTITLE_$vts=""
            eval VTSPIC_$vts=""
            eval VTSINFO_$vts=0
        fi
   	    eval VTSAUDIO_$vts=1
   	    shift
  	;;
  	*)
   	    echo "Unrecognized command line parameter $1. Aborting" >&2
        usage
  	;;
    esac
done

#
# Let's see, if all options are correct
# Check output-directories and files
#
mk_check_dir "$VMGMDIR" "NEW"
mk_check_dir "$TMPDIR" "NEW"
mk_check_file "$XMLFILE" "NEW"
[ ! -z "$VMGMBG" ] && mk_check_file "$VMGMBG" "OLD"
if [ -z "$vts" ]; then
	vts=1
    eval VTSTITLE_$vts=""
    eval VTSPIC_$vts=""
fi
for i in $(seq 1 $vts); do
	eval bgpic=\"\$VTSPIC_$i\"
    [ ! -z "$bgpic" ] && mk_check_file "$bgpic" "OLD"
done
[ -z "$VMGMTITLE" ] && VMGMTITLE=$VTSTITLE_1
[ $vts -eq 1 ] && VTSTITLE=""

#
# Do some file and directory preparation
#
ls -d "$TMPDIR"/tmp_mk_vmgm* > /dev/null 2>&1 && rm -R "$TMPDIR"/tmp_mk_vmgm*
workDir=`mktemp -d "$TMPDIR"/tmp_mk_vmgm_XXXXXX`
spuxml="$workDir"/tmp_spumux.xml

#
# Create an empty audio track for the menu mpeg
#
create_silence

#
# Prepare the background picture
# ($VMGMBG will be converted to $workbg)
#
prepare_bg "$VMGMBG"

#
# Place the title on the picture, if not opted out by --notitle
# First, check if title will fit in one row - if not split it!
#
if [ "$NOTITLE" -ne 1 -a ! -z "$VMGMTITLE" ]; then
	echo -n "Placing title on the menu..."
	trow="$VMGMTITLE"
	twords=$(echo "$VMGMTITLE" | wc -w)
	wpr=$twords
	rows=1
	mintSize=$(convert -size $normSize xc:black -pointsize $TFONTSIZE -fill red -stroke white \
    	               -draw 'gravity center text 0,0 "'"$trow"'"' \
        	           -trim png:- | identify - | cut -d' ' -f3 | cut -dx -f1) || error_out
	while [ $mintSize -gt $(( $tvX-25 )) -a $wpr -gt 1 ]; do
		let rows+=1
		let "wpr=($twords/$rows)"
		wir=1
		trow=""
		for w in $(seq 1 $twords); do
			tword=$(echo "$VMGMTITLE" | cut -d' ' -f$w)
			trow="$trow $tword"
			let wir+=1
			if [ $wir -gt $wpr ]; then
				trow="$trow \\n"
				wir=1
			fi
   		done
		mintSize=$(convert -size $normSize xc:black -pointsize $TFONTSIZE -fill red -stroke white \
        		           -draw 'gravity center text 0,0 "'"$trow"'"' \
						   -trim png:- | identify - | cut -d' ' -f3 | cut -dx -f1) || error_out
	done
	mogrify -fill black -stroke white -pointsize $TFONTSIZE \
    	    -draw 'gravity north text 0,'"$(( $offsetY+50 ))"' "'"$trow"'"' "$workbg" || error_out
 	echo "done"
fi

#
# Determine height of first VTS-Thumbnail (all subsequent thumbnails will align with this one)
# if no picture is supplied, create an image saying that :-)
#
echo -n "Creating VTS-Thumbnails..."
emptythumb="$workDir"/tmp_empty_thumb.jpg
workthumb="$workDir"/tmp_thumb.png
convert -fill black -stroke white -pointsize 60 \
		-draw 'gravity center text 0,0 "Sorry\nNo Picture supplied\n:-("' -charcoal 0.2 "$workbg" "$emptythumb" || error_out
[ -z "$VTSPIC_1" ] && VTSPIC_1="$emptythumb"
thumbHeight=$(convert -geometry 300x "$VTSPIC_1" png:- | identify - | \
	cut -d' ' -f3 | cut -d'+' -f1 | cut -d'x' -f2)

#
# Create Button Pictograms
#
mk_picts

#
# Create Thumbnail-Tiles for every VTS
#
for i in $(seq 1 $vts); do
	eval vtspic=\"\$VTSPIC_$i\"
    [ -z "$vtspic" ] && vtspic="$emptythumb"
    mk_vts_tile $i
done
echo "done"

#
# Prepare the button panel
# Placement depends on number of VTS on the DVD
#
echo -n "Placing buttons on Background-Picture..."
case $vts in
	1)
    	rows=1
        cols=1
    	let panelX=$tileX
    	let panelY=$tileY
    	grav=( center )
    	offset=( +0+0 )
    ;;
    2|3|4)
    	let "rows=($vts-1)/2+1"
        cols=2
    	let panelX=$tileX*2
        let panelY=$tileY*$rows
	   	grav=( northwest northeast southwest southeast )
     	offset=( +0+0 +0+0 +0+0 +0+0 )
        if [ $vts -eq 3 ]; then
        	grav[2]=south
        fi
    ;;
    *)
    	let "rows=($vts-1)/3+1"
        cols=3
    	let panelX=$tileX*3
        let panelY=$tileY*$rows
        grav=( northwest north northeast west center east southwest south southeast )
        offset=( +0+0 +0+0 +0+0 +0+0 +0+0 +0+0 +0+0 +0+0 +0+0 )
        if [ $vts -le 6 ]; then
        	for i in 3 4 5; do
            	let copyi=$i+3
                grav[i]=${grav[copyi]}
         	done
        fi
        case $vts in
            5)
            	offset[4]=+$(( $tileX/2 ))+0
                offset[3]=+$(( $tileX/2 ))+0
                grav[4]=southeast
         	;;
        	7)
            	grav[6]=south
         	;;
            8)
            	offset[7]=+$(( $tileX/2 ))+0
                offset[6]=+$(( $tileX/2 ))+0
                grav[7]=southeast
         	;;
            *)
            	:
         	;;
         esac
    ;;
esac

#
# Create the panels
#
menupanel[0]="$workDir"/tmp_panel.png
menupanel[1]="$workDir"/tmp_high_panel.png
menupanel[2]="$workDir"/tmp_sel_panel.png

for s in 0 1 2; do
	if [ $s -eq 0 ]; then
		convert -size ${panelX}x${panelY} xc:'rgba(255,255,255,48)' "${menupanel[s]}" || error_out
	else
		convert -size ${panelX}x${panelY} xc:none "${menupanel[s]}" || error_out
  	fi

    for i in $(seq 1 $vts); do
		let indx=$i-1
    	eval tile=\"\${VTSTILE_$i[s]}\"
    	composite -compose copy -gravity ${grav[indx]} -geometry ${offset[indx]} \
        "$tile" "${menupanel[s]}" "${menupanel[s]}" || error_out
  	done
done

#
# Panel may not fit on background
# Check width
#
if [ $panelX -gt $(( $tvX-40 )) ]; then
	for s in 0 1 2; do
    	[ $s -ne 0 ] && aa="+antialias -filter Point" || aa=""
    	mogrify $aa -geometry $(( $tvX-40 ))x "${menupanel[s]}"
 	done
fi

#
# Check height
#
panelY=$(identify "${menupanel[0]}" | cut -d' ' -f3 | cut -d'+' -f1 | cut -d'x' -f2)
if [ $panelY -gt $(( ($tvY/10)*8-30 )) ]; then
	for s in 0 1 2; do
    	[ $s -ne 0 ] && aa="+antialias -filter Point" || aa=""
    	mogrify $aa -geometry x$(( ($tvY/10)*8-30 )) "${menupanel[s]}"
 	done
fi

#
# Place panel on background image
#
let panelX=$(identify "${menupanel[0]}" | cut -d' ' -f3 | cut -d'+' -f1 | cut -d'x' -f1)+20
let panelY=$(identify "${menupanel[0]}" | cut -d' ' -f3 | cut -d'+' -f1 | cut -d'x' -f2)+20
let pRoomY="($tvY/10)*8-10"
let pOY="($pRoomY-$panelY)/2"
[ $pOY -lt 10 ] && pOY=10
convert -size ${panelX}x${panelY} xc:'rgba(255,255,255,48)' png:- | \
composite -compose copy -gravity center "${menupanel[0]}" - png:- | \
composite -compose over -gravity south -geometry +0+$(( $pOY+10 )) - "$workbg" "$workbg" || error_out
mogrify -density 75x80 -depth 8 "$workbg" || error_out
for s in 1 2; do
	maskPic[s]="$workDir"/tmp_${state[s]}_mask.png
	convert -size $normSize xc:none png:- | \
    	composite -compose over -gravity south -geometry +0+$(( $pOY+20 )) \
     			  "${menupanel[s]}" - "${maskPic[s]}" || error_out
 		mogrify -colors 4 -density 75x80 +dither "${maskPic[s]}" || error_out
        mogrify -fill 'rgba(255,255,255,48)' -fuzz 2% -opaque "$subcolor" "${maskPic[s]}" || error_out
done
echo "done"

#
# This is the xml to tell spumux what to do
#
echo "Creating MPEG-Stream..."
cat <<EOF > "$spuxml"
<subpictures>
   <stream>
      <spu start="0"
           highlight="${maskPic[1]}"
           select="${maskPic[2]}"
           autoorder="rows" force="yes"
           autooutline="infer" outlinewidth="2" />
   </stream>
</subpictures>
EOF

#
# Create MPEG-Stream from Background-Picture and mux with buttonmasks
#
videotrack="$workDir"/tmp_vmgm.m2v
menumpeg="$VMGMDIR"/vmgm.mpg
if [ "$TVNORM" == "NTSC" ]; then
	encFrameRate="30000:1001"
	encNorm="n"
else
	encFrameRate="25:1"
	encNorm="p"
fi
ppmtoy4m -n 10 -F "$encFrameRate" -r "$workbg" | \
	mpeg2enc -a 2 -n "$encNorm" -f 8 -o "$videotrack" || error_out
mplex -f 8 -o /dev/stdout "$videotrack" "$audiotrack" | \
  	spumux -v4 "$spuxml" > "$menumpeg" || error_out
echo "done"

#
# Create the xml definition for dvdauthor
#
echo -n "Writing out XML-definition..."
echo -e "\t<vmgm>" >> $XMLFILE
echo -e "\t\t<menus>" >> $XMLFILE
echo -e "\t\t\t<pgc entry=\"title\" pause=\"0\">" >> $XMLFILE
echo -e "\t\t\t\t<pre> { g1=0; if (g0 lt 1024) button=1024; else button=g0; if (g9 ne 42) { audio=0; g2=0; g9=42; } } </pre>" >> $XMLFILE
echo -e "\t\t\t\t<vob file=\"$menumpeg\" pause=\"inf\"/>" >> $XMLFILE

#
# Loop through all the buttons to be defined for each titleset
#
target=( 'jump title $title' 'jump titleset $title menu entry ptt' 'jump titleset $title menu entry audio' 'jump titleset $title menu entry angle' )
bi=0
for row in $(seq 1 $rows); do
	let "begvts=($row-1)*cols+1"
	let endvts=$begvts+cols-1
	[ $endvts -gt $vts ] && endvts=$vts
	for button in 0 1 2 3; do
		for title in $(seq $begvts $endvts); do
        	ok=1
			[ "$button" -eq 2 ] && eval ok=\$VTSAUDIO_$title
			[ "$button" -eq 3 ] && eval ok=\$VTSINFO_$title
			if [ "$ok" -eq 1 ]; then
				eval jump="\$(echo ${target[button]})"
				buttonxml="<button name=\"$(( $bi+1 ))\"> { g0=button; ${jump}; } </button>"
                echo -e "\t\t\t\t${buttonxml}" >> $XMLFILE
				let bi+=1
			fi
		done
	done
done
echo -e "\t\t\t</pgc>" >> $XMLFILE
echo -e "\t\t</menus>" >> $XMLFILE
echo -e "\t</vmgm>" >> $XMLFILE
echo "done"

#
# Ok, work finished. Hope everything is ok. Remove the working directory
#
rm -R "$workDir"

exit 0
