#!/bin/bash
#
# mk_vtsm_lang - Create language selection menus for audio and video tracks in current VTSM
#
# Version   0.5 written by Wolfgang Wershofen (mailto: itconsult at wershofen.de)
#
# See TOOLS in the dvdwizard tarball for info about needed tools and programs
#
usage()
{
 cat <<EOF
Usage: `basename $0` --audio [options] track_list
       `basename $0` --subtitle [options] track_list
       `basename $0` -h|--help

currently supported options:
----------------------------
-C  | --config-file	filename of dvdwizard-configuration file
			[~/.dvdwizard/dvdwizard.conf]
-o  | --output-dir	Define Output-Directory where ready-made menu-mpegs
			should be written to [.]
-x  | --xml-file	Define filename for xml-definition
			[<output-dir>/dvdwizard.xml]
-b  | --vtsmbg		Image to use as background for menu options.
-N  | --tvnorm		TV-Norm to use <PAL|NTSC> [PAL]
-V  | --tvsize		Visible area of frame on TV set. At least my tv does
			not show full "$normSize", but maybe yours can. [635x535]
-t  | --vts		Titleset on the DVD where the menus should belong 
			to [1]
-M  | --menu		Language to use in menu items [en]
			Textelements are defined in config file
-ms | --vtsmsound	Soundfile to be used as background sound for the 
			menu. If empty, a silent audio track will be 
			produced. Can be any format, ffmpeg recognizes and 
			will be converted to ac3, if neccessary.
--hasaudio		Title has multiple audio tracks. A button to jump to
			the audio selection menu will be created 
			Meaningless, if --audio is specified
--hassubtitle		Title has at least one Subtitle-Stream which may be
			activated in a subsequent subtitle-menu 
			Meaningless, if --subtitle is specified
--hasinfo		Title has EPG-Informations available. A button to
			jump to the info panel will be created
-h  | --help		print this lot out

track_list:
	one entry for each audio or subtitle track, comma separated
	for audio:	<lang>+<fmt>[[=s<0-31>],<lang>+<fmt>...]
			<lang>=2-Letter language code
			<fmt>=Audio format (MP2, AC3, DTS)
			<0-31>=binding to special forced subtitle track
			(not yet implemented!)
			e.g. de+ac3,en+mp2=s5
	for subtitle:	<lang>[[+hi],<lang>...]
			<lang>=2-Letter language code
			hi=Subtitle is for hearing impaired, will be noted
			on the menu as such 
			e.g. en,fr,de,de+hi

EOF
exit 1
}

# ------------------------------------------
# Initialize constants throughout the whole script
#
init_proc()
{
	for i in DVD CHAPTER AUDIO SUBS INFO RETURN AUDIOH SUBSH SUBHI SUBOFF; do
		eval txt_$i=\"\$TXT_VTSM_${i}_$MENU\"
	done

	if [ $MKAUDIO -eq 1 ]; then
		actMenu="$txt_AUDIO"
		eval actHeader=\"\$txt_AUDIOH\"
	else
		actMenu="$txt_SUBS"
		eval actHeader=\"\$txt_SUBSH\"
	fi

	[ -e "$TMPDIR/common_objects/.menucount" ] \
		&& prevmenus=$(cat "$TMPDIR/common_objects/.menucount") \
		|| prevmenus=2

	return 0
}

