#!/usr/bin/env bash
#
#   mk_vtsm 
#     - Create one or more titleset menus (VTSM) 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
#   2009-06-23  Joo Martin
#               * add aspect ratio option for menu background image (-r)
#   2009-09-11  Joo Martin
#               * optimize bc computing of chapter thumbnail buttons
#   2010-06-21  Markus Kohm
#               * renamed dvdwizardrc into dvdwizard_common
#               * moved some functions to dvdwizard_common
#               * usage of gettext features for multilanguage ui
#                 -several `echo' replaced by `printf'
#   2010-09-29  Joo Martin
#               * relaced `-ab 224kb' by `-ab 224000' at ffmpeg calls
#   2011-01-04  Joo Martin
#               * added setting of VIDEO_FORMAT at spumux call
#   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] image-file(s)
	${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/vtsm]
-x  | --xml		Print dvdauthor XML-specs into this file
			[\$BASEDIR/dvdwizard.xml]
-h  | --help		print this lot out
-v  | --version         print version information only

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:
---------------------
-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]
-R  | --menuratio	Menue background aspect ratio <4:3|16:9>  [4:3]
-M  | --menu		Language to use in menu items;    [en]
			strings are defined in config file.


Title-specific options:
-----------------------
-t  | --vts		Titleset on the DVD where the menus should belong to.
			[1]
-c  | --chaptersperrow	Define how many chapter thumbnails will fit in 
			a row.   [3]
-b  | --vtsmbg		Filename of background picture for this titleset.
-r  | --bgratio		Define aspect ratio of menu background and 
			thumbnails. <4:3|16:9>  [4:3]
-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.
--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.
"

