#!/usr/bin/env bash
#
#   mk_vmgm 
#     - Create Main menu of the DVD (VMGM) for authoring a DVD with dvdauthor
#
#   Copyright (c) 2004-2008 W. Wershofen <itconsult at wershofen.de>
#   Copyright (c) 2010-2011 Markus Kohm <kohm at users.sf.net>
#   Copyright (c) 2009-2012 Joo Martin <joomart2009 at users.sf.net>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This package is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Changes:
#
#   2004-04-13  Wolfgang Wershofen
#               * initial version
#   2006-08-31  Wolfgang Wershofen
#               * change whole layout of menu
#               * support for multiple languages (-M)
#               * add subtitle button
#   2009-06-23  Joo Martin
#               * add aspect ratio option for menu background image (-r)
#   2010-06-21  Markus Kohm
#               * renamed dvdwizardrc into dvdwizard_common
#               * usage of gettext features for multilanguage ui
#                 -several `echo' replaced by `printf'
#   2010-06-22  Markus Kohm
#               * usage of printf to place ${DW_NAME}
#   2010-09-29  Joo Martin
#               * relaced `-ab 224kb' by `-ab 224000' at ffmpeg calls
#   2011-01-04  Joo Martion
#               * setting of VIDEO_FORMAT at call of spumux
#   2012-03-18  Joo Martin
#               * user config file always in $HOME/.config/dvdwizard/
#
# -------------------------------------------------------------------------

#
# i18n
#
export TEXTDOMAIN=dvdwizard
export TEXTDOMAINDIR="@LOCALEDIR@"