# ------------------------------------------
# Create Navigation-Panel without Prev/next-Arrows
#
mk_nav_panel()
{
	echo -n "Creating navigation panel..."
	targets="$*"
	navBar=( "$(mktemp -t png.XXXXXXXXXX)"  "$(mktemp -t png.XXXXXXXXXX)" )
	for state in 0 1; do
		convert null: png:"${navBar[state]}"
		for tgt in $targets; do
			if [ "$tgt" == "$actMenu" ]; then
				[ $state -eq 0 ] && btnInd=2 || btnInd=3
			else
				btnInd=$state
			fi
			addbtn="$TMPDIR/common_objects/navbtn_${tgt}_$btnInd.png"
			convert "${navBar[state]}" "$addbtn" +append png:"${navBar[state]}" || error_out
		done
		convert "${navBar[state]}" -crop +2+0 png:"${navBar[state]}" || error_out
	done
	fpat="$TMPDIR/navPnl_%d.png"
	pnlDim=$( convert "${navBar[0]}" -border 10x40 png:- | identify -format %wx%h -)
	draw1='image Copy 0,30 0,0 "'"${navBar[1]}"'"'
	draw2='image Copy 0,20 0,0 "'"$TMPDIR/common_objects/navbtn_${txt_RETURN}_1.png"'"'
	convert -size $pnlDim xc:transparent \
		\( -clone 0 +antialias -bordercolor transparent -border 10 \
			-gravity south -draw "$draw1" \
			-gravity north -draw "$draw2" \) \
		\( -clone 0 -fill $TRANSLUCENT \
			-draw 'roundrectangle 0,0 '$(echo $pnlDim | tr 'x' ',')' 20,20' \
			-bordercolor transparent -border 10 \
			\( +clone -negate -blur 0x8 \) \
			+swap -gravity center -compose src-atop -composite \
			"${navBar[0]}" -gravity south -geometry +0+30 -compose over -composite \
			"$TMPDIR/common_objects/navbtn_${txt_RETURN}_0.png" -gravity north \
			-geometry +0+20 -composite \) \
		-swap 0,2 -delete 2 -crop +0-30 png:"$fpat" || error_out

	navpnlh=$(identify -format %h "$TMPDIR/navPnl_0.png")
	echo "done"
	return 0
}