# ------------------------------------------
# Initialize constants troughout the whole script
#
init_proc()
{
    for i in DVD CHAPTER AUDIO SUBS INFO RETURN; do
	eval txt_$i=\"\$TXT_VTSM_${i}_${MENU}\"
    done
    
    actMenu="$txt_CHAPTER"	
    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 Chapter Thumbnails
#
mk_thumbs()
{
    echo -n $"Creating Chapter thumbnail buttons..."
    #
    # Calculation of thumbnail sizes and how many thumbs will fit on one page
    # THUMBRATIO has to be 4:3 for 16:9 movies too 
    # (if menu background are 16:9)!
    #
    THUMBRATIOX=`echo $THUMBRATIO | cut -d: -f 1`
    THUMBRATIOY=`echo $THUMBRATIO | cut -d: -f 2`
    let patchX="(TVWidth-70)/CHAPTERSPERROW"
    let thumbX="patchX-THUMBBORDER*2-THUMBSPACE*2"
    thumbY=$( echo "scale=3; $thumbX * $THUMBRATIOY/$THUMBRATIOX + 0.5" | bc | cut -d'.' -f1)
    #
    # Try to make the patch (thumb incl. borders) same aspect ratio as thumb
    # If vertical spacing around border is less than specfied, reduce thumb 
    # dimensions, keeping patch height unchanged.
    #
    patchY=$( echo "scale=3; $patchX * $THUMBRATIOY/$THUMBRATIOX + 0.5" \
	| bc | cut -d'.' -f1)
    let gapY="(patchY-thumbY-THUMBBORDER*2)/2"
    if [ $gapY -lt $THUMBSPACE ]; then
	let thumbY="patchY-THUMBBORDER*2-THUMBSPACE*2"
	thumbX=$( echo "scale=3; $thumbY * $THUMBRATIOX/$THUMBRATIOY + 0.5" \
	    | bc | cut -d'.' -f1)
	let patchX="thumbX+THUMBBORDER*2+THUMBSPACE*2"
    fi
    thumbsize="$thumbX"x"$thumbY"
    patchsize="$patchX"x"$patchY"
    let cpc="(TVHeight-navpnlh+THUMBSPACE)/patchY"
    let cpm="CHAPTERSPERROW*cpc"
    tiles="$CHAPTERSPERROW"x"$cpc"
    let thumbsPerPage="CHAPTERSPERROW*cpc"
    let thumbpnlW="patchX*CHAPTERSPERROW"
    let thumbpnlH="patchY*cpc"
    thumbOutline="$(mktemp -t png.XXXXXXXXXX)"
    convert +antialias -size $thumbsize xc:black \
	-bordercolor ${hiColor[1]} -border $THUMBBORDER \
	-bordercolor black -border $THUMBSPACE \
	-transparent black png:"$thumbOutline" || error_out
    #
    # Create Thumbnails in separate directory
    #
    thumbDir="$TMPDIR/thumbs"
    [ -e "$thumbDir" -a -d "$thumbDir" ] && rm -R "$thumbDir"
    mkdir -p "$thumbDir" || error_out
    thumbPat="$thumbDir/cpic_%02d.png"
    convert "$@" \
	-trim +repage -scale $thumbsize! -matte \
	-bordercolor ${hiColor[0]} -border $THUMBBORDER \
	-bordercolor transparent -border $THUMBSPACE \
	-scene 1 png:"$thumbPat" || error_out
    #
    # Annotate Chapter number onto thumbnail
    #
    cnum=1
    for thumb in "$thumbDir/"*.png; do
	convert "$thumb" \
	    \( -size $(identify -format %wx%h "$thumb") xc:none \
	       -gravity southeast -matte $HFONT -pointsize $HFONTSIZE \
	       -fill black \
	       -annotate +$(( $THUMBBORDER+$THUMBSPACE+4 ))+$(( $THUMBBORDER+$THUMBSPACE+4 )) "$cnum" \
	       -fill white -annotate +$(( $THUMBBORDER+$THUMBSPACE+6 ))+$(( $THUMBBORDER+$THUMBSPACE+6 )) "$cnum" \
	       -fill gray -annotate +$(( $THUMBBORDER+$THUMBSPACE+5 ))+$(( $THUMBBORDER+$THUMBSPACE+5 )) "$cnum" \
	       -transparent gray \) \
	    -gravity center -composite png:"$thumb" || error_out
	tOl_List_mask[$cnum]="$thumbOutline"
	let "cnum+=1"
    done
    let numChapters="cnum-1"
    #
    # Montage the thumbnail panel(s)
    #
    rm -R "$TMPDIR/"thumbs_0_*.png 2>/dev/null
    tpPat="$TMPDIR/thumbs_0_%d.png"
    montage -size ${thumbpnlW}x${thumbpnlH} -background transparent \
	-geometry +0+0 -tile $tiles "$thumbDir"/*.png \
	png:"$tpPat" || error_out
    numPages=$(ls -1 "$TMPDIR/"thumbs_0_*.png | wc -l)
    tpPat="$TMPDIR/thumbs_1_%d.png"
    montage -size ${thumbpnlW}x${thumbpnlH} -background transparent \
	-geometry +0+0 -tile $tiles "${tOl_List_mask[@]}" \
	png:"$tpPat" || error_out
    
    echo $"done."
    printf $"Will need %d chapter selection menu page(s).\n" $numPages
    let prevmenus="numPages+1"
    echo $prevmenus > "$TMPDIR/common_objects/.menucount"
    return 0
}

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

    #
    # Start a new xml definition
    #
    xml_start()
    {
	let g6="100+$numPages"
	cat << EOF >> "$XMLFILE"
			<pgc entry="root" pause="0">
				<pre> {
						if (g1 lt 9) g1=1; 
						g4=101; g6=$g6;
						if (g7 lt g4) g7=g4;
						if (g7 gt g6) g7=g6;
EOF

	for i in $(seq 1 $numPages); do
	    let regi="$i+100"
	    let nexti="$i+1"
	    cat << EOF >> "$XMLFILE"
						if (g7 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="rows" force="yes"
			 autooutline="infer" outlinewidth="2">
EOF

	let button="$retbtn*1024"
	cat << EOF >> "$XMLFILE"
			<pgc pause="0">
				<pre> { button=$button; } </pre>
				<vob file="$thismpg" pause="inf" />
EOF

	return 0
    }

    #
    #	Write the Chapter buttons
    #
    xml_buttons()
    {
	for btn in $(seq $1 $2); do
	    cat << EOF >> "$XMLFILE"
				<button name="Chapter_$btn"> { jump title 1 chapter $btn; } </button>
EOF
	    let rembtn="$2-$btn+1"
	    [ $rembtn -le $CHAPTERSPERROW ] && down='down="nav_Return"' || down=""
	    cat << EOF >> "$thisspuxml"
			<button name="Chapter_$btn" $down />
EOF
	done

	return 0
    }

    #
    #	Write the navigation buttons
    #
    xml_navi()
    {
	if [ $page -ne 1 ]; then
	    left="left=\"act_Prev\""
	    cat << EOF >> "$XMLFILE"
				<button name="nav_Prev"> { g7=g7-1; jump menu entry root; } </button>
EOF
	    cat << EOF >> "$thisspuxml"
			<button name="nav_Prev" />
EOF
	fi
	[ $page -ne $numPages ] && right="right=\"act_Next\""
	cat << EOF >> "$XMLFILE"
				<button name="nav_Return"> 
					{ if (g1 ne 9) jump vmgm menu entry title; 
					  if (g1 eq 9) resume; } 
				</button>
EOF
	cat << EOF >> "$thisspuxml"
			<button name="nav_Return" $left $right />
EOF
	if [ $page -ne $numPages ]; then
	    cat << EOF >> "$XMLFILE"
				<button name="nav_Next"> { g7=g7+1; jump menu entry root; } </button>
EOF
	    cat << EOF >> "$thisspuxml"
			<button name="nav_Next" />
EOF
	fi
	cat << EOF >> "$XMLFILE"
				<button name="nav_VMGM"> { jump vmgm menu entry title; } </button>
EOF
	cat << EOF >> "$thisspuxml"
			<button name="nav_VMGM" up="nav_Return" />
EOF
	if [ $audio -eq 1 ]; 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 ]; 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
	if [ $page -ne 1 ]; then
	    cat << EOF >> "$XMLFILE"
				<button name="act_Prev"> { g7=g7-1; jump menu entry root; } </button>
EOF
	    cat << EOF >> "$thisspuxml"
			<button name="act_Prev" />
EOF
	fi
	if [ $page -ne $numPages ]; then
	    cat << EOF >> "$XMLFILE"
				<button name="act_Next"> { g7=g7+1; jump menu entry root; } </button>
EOF
	    cat << EOF >> "$thisspuxml"
			<button name="act_Next" />
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
	    ;;
	begin_pgc)
	    shift
	    xml_begin_pgc $1
	    ;;
	buttons)
	    shift
	    xml_buttons $1 $2
	    ;;
	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="$BASEDIR/vtsm"
vts=1
VTSMBG=""
fList=""
info=0
audio=0
subtitle=0

#
# Check for needed tools
#
check_tools

#
# Now deal with command line arguments
#
while [ "$fList" == "" -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|--thumbaspectratio)
            # --thumbaspectratio only for transition
  	    shift
  	    THUMBRATIO="$1"
  	    BGRATIO="$1"
  	    shift
  	    ;;
  	-c|--chaptersperrow)
   	    shift
   	    CHAPTERSPERROW="$1"
   	    shift
  	    ;;
  	*)
   	    fList="$@"
  	    ;;
    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 "$VTSMDIR" "NEW" "\$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"

#
# Chapter-Pictures supplied and existing?
#
if [ -z "$fList" ]; then
    error_help $"No input files specified"
fi

for i in "$@"; do
    mk_check_file "$i" "OLD" "Picture file #$i from command line"
done

#
# Prepare the background picture
# ($VTSMBG will be converted to $workbg)
#
prepare_bg $vts "$VTSMBG"
create_overlay "VTSM"
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 ] && thistgt="$thistgt $txt_AUDIO"
[ $subtitle -eq 1 ] && thistgt="$thistgt $txt_SUBS"
[ $info -eq 1 ] && thistgt="$thistgt $txt_INFO"
mk_nav_buttons $thistgt
mk_nav_panel $thistgt
mk_thumbs "$@"

#
# Write out xml headers
#
write_xml start

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

#
# Now loop through all pages
#
for page in $(seq 1 $numPages); do
    printf $"Creating menu page #%d" $page
    let p="$page-1"
    thisppm="$VTSMDIR"/vts_${vts}_${page}_bg.ppm
    thisspuxml="$VTSMDIR/vts_${vts}_${page}_spu.xml"
    thisMask=( "dummy" "$VTSMDIR/vts_${page}_hi.png" "$VTSMDIR/vts_${page}_sel.png" )
    thismpg="$VTSMDIR"/vts_${vts}_${page}.mpg
    let lastChapter="$cpm*$page"
    [ $lastChapter -gt $numChapters ] && lastChapter=$numChapters
    let firstChapter="$cpm*($page-1)+1"
    let numButtons="$lastChapter-$firstChapter+1"
    let retbtn="$numButtons+1"
    [ $page -ne 1 ] && let "retbtn+=1"
    # write begin of pgc and chapter buttons
    write_xml begin_pgc $page
    write_xml buttons $firstChapter $lastChapter
    echo -n "."
	
    # create previous button, if not first page
    for state in 0 1; do
	if [ $page -ne 1 ]; then 
	    convert "$TMPDIR/navPnl_${state}.png" \
		\( "$TMPDIR/common_objects/pictPrev_${state}.png" \) \
		-geometry +15+15 -gravity NorthWest \
		-composite png:"${thispnl[state]}" || error_out
	else
	    cp "$TMPDIR/navPnl_${state}.png" "${thispnl[state]}"
	fi
    done

    # create next button, if not last page
    for state in 0 1; do
	if [ $page -ne $numPages ]; then 
	    convert "${thispnl[state]}" \
		\( "$TMPDIR/common_objects/pictNext_${state}.png" \) \
		-geometry +15+15 -gravity NorthEast \
		-composite png:"${thispnl[state]}" || error_out
	fi
    done

    # write navigation buttons to xml
    write_xml navigation
    write_xml end_pgc
    echo -n "."
	
    # create background picture with nav panel and chapter thumbnails
    convert "$TMPDIR/common_objects/menubg_$vts".png \
	"$logoPic" -gravity center -composite \
	"${thispnl[0]}" -gravity south -geometry +0+${offsetTVY} -composite \
	"$TMPDIR/thumbs_0_$p.png" -gravity northwest \
	-geometry +${offsetTVX}+${offsetTVY} \
	-composite -depth 8 -density $normDensity \
	-units PixelsPerInch "$thisppm" || error_out
			
    # create button masks
    convert +antialias -size $normSize xc:transparent \
	"${thispnl[1]}" -gravity south -geometry +0+${offsetTVY} -composite \
	"$TMPDIR/thumbs_1_$p.png" -gravity northwest \
	-geometry +${offsetTVX}+${offsetTVY} \
	-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 "."

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

done

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

#
# Finished
#
echo $"Creation of Chapter selection menu pages finished."
echo	

# Cleanup temporary directory if script was called directly
#
cleanup_tmpdir

exit 0	