# We need some sub-routines from dvdwizard_common.
# This file must be found at PATH.
#
. dvdwizard_common || {
    echo $"FATAL ERROR: could not execute common function file \`dvdwizard_common'!
You have to install \`dvdwizard_common' somewhere at PATH." >&2
    exit 1
}

# Usage message
#
usagetext=$"
Usage:	${thisscript} [options]
	${thisscript} -h|--help
	${thisscript} -v|--version

general processing:
-------------------
-C  | --config-file	Filename of dvdwizard-configuration file.
			[~/.config/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]
-h  | --help		Print this lot out.
-v  | --version		Print version and exit.

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

DVD-specific options:
---------------------
-T  | --vmgm <string>	Titlestring for the whole DVD; if not specified
			no title will be printed on the main (VMGM) menu.
-N  | --tvnorm		TV-Norm to use <PAL|NTSC>         [PAL]
			(PAL = 25fps, 720x576 and NTSC = 29.97fps, 720x480)
-V  | --tvsize		Visible Area on TV-Screen <XxY>   [660x530]
-M  | --menu		Language to use in menu items;    [en]
			strings 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 are:
			 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 all titles endlessly,
			1...9 - 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 this titleset. Will be ignored for 
			single-titleset DVDs, if -T is given.
-b  | --vtsmbg		Filename of background picture for this titleset.
-r  | --bgratio		Define aspect ratio of menu background  [4:3]
-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, 
-r, -ms, --hasaudio, --hassubtitle and --hasinfo apply only to that titleset.
"

# ------------------------------------------
# Initialize constants troughout the whole script
#
init_proc()
{
    for i in HEADER DUMMY ABOUT ABOUT1 ABOUT2 ABOUTTXT; 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
	# joo: patch because of seldom false color selection
	replColorLine=$(identify -verbose "$maskPic" | \
	    sed -e 1,/Histogram/d | head -n4 | grep "rgba" | tail -n1)
	replColor='#'$(echo "$replColorLine" | cut -d'#' -f2 | cut -d' ' -f1)
	for s in 1 2; do
	    # joo: define SELCOLOR (hiColor[2]) always as background 
	    #      for the buttons
	    convert "$maskPic" -fill "${hiColor[2]}" \
		-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 %w:%h -)
    titleDimW=$(echo "$titleDim" | cut -d':' -f1)
    titleDimH=$(echo "$titleDim" | cut -d':' -f2)
    [ "${titleDimW}" -gt "${maxpW}" ] && titleDimW=$maxpW
    OffsetDimW=$(( ( $maxpW - $titleDimW - 60 ) / 2 ))
	
    convert "$thisppm" \
	\( -size "$titleDimW"x"$titleDimH" xc:"$transparent" \
	   -fill "$TRANSLUCENT" \
	   -draw 'roundrectangle 0,0 '"$titleDimW","$titleDimH"' 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 +$(( $OffsetDimW+$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
    if [ -z "$txt_ABOUTTXT" ]; then
        # compatible to old version of config file
	txt_ABOUT22=$(echo "$txt_ABOUT2" | sed 's/dvdwizard\ //' | sed 's/DVDwizard\ //' | sed 's/\ GPL//')
	aboutGPL="${DW_NAME} ${txt_ABOUT22} ${GPLVERS}"
	echo -e "${txt_ABOUT1}\n${verStr}\n\n${HOMEADDR}\n\n${aboutGPL}." > "$aboutTxt"
    else
	printf "${txt_ABOUTTXT}" "${verStr}" "${HOMEADDR}" "${DW_NAME}" "${GPLVERS}"> "$aboutTxt"
    fi
    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?
#
test_versionhelp "$@"

#
# 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
        	error_help $"Incorrect TV-Norm %s specified.\nOnly PAL and NTSC are supported." "$TVNORM (-N|--tvnorm $TVNORM)"
	    fi
   	    shift
  	    ;;
  	-V|--tvsize)
	    shift
   	    TVSIZE="$1"
   	    shift
  	    ;;
  	-M|--menu)
	    shift
	    defMenu=$MENU
   	    MENU=$(echo "$1" | tr [:lower:] [:upper:])
	    eval testtxt=\"\$TXT_VMGM_PLAY_$MENU\"
	    if [ -z "$testtxt" ]; then
		error_help $"Text elements for menu language %s do not seem to be defined correctly." "$1"
	    fi
   	    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
            else
        	let "vts+=1"
            fi
            eval VTSTITLE_$vts=\"\$1\"
            eval VTSINFO_$vts=0
            eval VTSPIC_$vts=""
            eval VTSAUDIO_$vts=0
            eval VTSSUB_$vts=0
            eval VTSMSOUND_$vts=""
            eval VTSRATIO_$vts=""
            vtsAddButtons=0
   	    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=""
		eval VTSRATIO_$vts=""
		vtsAddButtons=0
            fi
   	    eval VTSPIC_$vts=\"\$1\"
            pics=1
   	    shift
  	    ;;
  	-r|--bgratio)
	    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=""
		eval VTSRATIO_$vts=""
		vtsAddButtons=0
            fi
            eval VTSRATIO_$vts=\"\$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=""
		eval VTSRATIO_$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=""
		eval VTSRATIO_$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=""
		eval VTSRATIO_$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=""
		eval VTSRATIO_$vts=""
		vtsAddButtons=0
            fi
   	    eval VTSSUB_$vts=1
	    let "vtsAddButtons+=1"
	    [ $vtsAddButtons -gt $maxAddButtons ] && maxAddButtons=$vtsAddButtons
   	    shift
  	    ;;
  	*)
   	    error_help $"Unrecognized command line parameter \`%s'"! "$1"
  	    ;;
    esac
done

#
# 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 ! is_integer "$LOOP"; then
    error_help $"Playback mode %s is not numeric." \
	"$LOOP (-L|--loop \$LOOP)"
fi
if [ $LOOP -lt -2 -o $LOOP -gt $vts ]; then
    error_help $"Playback mode %s invalid.\nMust be between -2 and number of titles on dvd (%d)" \
	"$LOOP (-L|--loop \$LOOP)" $vts
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
    
    # Set format parameters for PAL or NTSC
    #
    eval BGRATIO=\"\$VTSRATIO_$i\"
    set_format

    # Check sound and background files
    #
    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
	# simply link to previous background, if pic did not change
	ln -s "$lastbg" "$newbg"
    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
#
verStr="${DW_NAME}-${DW_VERSIONX}"
# check for pre-release
[ $(echo "${DW_DATE}" | grep -c pre) -eq 1 ] && verStr="${verStr}pre"
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
    printf "Now preparing menu for titleset %d..." $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' "'"$trimText"'"' \
		png:"$thistbg" || error_out
	else
	    abouttxt=$(printf "${txt_ABOUT}" "${DW_NAME}")
	    trim_title $maxtWidth "$MFONTTYPE" $(( $MFONTSIZE-3 )) "$abouttxt"
	    convert "$thistbg" \
		$MFONT -pointsize $(( $MFONTSIZE-3 )) -fill "$tcolor" \
		-draw 'gravity southwest text 20,15 "'"$trimText"'"' \
		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 for IM >= 6.2.5) - Thx to Rick Harris for this hint!
    #
    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 224000 -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
    #
    [ ! -z "$DEBUG" ] && \
	echo -e "\nppmtoy4m -S 420mpeg2 -A $pixAspect -n 1 -F $encFrameRate -r $thisppm |" \
	    "mpeg2enc -a $mpgAspect -n $encNorm -f 8 -q 5 -o /dev/stdout |" \
	    "mplex -f 8 -o /dev/stdout /dev/stdin $audiotrack |" \
  	    "spumux -v4 $thisspuxml > $thismpg || error_out "

    ppmtoy4m -S 420mpeg2 -A "$pixAspect" -n 1 -F "$encFrameRate" -r "$thisppm" \
	| mpeg2enc -a "$mpgAspect" -n "$encNorm" -f 8 -q 5 -o /dev/stdout \
	| mplex -f 8 -o /dev/stdout /dev/stdin "$audiotrack" \
	| VIDEO_FORMAT="$TVNORM" 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