# ------------------------------------------
# Create Track Selection Panel
#
mk_track_panel()
{
	echo -n "Creating track selection panel..."
	# Add "subtitle off"-Button if we are building subtitle-menu
	if [ $MKSUBS -eq 1 ]; then
		let "hitrack+=1"
		btnText[hitrack]="$txt_SUBOFF"
	fi
	# Determine longest string
	thisDim=$( \
	convert -size $normSize xc:black $HFONT -pointsize $HFONTSIZE \
			-gravity center -fill white -annotate +0+0 "$actHeader" \
			-trim +repage png:- | \
			identify -format %wx%h -)
	maxlen=$(echo $thisDim | cut -d'x' -f1)
	maxHeight=$(echo $thisDim | cut -d'x' -f2)
	for trk in $(seq 0 $hitrack); do
		thisDim=$( \
		convert -size $normSize xc:black $MFONT -pointsize $MFONTSIZE \
				-gravity center -fill white -annotate +0+0 "${btnText[trk]}" \
				-trim +repage png:- | \
				identify -format %wx%h -)
		thislen=$(echo $thisDim | cut -d'x' -f1)
		thisHeight=$(echo $thisDim | cut -d'x' -f2)
		[ $thislen -gt $maxlen ] && maxlen=$thislen
		[ $thisHeight -gt $maxHeight ] && maxHeight=$thisHeight
	done
	let "maxlen+=10"
	let "maxHeight+=10"
	btnDim="$maxlen"x"$maxHeight"
	trkpnl=( "$(mktemp -t png.XXXXXXXXXX)"  "$(mktemp -t png.XXXXXXXXXX)" )
	for state in 0 1; do
		fillColor="${hiColor[state]}"
		convert null: png:"${trkpnl[state]}"
		if [ $state -eq 0 ]; then
			bgcolor=$transparent
			aa=""
		else
			bgcolor=$TRANSLUCENT
			aa="+antialias"
		fi
		for trk in $(seq 0 $hitrack); do
			addbtn="$(mktemp -t png.XXXXXXXXXX)"
			[ $MKSUBS -eq 1 -a $trk -eq $hitrack ] && bh=12 || bh=2
			convert "${trkpnl[state]}" \
				\( -size $btnDim xc:"$bgcolor" $aa \
					$MFONT -pointsize $MFONTSIZE -gravity west \
					-fill $fillColor -annotate +5+0 "${btnText[trk]}" \
					-bordercolor "$transparent" -border 10x$bh \) \
				-append png:"${trkpnl[state]}" || error_out
		done
		convert "${trkpnl[state]}" -crop +2+2 png:"${trkpnl[state]}" || error_out
	done
	tpat="$TMPDIR/trkpnl_%d.png"
	pnlDim=$( convert "${trkpnl[0]}" -border 10x50 png:- | identify -format %wx%h -)
	pnlWidth=$(echo $pnlDim | cut -d'x' -f1)
	convert -size $pnlDim xc:transparent \
		\( -clone 0 +antialias -bordercolor transparent -border 10 \
			-gravity northwest -draw 'image Copy 20,60 0,0 "'"${trkpnl[1]}"'"' \) \
		\( -clone 0 -fill $TRANSLUCENT \
			-draw 'roundrectangle 0,0 '$(echo $pnlDim | tr 'x' ',')' 20,20' \
			-bordercolor transparent -border 10 \
			\( +clone -negate -blur 0x8 \) \
			+swap -gravity center -compose src-atop -composite \
			-antialias $HFONT -pointsize $HFONTSIZE -gravity NorthWest \
			-fill "$shadow" -annotate +22+22 "$actHeader" \
			-draw 'line 22,'$(( $HFONTSIZE+27 ))','$(( $pnlWidth-10 ))','$(( $HFONTSIZE+27 ))'' \
			-draw 'line 22,'$(( $HFONTSIZE+28 ))','$(( $pnlWidth-10 ))','$(( $HFONTSIZE+28 ))'' \
			-fill "$HEADCOLOR" -annotate +20+20 "$actHeader" \
			-draw 'line 20,'$(( $HFONTSIZE+25 ))','$(( $pnlWidth-12 ))','$(( $HFONTSIZE+25 ))'' \
			-draw 'line 20,'$(( $HFONTSIZE+26 ))','$(( $pnlWidth-12 ))','$(( $HFONTSIZE+26 ))'' \
			"${trkpnl[0]}" -gravity northwest -geometry +20+60 -compose over -composite \) \
		-swap 0,2 -delete 2 png:"$tpat" || error_out
	[ $MKSUBS -eq 1 ] && let "hitrack-=1"
	echo "done"
	return 0
}

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

#
# Start a new xml definition
#
xml_start()
{
cat << EOF > "$thisspuxml"
<subpictures>
	<stream>
		<spu start="0"
			 highlight="${thisMask[1]}"
			 select="${thisMask[2]}"
			 autoorder="rows" force="yes"
			 autooutline="infer" outlinewidth="2">
EOF

	if [ $MKAUDIO -eq 1 ]; then
	cat << EOF >> "$XMLFILE"
			<pgc entry="audio" pause="0">
				<pre> { button=(audio+1)*1024; } </pre>
EOF
	else
	cat << EOF >> "$XMLFILE"
			<pgc entry="subtitle" pause="0">
				<pre> { if (subtitle lt 64) button=(subtitle+1)*1024;
					    if (subtitle ge 64) button=(subtitle-64+1)*1024; } </pre>
EOF
	fi

	cat << EOF >> "$XMLFILE"
				<vob file="$thismpg" pause="inf" />
EOF

return 0
}

#
#	Write the Selection buttons
#
xml_buttons()
{
	track=$1
	let btn="track+1"
	[ $MKAUDIO -eq 1 ] && xmlcmd="audio=$track; if (subtitle lt 64) subtitle=$track" || \
						xmlcmd="subtitle=$(( $track+64 ))"
	cat << EOF >> "$XMLFILE"
				<button name="Button_$btn"> { $xmlcmd;
										if (g1 eq 0) jump vmgm menu entry title;
										if (g1 eq 1) jump menu entry root; 
										if (g1 eq 9) resume;
									 } </button>
EOF
	cat << EOF >> "$thisspuxml"
			<button name="Button_$btn" />
EOF

return 0
}

