#!/bin/bash
#
#   mk_vtsm_lang 
#     - Create language selection menus for audio and video tracks in
#       current VTSM
#
#   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:
#
#   2006-08-31  Wolfgang Wershofen
#               * initial version
#   2009-06-23  Joo Martin
#               * add aspect ratio option for menu background image (-r)
#   2010-06-21  Markus Kohm
#               * audio for visually impaired
#               * renamed dvdwizardrc into dvdwizard_common
#               * moved some functions to dvdwizard_common
#               * usage of gettext features for multilanguage ui
#                 -several `echo' replaced by `printf'
#   2010-08-03  Markus Kohm
#               * audio tracks may be mono or stereo
#   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
#               * fixed: background for the buttons
#   2012-03-18  Joo Martin
#               * fixed: error while using subtitle with -s option
#               * 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} --audio [options] track_list
        ${thisscript} --subtitle [options] track_list
        ${thisscript} -h|--help
	${thisscript} -v|--version

supported options:
------------------
-C  | --config-file	filename of dvdwizard-configuration file
			[~/.config/dvdwizard/dvdwizard.conf]
-o  | --output		Path where the created menu mpegs will be stored 
			[\$BASEDIR/vtsm]
-x  | --xml		Print dvdauthor XML-specs into this file
			[\$BASEDIR/dvdwizard.xml]
-b  | --vtsmbg		Image to use as background for menu options.
-r  | --bgratio		Define aspect ratio of menu background   [4:3]
-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. 
			[660x530]
-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.
-h  | --help		print this lot out
-v  | --version         print version information only
--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

track_list:
	one entry for each audio or subtitle track, comma separated
	for audio:	<lang>+<fmt>[+vi][+m|s][,<lang>+<fmt>...]
			<lang>=2-Letter language code
			<fmt>=Audio format (MP2, AC3, DTS)
			vi=Audio track for vizually impaired, will be noted
			   on the menu as such
                        m=Audio track will be noted as mono on the menu
                        s=Audio track will be noted as stereo on the menu
		e.g. de+ac3,en+mp2,en+mp2+m
	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
"

# ------------------------------------------
# Initialize constants throughout the whole script
#
init_proc()
{
    for i in DVD CHAPTER INFO RETURN \
	AUDIO AUDIOH AUDIOVI AUDIOMONO AUDIOSTEREO \
	SUBS 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 -scene 0 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 -scene 0 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?
#
test_versionhelp "$@"

#
# 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
	;;
    *)
   	error_help $"First Parm is neither --audio nor --subtitle.\n\`%s' is invalid." "$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
	        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
  	    ;;
	-ms|--vtsmsound)
	    shift
	    vtsmsound="$1"
   	    shift
	    ;;
  	--hasinfo)
  	    info="1"
   	    shift
  	    ;;
  	--hasaudio)
  	    audio="1"
   	    shift
  	    ;;
  	--hassubtitle)
  	    subtitle="1"
   	    shift
  	    ;;
  	-r|--bgratio)
  	    shift
  	    BGRATIO="$1"
  	    shift
  	    ;;
  	*)
   	    langList="$1"
   	    shift
  	    ;;
    esac
done

#
# Do we have extra arguments, not yet processed?
#
if [ "$*" != "" ]; then
    print_warn "Ignoring extraenous arguments \`%s'" "$*" >&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
    error_help $"No language list specified"
fi

#
# No more than 8 tracks?
#
# TODO: [ $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
    error_help "Only up to %d different tracks supported. Sorry." $maxtrk
fi

#
# Validate and store languages and formats
#
lind=0
for i in $(echo "${langList}" | tr ',' ' '); do
    split_formatstring "${i}"
    [ $MKAUDIO -eq 1 -a -z "S{str_format}" ] && str_format="MP2"
    
    eval language[lind]=\${$str_language}
    if [ -z "${language[lind]}" ]; then
	print_warn $"Language \`%s' not defined in config file!" "${str_language}"
	language[lind]=${str_language}
    fi

    case ${str_format} in
	"")
	    if [ ${MKSUBS} -eq 1 ]; then
		format[lind]=${str_format}
	        [ $flag_special -ge 1 ] && disfmt=" ($txt_SUBHI)"
	    else
		error_help $"Invalid format \`%s' specified." "${str_format}"
	    fi
	    ;;
	MP2|AC3|DTS)
	    if [ ${MKAUDIO} -eq 1 ]; then
		format[lind]=${str_format}
		disfmt="${str_format}"
		case ${n_channels} in
		    1) disfmt="${disfmt} ${txt_AUDIOMONO}" 
			;;
		    2) disfmt="${disfmt} ${txt_AUDIOSTEREO}"
			;;
		esac
		[ $flag_special -ge 1 ] && disfmt="${disfmt} ${txt_AUDIOVI}"
		if [ "${disfmt}" == "MP2" ]; then
		    disfmt=""
		else
		    disfmt=" (${disfmt})"
		fi

	    else
		error_help $"Invalid format \`%s' specified." "${str_format}"
	    fi
	    ;;
	*)
	    error_help $"Invalid format \`%s' specified." "${str_format}"
	    ;;
    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
    # 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

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!
#
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 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
#
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

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