#
#	Write the navigation buttons
#
xml_navi()
{
	if [ $MKSUBS -eq 1 ]; then
		cat << EOF >> "$XMLFILE"
				<button name="subs_Off"> 
					{ if (subtitle ge 64) subtitle=subtitle-64; 
					  if (g1 eq 0) jump vmgm menu entry title;
					  if (g1 eq 1) jump menu entry root; 
					  if (g1 eq 9) resume;
					} </button>
EOF
		cat << EOF >> "$thisspuxml"
			<button name="subs_Off" />
EOF
	fi
	
	cat << EOF >> "$XMLFILE"
				<button name="nav_Return"> 
					{ if (g1 eq 0) jump vmgm menu entry title; 
 					  if (g1 eq 1) jump menu entry root; 
					  if (g1 eq 9) resume; } 
				</button>
				<button name="nav_VMGM"> { jump vmgm menu entry title; } </button>
				<button name="nav_VTSM"> { jump menu entry root; } </button>
EOF
	cat << EOF >> "$thisspuxml"
			<button name="nav_Return" />
			<button name="nav_VMGM" up="nav_Return" />
			<button name="nav_VTSM" up="nav_Return" />
EOF
	if [ $audio -eq 1 -a $MKAUDIO -eq 0 ]; then
		cat << EOF >> "$XMLFILE"
				<button name="nav_Audio"> { jump menu entry audio; } </button>
EOF
		cat << EOF >> "$thisspuxml"
			<button name="nav_Audio" up="nav_Return" />
EOF
	fi
	if [ $subtitle -eq 1 -a $MKSUBS -eq 0 ]; then
		cat << EOF >> "$XMLFILE"
				<button name="nav_Subs"> { jump menu entry subtitle; } </button>
EOF
		cat << EOF >> "$thisspuxml"
			<button name="nav_Subs" up="nav_Return" />
EOF
	fi
	if [ $info -eq 1 ]; then
		cat << EOF >> "$XMLFILE"
				<button name="nav_Info"> { jump menu entry ptt; } </button>
EOF
		cat << EOF >> "$thisspuxml"
			<button name="nav_Info" up="nav_Return" />
EOF
	fi

return 0
}

#
#	End pgc definition
#
xml_end_pgc()
{
cat << EOF >> "$XMLFILE"
			</pgc>
EOF
cat << EOF >> "$thisspuxml"
		</spu>
	</stream>
</subpictures>
EOF

return 0
}

case "$1" in
	start)
		xml_start
	;;
	buttons)
		shift
		xml_buttons $1
	;;
	navigation)
		shift
		xml_navi
	;;
	end_pgc)
		xml_end_pgc
	;;
	*)
		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

#
# Ok, first define some default values
#
set_defaults "$@"
VTSMDIR="./vtsm"
vts=1
VTSMBG=""
langList=""
info=0
audio=0
subtitle=0
MKAUDIO=0
MKSUBS=0

#
# Check for needed tools
#
check_tools

#
# Now deal with command line arguments
# First argument may only be --audio, --subtitle or -h|--help
#
case "$1" in
	--audio)
		MKAUDIO=1
	;;
	--subtitle)
		MKSUBS=1
	;;
  	*)
   	    echo "First Parm is neither --audio nor --subtitle. $1 is invalid. Aborting" >&2
        echo "See $thisscript -h for more infos" >&2
        exit 1
  	;;
esac
shift

while [ "$langList" == "" -a "$*" != "" ]; do
    case "$1" in
  	-C|--config-file)
    	shift
# -C and it's following parm already processed in set_defaults()
        shift
  	;;
	-o|--output)
 		shift
		VTSMDIR="$1"
	    shift
  	;;
  	-x|--xml)
	    shift
   	    XMLFILE="$1"
   	    shift
  	;;
  	-t|--vts)
	    shift
   	    vts="$1"
   	    shift
	;;
  	-b|--vtsmbg)
	    shift
   	    VTSMBG="$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"
	        	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" >&2
			usge
		fi
   	    shift
  	;;
	-ms|--vtsmsound)
	    shift
		vtsmsound="$1"
   		shift
	;;
  	--hasinfo)
  	    info="1"
   	    shift
  	;;
  	--hasaudio)
  	    audio="1"
   	    shift
  	;;
  	--hassubtitle)
  	    subtitle="1"
   	    shift
  	;;
  	*)
   		langList="$1"
   		shift
  	;;
    esac
done

#
# Do we have extra arguments, not yet processed?
#
if [ "$*" != "" ]; then
	echo "Ignoring extraenous arguments $*" >&2
fi

#
# Set format parameters for PAL or NTSC
#
init_proc
set_format

#
# Let's see, if all options are correct
# Check output-directories and files
#
mk_check_dir "$VTSMDIR" "OLD" "\$VTSMDIR -o|--output"
mk_check_file "$XMLFILE" "NEW" "\$XMLFILE -x|--xml"
[ ! -z "$VTSMBG" ] && mk_check_file "$VTSMBG" "OLD" "\$VTSMBG -b|--vtsmbg"
[ ! -z "$vtsmsound" ] && mk_check_file "$vtsmsound" "OLD" "\$vtsmsound -ms|--vtsmsound"
[ -z "$vtsmsound" -a ! -z "$MENUSOUND" ] && mk_check_file "$MENUSOUND" "OLD" "\$MENUSOUND"

#
# Language-List supplied?
#
if [ -z "$langList" ]; then
 	echo "No language list specified"
    echo "See $thisscript -h for more infos"
    exit 1
fi >&2

#
# No more than 8 tracks?
#
#[ $MKAUDIO -eq 1 ] && maxtrk=8 || maxtrk=32   enlarge max subtitles to 32 later!
maxtrk=8
numlangs=$(echo $langList | tr ',' ' ' | wc -w)
if [ $numlangs -gt $maxtrk ]; then
	echo "Only up to $maxtrk different tracks supported. Sorry"
    echo "See $thisscript -h for more infos"
    exit 1
fi >&2

#
# Validate and store languages and formats
#
lind=0
for i in $(echo $langList | tr ',' ' '); do
	langkz=$(echo $i | cut -d'+' -f1 | tr [a-z] [A-Z] )
	if [ "$(echo $i | tr '+' ' ' | wc -w)" -ne 1 ]; then
		trackfmt=$(echo $i | cut -d'+' -f2 | tr [a-z] [A-Z] )
	else
		trackfmt=""
	fi
	eval language[lind]=\${$langkz}
	if [ -z ${language[lind]} ]; then
		echo "Language $langkz not defined in config file!" >&2
		language[lind]=$langkz
	fi 
	disfmt=""
	case "$trackfmt" in
		"")
			[ $MKAUDIO -eq 1 ] && format[lind]="MP2" || format[lind]=""
		;;
		MP2|AC3|DTS)
			if [ $MKAUDIO -eq 1 ]; then
				format[lind]=$trackfmt
				[ "$trackfmt" != "MP2" ] && disfmt="($trackfmt)"
			else
				echo "Invalid format $trackfmt specified. Aborting"
		        echo "See $thisscript -h for more infos"
        		exit 1
			fi >&2
		;;
		HI)
			if [ $MKSUBS -eq 1 ]; then
				format[lind]=$trackfmt
				disfmt="($txt_SUBHI)"
			else
				echo "Invalid format $trackfmt specified. Aborting"
				echo "See $thisscript -h for more infos"
		        exit 1
			fi >&2
		;;
		*)
			echo "Invalid format $trackfmt specified. Aborting" >&2
	        echo "See $thisscript -h for more infos" >&2
    	    exit 1
		;;
	esac
	let "tnum=lind+1"
	btnText[lind]="$tnum. ${language[lind]} $disfmt"
	let "lind+=1"
done
let hitrack="tnum-1"
	
#
# Prepare the background picture
# ($VTSMBG will be converted to $workbg)
#
prepare_bg $vts "$VTSMBG"
[ $MKAUDIO -eq 1 ] && create_overlay "AUDIO" || create_overlay "SUBS"
create_common_objects
cp "$emptympg" "$VTSMDIR/$(basename "$emptympg")"
EMPTYMPG="$VTSMDIR/$(basename "$emptympg")"
mk_picts

#
# Panel for Intra-Menu-Navigation and Thumbnail-Collections
#
init_proc
thistgt="$txt_DVD $txt_CHAPTER"
[ $audio -eq 1 -o $MKAUDIO -eq 1 ] && thistgt="$thistgt $txt_AUDIO"
[ $subtitle -eq 1 -o $MKSUBS -eq 1 ] && thistgt="$thistgt $txt_SUBS"
[ $info -eq 1 ] && thistgt="$thistgt $txt_INFO"
mk_nav_buttons $thistgt
mk_nav_panel $thistgt
mk_track_panel
#
# Write out xml headers
#
echo -n "Creating menu page..."
[ $MKAUDIO -eq 1 ] && modeid="audio" || modeid="subtitle"
thisspuxml="$VTSMDIR/vts_${vts}_${modeid}_spu.xml"
thisMask=( "dummy" "$VTSMDIR/vts_${modeid}_hi.png" "$VTSMDIR/vts_${modeid}_sel.png" )
thisppm="$VTSMDIR"/vts_${vts}_${modeid}_bg.ppm
thismpg="$VTSMDIR"/vts_${vts}_${modeid}.mpg
write_xml start

for trk in $(seq 0 $hitrack); do
	write_xml buttons $trk
	echo -n "."
done

write_xml navigation
write_xml end_pgc
	
# create background picture with nav panel and audio selection buttons
convert "$TMPDIR/common_objects/menubg_$vts".png \
		"$logoPic" -gravity center -composite \
		"$TMPDIR/navPnl_0.png" -gravity south -geometry +0+${offsetTVY} -composite \
		"$TMPDIR/trkpnl_0.png" -gravity northwest \
		-geometry +$(( $offsetTVX+10 ))+$(( $offsetTVY+10 )) -composite \
		-depth 8 -density $normDensity -units PixelsPerInch "$thisppm" || error_out
		
# create button masks
maskPic="$(mktemp -t png.XXXXXXXXXX)"
convert +antialias -size $normSize xc:transparent \
		"$TMPDIR/navPnl_1.png" -gravity south -geometry +0+${offsetTVY} -composite \
		"$TMPDIR/trkpnl_1.png" -gravity northwest \
		-geometry +$(( $offsetTVX+10 ))+$(( $offsetTVY+10 )) -composite \
		-density $normDensity -units PixelsPerInch png:"$maskPic" || error_out
convert "$maskPic" -depth 8 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

echo ".done"

#
# 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!
#
[ ! "$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
#
audiotrack="$vtsmsound"
[ -z $audiotrack ] && audiotrack="$MENUSOUND"
[ -z $audiotrack ] && audiotrack="$silence"
fext="${audiotrack##*.}"

if [ "$fext" != "ac3" ]; then
	audiotrack_ac3="$TMPDIR/common_objects/vts_$vts.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


#
# Write out menu count
#
let "prevmenus+=1"
echo $prevmenus > "$TMPDIR/common_objects/.menucount"

#
# Finished
#
echo "Creation of Language Selection menu finished."
echo ""	

# Cleanup temporary directory if script was called directly
#
cleanup_tmpdir

exit 0	
