#!/bin/sh
# Version: 0.2.0
# Author: Dimitrios Dimitrakos mail@dimitrios.de
# $Id: vdr2dvd.sh,v 1.61 2005/10/07 17:12:39 dimi Exp $
#
# initial code taken over from 'dvdcreate.sh' Version 20030511 (P) & (C)
# 2003 by Dr. Peter Bieringer <pb at bieringer dot de>"

## Major work
# 20041023/PB: do_titelmenu speed-optimized

LANG=C

vco_user=`id -n -u`
homedir=`cat /etc/passwd|grep "^${vco_user}:"|cut -f6 -d ':'`
. $homedir/.vdrconvert/vdrconvert.env
[ -r $homedir/.vdrconvert/vdr2dvd.env ] && . $homedir/.vdrconvert/vdr2dvd.env

PIDFILE="$VCORUNDIR/`basename ${0}.pid`"
echo "$$" >> $PIDFILE

[ "$DVD_DEBUG" != "yes" ] && DVD_DEBUG="$DEBUG_VDR2DVD"
[ "$VERBOSE" != "yes" ] && VERBOSE="$VERBOSE_VDR2DVD"

if [ -z "$RM" ]
then
	RM="rm"
	#RM="echo"
fi

trap do_clean SIGINT SIGQUIT SIGTERM 
do_clean() {
	if [ -f $PIDFILE ]
	then
	    TEMPPID=$LTEMPDIR/`basename $PIDFILE`.$$
	    mv $PIDFILE $TEMPPID
	    status=$?
	    if [ $status -eq 0 ]
	    then
	        [ `cat $TEMPPID|wc -l` -gt 0 ] && cat $TEMPPID|grep -v $$ > $PIDFILE 
	    fi
	    [ -f $TEMPPID ] && $RM $TEMPPID
	fi
	[ -d $LTEMPDIR ] && $RM -rf $LTEMPDIR
	printf "`date +"%d-%m-%2Y %T"` : Session %s Exit\n" "$0"
	exit
}

ExitError() {
	echo "ERROR : exit on error: $1" >&2
	exit 1
}

Exit() {
	echo "NOTICE : exit!" >&2
	[ -x $VDRCONVERTBINDIR/post${JOBFIL}.sh ] && $VDRCONVERTBINDIR/post${JOBFIL}.sh $2 $3
	do_clean
}

ExitClean()  {
	echo "NOTICE : exit on clean!" >&2
	# Cleaning
	cd $VDRCONVERTDIR
	$RM -rf ${UniqueDir[Number]} ${UniqueDVDDIR}
	Exit
}

NewJobs=$1
JOBFIL=$2
LOGFILE=$3

if [ "$VERBOSE" = "yes" ]
then
	echo "vdr2dvd called: NewJobs=$NewJobs JOBFIL=$JOBFIL LOGFILE=$LOGFILE"

	# Set stdout and stderr
	STDOUT="/dev/stdout"
	STDERR="/dev/stderr"
else
	STDOUT="/dev/null"
	STDERR="/dev/stderr"
fi

# Check for writing
if [ ! -w $STDOUT ]
then
	echo "WARN  : can't write to $STDOUT, use /dev/null for STDOUT instead" >&2
	STDOUT="/dev/null"
fi
if [ ! -w $STDERR ]
then
	echo "WARN  : can't write to $STDERR, use /dev/null for STDERR instead" >&2
	STDERR="/dev/null"
fi

[ "$DVD_DEBUG" = "yes" ] && set -x 

printf "`date +"%d-%m-%2Y %T"` : Session begin ($Id: vdr2dvd.sh,v 1.61 2005/10/07 17:12:39 dimi Exp $)\n" 


# Default values
[ -z "$DVD_DESTDIR" ]  && DVD_DESTDIR=$DESTDIR/dvd

# set mplex tool.
# (migration from USE_ to MULTIPLEXER)
if [ -z "$MULTIPLEXER" ]; then
	MULTIPLEXER="tcmplex_panteltje"	# Default
	if [ "$USE_DVBMPLEX" = "yes" ]
	then
		MULTIPLEXER="dvb_mplex"
	elif [ "$USE_TCMPLEX_PANTELTJE" = "yes" ]
	then
		MULTIPLEXER="tcmplex_panteltje"
	elif [ "$USE_MPLEX" = "yes" ]
	then
		MULTIPLEXER="mplex"
	fi
fi

# Options for tcmplex/mplex/dvb-mplex
[ -z "$DVDTCMPLEXOPTS" ]       && DVDTCMPLEXOPTS="-m d"
[ -z "$DVD_MPLEXOPTS" ]        && DVD_MPLEXOPTS="-f 8 -V -S 0"
[ -z "$DVD_DVBMPLEXOPTS" ]     && DVD_DVBMPLEXOPTS="-t DVD"
[ -z "$RETRANSCODE" ]          && export RETRANSCODE="no"
# No transcode for this values
[ -z "$DVDALLOWEDWIDTH" ]     && DVDALLOWEDWIDTH="720 704 352 480"
[ -z "$DVDFORCERECODE" ]      && DVDFORCERECODE="no"
# more options
[ -z "$DVDNORM" ]              && DVDNORM="_dvdnorm_"
[ "$DVDNORM" = "_dvdnorm_" ]   && DVDNORM="pal"
[ "$DVDNORM" = "pal" ]         && TCORES="720x576" || TCORES="720x480"
#
#[ -z "$DVDTRANSCODEOPTS" ]     && DVDTRANSCODEOPTS="-I 3 -y ffmpeg,mp2enc -F mpeg2video -Z $TCORES -b 192" || \
#[ -z "$DVDTRANSCODEOPTS" ]     && DVDTRANSCODEOPTS="-I 3 -y mpeg2enc,null -Z 576 -b 192"
#[ -z "$DVDTRANSCODEOPTS" ]     && DVDTRANSCODEOPTS="-I 3 -y ffmpeg,mp2enc -F mpeg2video -Z 720x576 -b 192"
#
[ -z "$DVDTRANSCODEOPTS" ]     && DVDTRANSCODEOPTS="-I 3 -y mpeg2enc,null -Z $TCORES -b 192"
[ -z "$DVDTRANSCODEBITRATE" ]  && DVDTRANSCODEBITRATE="3300000.0"
[ -z "$DVDAUTHORMODE" ]        && DVDAUTHORMODE=15min
[ -z "$DVDMKISOFSOPTS" ]       && DVDMKISOFSOPTS="-V VDRCONVERT_`date +"%d-%m-%Y"`"
[ -z "$DVDSIZE" ]              && DVDSIZE=4472
[ -z "$CDSIZE" ]               && CDSIZE=650
[ -z "$DVD_OVERHEAD" ]         && DVD_OVERHEAD=180000
[ -z "$DVD_TITLEDATE" ]        && DVD_TITLEDATE=$CONV_TITLEDATE
[ -z "$REQUANT" ]              && REQUANT=tcrequant
[ -z "$DVD_AUTOWRITE" ]        && DVD_AUTOWRITE=no
[ -z "$DVDDELBURNEDIMAGE" ]    && DVDDELBURNEDIMAGE="yes"
[ -z "$DVD_CREATEISO" ]        && DVD_CREATEISO=yes
[ -z "$DVD_MPLAYERPPM" ]       && DVD_MPLAYERPPM=no
[ -z "$DVD_MPLAYERPPMFRAMES" ] && DVD_MPLAYERPPMFRAMES=0

[ -z "$DVDAUTHORUSERCHAP" ]    && DVDAUTHORUSERCHAP=$DVDAUTHORCHAPTERS
[ -z "$DVDUSESTREAMS" ]        && DVDUSESTREAMS="dpid1:ac3+de apid1:mp2+de apid2:mp2+en apid3:mp2+en apid4:mp2+en apid5:mp2+en apid6:mp2+en apid7:mp2+en apid8:mp2+en apid9:mp2+en"
[ -z "$DVDUSESUBS" ]           && DVDUSESUBS="de en"
[ -z "$DVDSAVEAUTHORDIR" ]     && DVDSAVEAUTHORDIR="no"
[ -z "$DVDSAVEAUTHORSRC" ]     && DVDSAVEAUTHORSRC="no"
[ -z "$DVDMAINBACKFILE_USE" ]  && DVDMAINBACKFILE_USE="yes"
[ -z "$DVDSUBBACKFILE_USE" ]   && DVDSUBBACKFILE_USE="yes"
[ -z "$DVDMAINBACKFILE" ]      && DVDMAINBACKFILE="$VDRCONVERTDIR/share/vdrconvert/images/$DVDNORM/Main.pnm"
[ -z "$DVDSUBBACKFILE" ]       && DVDSUBBACKFILE="$VDRCONVERTDIR/share/vdrconvert/images/$DVDNORM/Sub.pnm"
[ -z "$DVDMAINSILENCEFILE" ]	&& DVDMAINSILENCEFILE="$VDRCONVERTDIR/share/vdrconvert/images/silence-30s.mp2"
[ -z "$DVDSUBSILENCEFILE" ]	&& DVDSUBSILENCEFILE="$DVDMAINSILENCEFILE"
# Text
case $VDRCONVERT_LANG in
	de|DE)
		[ -z "$DVDTEXTPLAYMOVIE" -o "$DVDTEXTPLAYMOVIE" = "" ]     && DVDTEXTPLAYMOVIE="Film abspielen"
		[ -z "$DVDTEXTMENU" -o "$DVDTEXTMENU" = "" ]               && DVDTEXTMENU="Titelmenü"
		[ -z "$DVDMENU_MENU_MAIN" -o "$DVDMENU_MENU_MAIN" = "" ]   && DVDMENU_MENU_MAIN="Titelmenü"
		[ -z "$DVD_PAGETEXT" -o "$DVD_PAGETEXT" = "" ]             && DVD_PAGETEXT="Seite"
		[ -z "$DVD_MINUTESTEXT" -o "$DVD_MINUTESTEXT" = "" ]       && DVD_MINUTESTEXT="min"
		;;
	*)
		[ -z "$DVDTEXTPLAYMOVIE" -o "$DVDTEXTPLAYMOVIE" = "" ]     && DVDTEXTPLAYMOVIE="Play Movie"
		[ -z "$DVDTEXTMENU" -o "$DVDTEXTMENU" = "" ]               && DVDTEXTMENU="Menu Title"
		[ -z "$DVDMENU_MENU_MAIN" -o "$DVDMENU_MENU_MAIN" = "" ]   && DVDMENU_MENU_MAIN="Menu Title"
		[ -z "$DVD_PAGETEXT" -o "$DVD_PAGETEXT" = "" ]             && DVD_PAGETEXT="Page"
		[ -z "$DVD_MINUTESTEXT" -o "$DVD_MINUTESTEXT" = "" ]       && DVD_MINUTESTEXT="Min"
		;;
esac
# Farbe Rahmen select Button
[ -z "$DVDBUTTONCOLOR" ]       && DVDBUTTONCOLOR="#C0C0C0"
# Farbe nach Auswahl Button
[ -z "$DVDHIBUTTONCOLOR" ]     && DVDHIBUTTONCOLOR="#ff0000"
# Farbe nach Auswahl Button
[ -z "$DVDSELBUTTONCOLOR" ]    && DVDSELBUTTONCOLOR="#fff030"
# Hintergrundfarbe 
[ -z "$DVDFILE_MAINBACKGROUND_COLOR" ] && DVDFILE_MAINBACKGROUND_COLOR="#6666AA"
[ -z "$DVDFILE_SUBBACKGROUND_COLOR" ]  && DVDFILE_SUBBACKGROUND_COLOR="#00AAAA"

####### C O L O R S #########################################################
[ -z "$DVDMAINCOLFG" ]         && DVDMAINCOLFG="#FFFF00FF"
[ -z "$DVDCOLBG" ]             && DVDCOLBG="#00000000"
[ -z "$DVDSUBCOLFG" ]          && DVDSUBCOLFG="#C0C0C0FF"
[ -z "$DVDMAINVERCOLFG" ]      && DVDMAINVERCOLFG="#C0C0C0FF"
[ -z "$DVDMAINSUBTITLECOLFG" ] && DVDMAINSUBTITLECOLFG="#C0C0C0FF"
[ -z "$DVDMAINTITLECOLFG" ]    && DVDMAINTITLECOLFG="#C0C0C0FF"
[ -z "$DVDMAINPAGETEXTCOLFG" ] && DVDMAINPAGETEXTCOLFG="#C0C0C0FF"
[ -z "$DVDBUTTONTEXTCOLFG" ]   && DVDBUTTONTEXTCOLFG="#C0C0C0FF"
[ -z "$DVDMAINNUMTITLECOLFG" ] && DVDMAINNUMTITLECOLFG="#C0C0C0FF"
[ -z "$DVD_USE_COLOR_SCHEMA" ] && DVD_USE_COLOR_SCHEMA="YELLOW_WHITE"

case $DVD_USE_COLOR_SCHEMA in 
	GRAY)
		DVDMAINCOLFG="#FFFFFFFF"
		DVDCOLBG="#00000000"
		DVDSUBCOLFG="#FFFFFFFF"
		DVDMAINVERCOLFG="#F2F2F2FF"
		DVDMAINSUBTITLECOLFG="#999999FF"
		DVDMAINTITLECOLFG="#C4C4C4FF"
		DVDMAINPAGETEXTCOLFG="#F9F9F9FF"
		DVDBUTTONTEXTCOLFG="#FAFAFAFF"
		DVDMAINNUMTITLECOLFG="#FAFAFAFF"
		DVDBUTTONCOLOR="#C0C0C0"
		DVDHIBUTTONCOLOR="#C0C0C0"
		DVDSELBUTTONCOLOR="#FFFFE0"
		;;
	BLUE)
		DVDMAINCOLFG="#FFFFFFFF"
		DVDCOLBG="#00000000"
		DVDSUBCOLFG="#FFFFFFFF"
		DVDMAINVERCOLFG="#E0FFFFFF"
		DVDMAINSUBTITLECOLFG="#00688BFF"
		DVDMAINTITLECOLFG="#009ACDFF"
		DVDMAINPAGETEXTCOLFG="#C6E2FFFF"
		DVDBUTTONTEXTCOLFG="#BFEFFFFF"
		DVDMAINNUMTITLECOLFG="#BFEFFFFF"
		DVDBUTTONCOLOR="#00008B"
		DVDHIBUTTONCOLOR="#00008B"
		DVDSELBUTTONCOLOR="#4F94CD"
		;;
	GREEN)
		DVDMAINCOLFG="#FFFFFFFF"
		DVDCOLBG="#00000000"
		DVDSUBCOLFG="#FFFFFFFF"
		DVDMAINVERCOLFG="#R98FB98F"
		DVDMAINSUBTITLECOLFG="#006400FF"
		DVDMAINTITLECOLFG="#8FBC8FFF"
		DVDMAINPAGETEXTCOLFG="#00FF7fFF"
		DVDBUTTONTEXTCOLFG="#ADFF2FFF"
		DVDMAINNUMTITLECOLFG="#ADFF2FFF"
		DVDBUTTONCOLOR="#008B00"
		DVDHIBUTTONCOLOR="#008B00"
		DVDSELBUTTONCOLOR="#C0FE3E"
		;;
	RED)
		DVDMAINCOLFG="#FFFFFFFF"
		DVDCOLBG="#00000000"
		DVDSUBCOLFG="#FFFFFFFF"
		DVDMAINVERCOLFG="#FFF6347F"
		DVDMAINSUBTITLECOLFG="#FF0000FF"
		DVDMAINTITLECOLFG="#FF4500FF"
		DVDMAINPAGETEXTCOLFG="#FF7F50FF"
		DVDBUTTONTEXTCOLFG="#FFA500FF"
		DVDMAINNUMTITLECOLFG="#FFA500FF"
		DVDBUTTONCOLOR="#EE0000"
		DVDHIBUTTONCOLOR="#EE0000"
		DVDSELBUTTONCOLOR="#FF0000"
		;;
	YELLOW)
		DVDMAINCOLFG="#FFFFFFFF"
		DVDCOLBG="#00000000"
		DVDSUBCOLFG="#FFFFFFFF"
		DVDMAINVERCOLFG="#FFFFE0FF"
		DVDMAINSUBTITLECOLFG="#FFFF00FF"
		DVDMAINTITLECOLFG="#EEEE00FF"
		DVDMAINPAGETEXTCOLFG="#CDAD00FF"
		DVDBUTTONTEXTCOLFG="#FFB90FFF"
		DVDMAINNUMTITLECOLFG="#FFB90FFF"
		DVDBUTTONCOLOR="#FFD700"
		DVDHIBUTTONCOLOR="#FFD700"
		DVDSELBUTTONCOLOR="#fff000"
		;;
	YELLOW_WHITE)
		DVDMAINCOLFG="#FFFFFFFF"
		DVDCOLBG="#00000000"
		DVDSUBCOLFG="#FFFFFFFF"
		DVDMAINVERCOLFG="#090909FF"
		DVDMAINSUBTITLECOLFG="#FFFFFFFF"
		DVDMAINTITLECOLFG="#E2E2E2FF"
		DVDMAINPAGETEXTCOLFG="#CDAD00FF"
		DVDBUTTONTEXTCOLFG="#FFB90FFF"
		DVDMAINNUMTITLECOLFG="#FFB9AFFF"
		DVDBUTTONCOLOR="#FFD700"
		DVDHIBUTTONCOLOR="#FFD700"
		DVDSELBUTTONCOLOR="#fff000"
		;;
	*)
		;;
esac


# Fonts
[ -z "$DVD_USE_FONT" ]         && export DVD_USE_FONT="arial"
[ -z "$PATH_FONTS" ]           && export PATH_FONTS="$VDRCONVERTDIR/share/vdrconvert/fonts/truetype"

if [ ! -z "$PATH_FONTS" -a ! -z "$DVD_USE_FONT" ]
then
  case $DVD_USE_FONT in

  luximb)
    [ -z "$font_title" ]             && export font_title="luximb/18"
    [ -z "$font_menu" ]              && export font_menu="luximb/16"
    [ -z "$font_info" ]              && export font_info="luximb/14"
    [ -z "$font_big_additional" ]    && export font_big_additional="luximb/14"
    [ -z "$font_additional" ]        && export font_additional="luximb/12"
    [ -z "$font_medium_additional" ] && export font_medium_additional="luximb/10"
    [ -z "$font_tiny_additional" ]   && export font_tiny_additional="luximb/9"
    [ -z "$font_version" ]           && export font_version="luximb/12"
    ;;
  arial)
    [ -z "$font_title" ]             && font_title="arial/18"
    [ -z "$font_menu" ]              && font_menu="arial/16"
    [ -z "$font_info" ]              && font_info="arial/14"
    [ -z "$font_big_additional" ]    && font_big_additional="arial/14"
    [ -z "$font_additional" ]        && font_additional="arial/12"
    [ -z "$font_medium_additional" ] && font_medium_additional="arial/10"
    [ -z "$font_tiny_additional" ]   && font_tiny_additional="arial/9"
    [ -z "$font_version" ]           && font_version="arial/10"
    ;;
  *)
	echo "Unknown Font. Abort"
	Exit
  esac
fi

generatedvd_version="vdrconvert-0.2.0 cvs"

[ -z "$DVDLABELMODE" ]              && DVDLABELMODE="--create-dvd-outside"
[ -z "$DVDLABELOPTIONS" ]           && DVDLABELOPTIONS="$DVDLABELMODE"
[ -z "$DVDLABELDATEFORMAT" ]        && DVDLABELDATEFORMAT="DVD-`date +"%d-%m-%Y"`"
[ -z "$DVDLABELTEMPLATE" ]          && DVDLABELTEMPLATE="$VDRCONVERTDIR/share/vdrconvert/postscript/penguin.eps"
[ -z "$DVDSUBCATECORY" ]            && DVDSUBCATECORY="$generatedvd_version"
[ -z "$DVDLABELPRINTER" ]           && DVDLABELPRINTER=""
[ -z "$DVDDELETELABEL" ]            && DVDDELETELABEL="yes"
[ -z "$DVDCDLABELCONV" ]            && DVDCDLABELCONV=""

[ -z "$DVDDISABLEMENU" ]            && DVDDISABLEMENU="no"
[ -z "$DVDDISABLESUBMENU" ]         && DVDDISABLESUBMENU="no"
[ -z "$DVDXMLNORM" ]                && DVDXMLNORM="$DVDNORM"
[ -z "$DVDXMLASPECT" ]              && DVDXMLASPECT="4:3"
[ -z "$DVDXMLAUDIO" ]               && DVDXMLAUDIO="mp2"
[ -z "$DVDXMLCHANNELS" ]            && DVDXMLCHANNELS="2"
[ -z "$DVDXMLSAMPLERATE" ]          && DVDXMLSAMPLERATE="48khz"
[ -z "$XML_VERSION" ]               && XML_VERSION="1.0"
[ -z "$XML_ENCODING" ]              && XML_ENCODING="ISO-8859-1"
[ -z "$DVD_EPGCHARSPERLINE" ]       && DVD_EPGCHARSPERLINE=60
[ "$DVDNORM" = "pal" -a -z "$DVD_EPGLINESPERPAGE" ]       && DVD_EPGLINESPERPAGE=12
[ "$DVDNORM" = "ntsc" -a -z "$DVD_EPGLINESPERPAGE" ]       && DVD_EPGLINESPERPAGE=10
[ -z "$DVD_CHAPTERPERLINE" ]        && DVD_CHAPTERPERLINE=2
[ -z "$DVD_CHAPTERLINES" ]          && DVD_CHAPTERLINES=3
[ -z "$CHAPTER_PER_PAGE" ]          && CHAPTER_PER_PAGE=$[ $DVD_CHAPTERPERLINE * $DVD_CHAPTERLINES ]

[ -z "$DVD_USEVIDEOBACKGROUND" ]    && DVD_USEVIDEOBACKGROUND="yes"
[ -z "$DVD_USESUBVIDEOBACKGROUND" ] && DVD_USESUBVIDEOBACKGROUND="yes"

# By default start on after 1 second (avoid strange pictures at beginning)
[ -z "$DVD_TIMEFRAME" ]             && DVD_TIMEFRAME="00:00:01-00:00:07"
[ -z "$DVD_TIMESUBFRAME" ]          && DVD_TIMESUBFRAME="$DVD_TIMEFRAME"
[ -z "$DVD_TIMEMAINBACKFRAME" ]     && DVD_TIMEMAINBACKFRAME="$DVD_TIMEFRAME"
[ -z "$DVD_TIMESUBBACKFRAME" ]      && DVD_TIMESUBBACKFRAME="$DVD_TIMEMAINBACKFRAME"

#[ -z "$DVDANIMFRAMES" ]             && DVDANIMFRAMES=150
#[ -z "$DVDANIMSUBFRAMES" ]          && DVDANIMSUBFRAMES=$DVDANIMFRAMES
#[ -z "$DVDANIMCHAPTERFRAMES" ]      && DVDANIMCHAPTERFRAMES=$DVDANIMFRAMES
[ -z "$DVD_DISABLEANIM" ]            && DVD_DISABLEANIM="no"

[ -z "$DVD_ZAPVIDEOBACKGROUND" ]    && DVD_ZAPVIDEOBACKGROUND="yes"

[ -z "$DVDMENUSCHEMA" ]             && DVDMENUSCHEMA=duester
[ -z "$DVDBUTTONDIR" ]              && DVDBUTTONDIR=$VDRCONVERTDIR/share/vdrconvert/images/buttons/$DVDMENUSCHEMA
[ -z "$DVDMENUEPAUSE" ]             && DVDMENUEPAUSE=2
[ -z "$DVDSUBMENUPAUSE" ]           && DVDSUBMENUPAUSE=2
[ -z "$DVDTITELPAUSE" ]             && DVDTITELPAUSE=2
[ -z "$DVD_PUTNUMBERTOTITLE" ]      && DVD_PUTNUMBERTOTITLE="no"
[ -z "$DVD_USENUMBERFORTITLES" ]    && DVD_USENUMBERFORTITLES="yes"
[ -z "$DVD_PUTNUMBERTOBUTTONS" ]    && DVD_PUTNUMBERTOBUTTONS="no"
[ -z "$DVD_ANIMATEVERSION" ]        && DVD_ANIMATEVERSION="no"
[ -z "$DVD_ANIMATELOGO" ]           && DVD_ANIMATELOGO="no"
[ -z "$DVD_ANIMATELOGO_FILE" ]      && DVD_ANIMATELOGO_FILE="$VDRCONVERTDIR/share/vdrconvert/images/logos/logosml.256.pnm"
[ -z "$DVD_DISPLAY_PAGETEXT" ]      && DVD_DISPLAY_PAGETEXT="no"
[ -z "$DVD_DISPLAY_SUBTITLE" ]      && DVD_DISPLAY_SUBTITLE="no"
[ -z "$DVD_INIT" ]                  && DVD_INIT="menu"
[ -z "$DVD_POST" ]                  && DVD_POST="menu"

if [ -z "$SHORTCIRCUIT_PID" ]; then
	LTEMPDIR=${TEMPDIR}/${JOBFIL}/$$
else
	LTEMPDIR=${TEMPDIR}/${JOBFIL}/$SHORTCIRCUIT_PID
fi

[ -d $LTEMPDIR ] || mkdir -p $LTEMPDIR || ExitError "Can't create directory: $LTEMPDIR"

## Set global variables depending on DVDNORM
case $DVDNORM in
    'pal')
	# Screen size
	DVDNORM_XRES=720
	DVDNORM_YRES=576
	# ppmtoy4m
	DVDNORM_PPMTOY4M="-F 25:1 -A 59:54"
	;;
    'ntsc')
	# Screen size
	DVDNORM_XRES=720
	DVDNORM_YRES=480
	# ppmtoy4m
	DVDNORM_PPMTOY4M="-F 30000:1001 -A 10:11"
	;;
    *)
	echo "ERROR : unsupported DVDNORM: $DVDNORM"
	Exit
	;;
esac

## Set global variables depending on static configurations
# get size of logo
if [ "$DVD_ANIMATELOGO" = "yes" -a -r "$DVD_ANIMATELOGO_FILE" ]
then
	LOGO_XSIZE=`pnmfile $DVD_ANIMATELOGO_FILE|awk '{print $4}'`
	LOGO_YSIZE=`pnmfile $DVD_ANIMATELOGO_FILE|awk '{print $6}'`
else
	LOGO_XSIZE=0
	LOGO_YSIZE=0
fi

# File names for version (animation)
version_main_png="${LTEMPDIR}/VMGMTEMP/version_sub.png"
version_main_pnm="${LTEMPDIR}/VMGMTEMP/version_sub.pnm"
version_main_alpha_pnm="${LTEMPDIR}/VMGMTEMP/version_sub.alpha.pnm"

version_sub_png="${LTEMPDIR}/VMGMTEMP/version_sub.png"
version_sub_pnm="${LTEMPDIR}/VMGMTEMP/version_sub.pnm"
version_sub_alpha_pnm="${LTEMPDIR}/VMGMTEMP/version_sub.alpha.pnm"

# Need Chroma Subsampling Mode ?
[ $(ppmtoy4m -h|grep 420mpeg2|wc -l ) -gt 0 ] && CHROMASUB="-S 420mpeg2" || CHROMASUB=""

do_init() {
      [ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_init"
      printf "\t`date +"%T"` : Start conversion for List : \n"
      let part=0
      for i in $CMDLIN
      do
      	      let part=part+1
	      printf "\t\t %5d) %s\n" $part "$i"

		if [ -n "$SHORTCIRCUIT_PID" ]; then
			# Skip test in shortcircuit mode
			continue
		fi
	      if [ ! -d $i ]
	      then
		printf "File <%s> not exist. Abort conversion\n" "$i"
		Exit
	      fi
      done
      let Number=1
      UniqueDVDDIR=${LTEMPDIR}/DVDSTRUCT 
      if [ ! -d $UniqueDVDDIR ]
      then
        mkdir -p $UniqueDVDDIR
        status=$?
        if [ $status -ne 0 ]
        then
	  echo "ERROR : unable to create $UniqueDVDDIR"
	  logger "$0 : ERROR : unable to create $UniqueDVDDIR"
          Exit
        fi
      fi
      UniqueMENUDIR=${LTEMPDIR}/DVDMENU
      mkdir -p $UniqueMENUDIR
      status=$?
      if [ $status -ne 0 ]
      then
	  echo "ERROR : unable to create $UniqueMENUDIR"
	  logger "$0 : ERROR : unable to create $UniqueMENUDIR"
          Exit
      fi

      UniqueTempDIR=${LTEMPDIR}/VMGMTEMP
      mkdir -p $UniqueTempDIR
      status=$?
      if [ $status -ne 0 ]
      then
	echo "ERROR : unable to create UniqueTempDIR"
        Exit
      fi

      let part=0
      for i in $CMDLIN
      do
      	let part=part+1
	Record[part]=""
        SourceDir[part]=$i
        r=`echo $VDRROOT|sed 's/\// /g'|wc -w`
        spalten=`echo $i|sed 's/\// /g'|wc -w`
        Record[part]=`echo $i|sed 's/\%//g'|cut -f $spalten -d '/'|sed 's/_/ /g'`
	[ $[$r+2] -lt $[$spalten-1] ] && SubTitel[part]=`echo ${i}|sed 's/\%//g'|cut -f $[$r+2]-$[$spalten-1] -d '/'|sed 's/_/ /g'`
	SubTitel[part]=`echo $i|sed 's/\%//g'|cut -f $[$spalten-1] -d '/'|sed 's/_/ /g'`
	[ "/${SubTitel[part]}" = "$VDRROOT" ] && SubTitel[part]=""
	while [ "`echo ${Record[part]}|cut -c1`" = "@" ]
	do 
		Record[part]=`echo ${Record[part]}|sed 's/^@//'`
        done
	while [ "`echo ${Record[part]}|cut -c1`" = "%" ]
	do 
		Record[part]=`echo ${Record[part]}|sed 's/^%//'`
        done
        BaseRecord[part]=`echo $i|cut -f $spalten -d '/'`
	BaseSubTitel[part]=`echo $i|cut -f $[$spalten-1] -d '/'`
	[ "/${BaseSubTitel[part]}" = "$VDRROOT" ] && BaseSubTitel[part]=""
	if [ -z "${BaseSubTitel[part]}" ]
	then
		BaseDir=${BaseRecord[part]}
	else
		BaseDir=${BaseSubTitel[part]}/${BaseRecord[part]}
	fi
	mkdir -p ${LTEMPDIR}/${BaseDir}
        status=$?
        if [ $status -ne 0 ]
        then
	  echo "ERROR : unable to create Temp $BaseDir"
	  logger "$0 : ERROR : unable to create Temp $BaseDir"
          Exit
        fi

        if [ -z "${SHORTCIRCUIT_TOKEN_UniqueDir[part]}" ]; then
                UniqueDir[part]=`mktemp -d ${LTEMPDIR}/${BaseDir}/VDRSYNC.XXXXXX`

		local status=$?
		if [ $status -ne 0 ]
		then
			echo "ERROR : (mktemp) unable to create ${UniqueDir[part]} for part $part"
			logger "$0 : ERROR : (mktemp) unable to create ${UniqueDir[part]} for part $part"
			$RM -rf ${UniqueDVDDIR}
			Exit
		fi

		# Fix permissions
		chmod g+rx ${UniqueDir[part]}

		# Append mktemp token to shortcircuit file (last 6 chars)
		local token=${UniqueDir[part]:$[ ${#UniqueDir[part]} - 6 ]:6}
		echo "SHORTCIRCUIT_TOKEN_UniqueDir[$part]=$token" >>$LTEMPDIR/SHORTCIRCUIT.txt
        else
                UniqueDir[part]="${LTEMPDIR}/${BaseDir}/VDRSYNC.${SHORTCIRCUIT_TOKEN_UniqueDir[part]}"

		if [ ! -d ${UniqueDir[part]} ]
		then
			echo "ERROR : shortcircuit problem, directory doesn't exist: ${UniqueDir[part]}"
			exit 1
		fi	
        fi

	if [ "$VERBOSE" = "yes" ]; then
		[ ! -z "${SubTitel[part]}" ] && printf "\t\t\tSubtitle set to: %s\n" "${SubTitel[part]}"
		[ ! -z "${Record[part]}" ] && printf "\t\t\tTitle set to: %s\n" "${Record[part]}"
	fi
      done

	if [ "$DVD_ANIMATEVERSION" = "yes" ]
	then
		# Prepare version picture
		text_to_pnm $version_main_pnm $version_main_alpha_pnm $font_version $DVDMAINVERCOLFG $DVDCOLBG "$generatedvd_version"
		text_to_pnm $version_sub_pnm  $version_sub_alpha_pnm  $font_version $DVDMAINCOLFG    $DVDCOLBG "$generatedvd_version"
	fi

      DVDMENU_ENTRY_MIN="1"
      DVDMENU_ENTRY_MAX="`echo $CMDLIN|wc -w|awk '{print $1}'`"
	if [ $DVDMENU_ENTRY_MAX -lt $DVDMENU_ENTRY_MIN ]; then
		echo "FATAL : major problem in calculation of DVDMENU_ENTRY_MAX"
		Exit
	fi
      menu_images_in_col=3
      DVDMENU_PAGE_MAX=$[ $[ $DVDMENU_ENTRY_MAX - 1 ] / menu_images_in_col + 1 ]

      mainbuttons=""

      first=${Record[1]}
}

do_dvdauthor() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_dvdauthor"

	# Cleanup DVD directory (prevents appending on shortcircuit mode)
	if [ -d $UniqueDVDDIR ]
	then
		nice -n $PRIO rm -rf $UniqueDVDDIR/*
	fi

	# Run dvdauthor
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && cat ${UniqueMENUDIR}/dvd.xml
	nice -n $PRIO $DVDAUTHOR -x ${UniqueMENUDIR}/dvd.xml
	local status=$?

	if [ "$DVDSAVEAUTHORSRC" != "yes" ]
	then
		$RM -rf ${UniqueMENUDIR}
	else
		if [ -z "${SubTitel[1]}" ]
		then
			Imagesrc=$(echo "$DVD_DESTDIR/${first}"|sed 's/:/_/g'|sed 's/ /_/g')
		else
			ImageDir=$(echo "${SubTitel[1]}"|sed 's/:/_/g'|sed 's/ /_/g')
			[ -d "$DVD_DESTDIR/${ImageDir}" ] || mkdir -p "$DVD_DESTDIR/${ImageDir}"
			ImageName=$(echo "${first}"|sed 's/:/_/g'|sed 's/ /_/g')
			Imagesrc=$DVD_DESTDIR/${ImageDir}/${ImageName}
		fi
    
		if [ ! -d $Imagesrc ]
		then
			mkdir -p $Imagesrc || ExitError "Can't create directory: $Imagesrc"
		fi
		if [ -d $Imagesrc ]
		then
			[ -d $Imagesrc/AUTHORSRC ] && nice -n $PRIO rm -rf $Imagesrc/AUTHORSRC
			nice -n $PRIO mv ${UniqueMENUDIR} $Imagesrc/AUTHORSRC
		fi
	fi
	if [ $status -ne 0 ]
	then
		echo "ERROR : Fehler bei dvdauthor -x. rc=<$status>"
		Exit
	fi
}

do_mkisofs() {
      [ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_mkisofs"
      if [ "$DVD_CREATEISO" != "no" ]
      then
          cd $LTEMPDIR
          LOG=${LTEMPDIR}/mkisofs.$$
 
          if [ -z "${SubTitel[1]}" ]
          then
                Image=$(echo "$DVD_DESTDIR/${first}"|sed 's/:/_/g'|sed 's/ /_/g')
          else
                ImageDir=$(echo "${SubTitel[1]}"|sed 's/:/_/g'|sed 's/ /_/g')
		[ -d "$DVD_DESTDIR/${ImageDir}" ] || mkdir -p "$DVD_DESTDIR/${ImageDir}"
                ImageName=$(echo "${first}"|sed 's/:/_/g'|sed 's/ /_/g')
	        Image=$DVD_DESTDIR/${ImageDir}/${ImageName}
          fi
    
          if [ -f "${Image}.iso" ]
	  then
                let index=1
                until [ ! -f "${Image}-${index}.iso" ]
                do
                      let index=index+1
                done
                Image=${Image}-${index}
          fi
    
          printf "\t`date +"%T"` : Start $MKISOFS\n"
          nice -n ${PRIO} $MKISOFS $DVDMKISOFSOPTS -dvd-video -o "${Image}.iso" ${UniqueDVDDIR} > $LOG 2>&1 || ExitError "mkisofs"
          status=$?
	[ "$VERBOSE" = "yes" ] && echo "Created ISO image file: ${Image}.iso"
          [ "$DVD_DEBUG" = "yes" ] && cat $LOG >> $LOGFILE
          let imagelen=`cat ${LOG}|grep "extents written"|tail -n 1|cut -f2 -d'('|awk '{print $1}'`
	  [ -f $LOG ] && $RM $LOG
          # Cleaning
          if [ $status -eq 0 ]
          then
	    local autoburn=0
            if [ $imagelen -gt $DVDSIZE ]
	    then
	        printf "\t\tWarn : The Image size <%d> ist bigger than %d MB\n. Autoburn disabled" $imagelen $DVDSIZE
	        logger "$0 : Warn : The Image ist bigger than $DVDSIZE MB. Autoburn disabled"
		autoburn=1
	    fi  

            # Add to queue
	    if [ "$DVD_AUTOWRITE" = "yes" -a $autoburn -eq 0 ]
            then
	        if [ "$MINIDVD" = "yes" ]
	        then
	                  # 
	                  #  FILE:TYPE:POSTACTION
	                  #
			  [ "$DVDDELBURNEDIMAGE" = "yes" ]  && DELFLAG="DEL" || DELFLAG="NODEL"
	        	  printf "`date +"%T"`\t : Add Entry for Autoburn\n\t\t%s" "${Image}.iso:MINIDVD:${DELFLAG}"
	                  echo "${Image}.iso:MINIDVD:${DELFLAG}" >> $VCOQUEUEDIR/burn
	        else
			  [ "$DVDDELBURNEDIMAGE" = "yes" ]  && DELFLAG="DEL" || DELFLAG="NODEL"
	        	  printf "\t\t : Add Entry for Autoburn %s" "${Image}.iso:DVD:${DELFLAG}"
	                  echo "${Image}.iso:DVD:${DELFLAG}" >> $VCOQUEUEDIR/burn
	        fi
	    fi
          else
              echo "ERROR : $MKISOFS report error. rcode(${status})."
              logger "$0 : ERROR : $MKISOFS report error. rcode(${status})."
          fi
      fi
      if [ "$DVDSAVEAUTHORDIR" != "yes" ]
      then
	 $RM -rf ${UniqueDVDDIR}
      else
          if [ -z "${SubTitel[1]}" ]
          then
                ImageAuth=$(echo "$DVD_DESTDIR/${first}"|sed 's/:/_/g'|sed 's/ /_/g')
          else
                ImageDir=$(echo "${SubTitel[1]}"|sed 's/:/_/g'|sed 's/ /_/g')
		[ -d "$DVD_DESTDIR/${ImageDir}" ] || mkdir -p "$DVD_DESTDIR/${ImageDir}"
                ImageName=$(echo "${first}"|sed 's/:/_/g'|sed 's/ /_/g')
	        ImageAuth=$DVD_DESTDIR/${ImageDir}/${ImageName}
          fi
    
	  if [ ! -d $ImageAuth ]
	  then
		 mkdir -p $ImageAuth|| ExitError "Can't create directory: $ImageAuth"
	  fi
	  if [ -d $ImageAuth ]
	  then
	  	[ -d $ImageAuth/Author ] && nice -n $PRIO rm -rf $ImageAuth/Author
		nice -n $PRIO mv ${UniqueDVDDIR} $ImageAuth/Author
	  fi
      fi
      let Number=1
      until [ $Number -gt $DVDMENU_ENTRY_MAX ]
      do
	  $RM -rf ${UniqueDir[Number]}
	  let Number=Number+1
      done
}

do_checkshrink() {
      [ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_checkshrink"
      SHRINK_PRG=`which $REQUANT`
      if [ "$DVD_SHRINK" != "no" -a -x $SHRINK_PRG ]
      then
          let Number=1
	  let ThisDVDVideoSize=0
	  let ThisDVDAudioSize=0
	  [ "$MINIDVD" = "yes" ] && DVDSIZE=$CDSIZE
          until [ $Number -gt $DVDMENU_ENTRY_MAX ]
          do
	      let ThisDVDVideoSize=ThisDVDVideoSize+`ls -Ll ${UniqueDir[Number]}/*.mpv |awk '{print $5}'|xargs $VDRCONVERTDIR/bin/add.sh`
	      for k in ${NEWSTREAMS[Number]}
	      do
	         j=`echo $k|cut -f 1 -d ':'|cut -f1 -d'.'`
	         jj=`echo $k|cut -f 1 -d ':'|cut -f2 -d'.'`
	         [ -f ${UniqueDir[Number]}/$j.$jj ] && \
			let ThisDVDAudioSize=ThisDVDAudioSize+`ls -Ll ${UniqueDir[Number]}/$j.$jj |awk '{print $5}'|xargs $VDRCONVERTDIR/bin/add.sh`
	      done

	      let Number=Number+1
          done

	  MPLEXAUDIO=""

	  let MenueSize=0
	  if [ "$DVDDISABLEMENU" != "yes" ]
	  then
            let Number=1
            until [ $Number -gt $DVDMENU_PAGE_MAX ]
            do
	
	      let MenueSize=MenueSize+`ls -Ll ${UniqueMENUDIR}/spu-mainmenu-${Number}.mpg |awk '{print $5}'|xargs $VDRCONVERTDIR/bin/add.sh`
	      let Number=Number+1
            done

	    if [ "$DVDDISABLESUBMENU" != "yes" ]
	    then
              let Number=1
              until [ $Number -gt $DVDMENU_ENTRY_MAX ]
              do
	
                let Page=1
                until [ $Page -gt ${epg_pages[Number]} ]
                do
	          let MenueSize=MenueSize+`ls -Ll $UniqueMENUDIR/Titel-${Number}/spu-submenu-${Page}.mpg |awk '{print $5}'|xargs $VDRCONVERTDIR/bin/add.sh`
	          let Page=Page+1
	        done
	        let Number=Number+1
              done
	    fi
	  fi

	  let ThisDVDVideoSize=ThisDVDVideoSize+DVD_OVERHEAD
          if [ $[$ThisDVDVideoSize ] -gt $[$[$DVDSIZE*1024000]-$ThisDVDAudioSize-$MenueSize] ]
          then
            shrinkfaktor=`echo "$ThisDVDVideoSize/(($DVDSIZE*1024000)-$ThisDVDAudioSize-$MenueSize)"|bc -l`
	    tshrink=`echo $shrinkfaktor|cut -f1 -d '.'`

	    if  [ ! -z "$tshrink" ] # Add some overhead
	    then
	      [ "$MINIDVD" = "yes" ] && shrinkfaktor=`echo "$shrinkfaktor+0.03"|bc -l` \
				     || shrinkfaktor=`echo "$shrinkfaktor+0.03"|bc -l`
             let Number=1
             until [ $Number -gt $DVDMENU_ENTRY_MAX ]
             do
	      cd ${UniqueDir[Number]}
	      # Fit to DVD
		    printf "\t`date +"%T"` : %s with %s for %s starting\n" "$REQUANT" "$shrinkfaktor" "`echo ${UniqueDir[Number]}/*.mpv`"
		    syncmv=`echo ${UniqueDir[Number]}/*.mpv`
		    nice -n $PRIO mv $syncmv ${syncmv}.requant

		    case `basename $REQUANT` in
  		        "requant")
		    		nice -n $PRIO $REQUANT $shrinkfaktor < ${syncmv}.requant > $syncmv 2>/dev/null
		    		status=$?
    		        ;;
  		        "tcrequant")
		    		nice -n $PRIO $REQUANT -f $shrinkfaktor < ${syncmv}.requant > $syncmv 2>/dev/null
		    		status=$?
    		        ;;
  		        "M2VRequantiser")
				let len=`$LS -Ls ${syncmv}.requant|awk '{print $1}'`
		    		nice -n $PRIO $REQUANT $shrinkfaktor 1 M2VRequantiser $len < ${syncmv}.requant > $syncmv 2>/dev/null
		    		status=$?
    		        ;;
  		        *)
		    	    echo "ERROR : Unknown requant prg $REQUANT."
		    	    logger "$0 : ERROR : Unknown requant prg $REQUANT."
    		        ;;
		    esac

		    if [ $status -eq 0 ] 
		    then
			$RM ${syncmv}.requant
		    else
		        printf "\tERROR : Requant finish. Status for %s. rc = <%d>\n" "${syncmv}" $status
		        logger "$0 : ERROR : Requant finish. Status for ${syncmv}.requant = $status"
			$RM ${syncmv}
			nice -n $PRIO mv ${syncmv}.requant ${syncmv}
		    fi
		    printf "\t`date +"%T"` : Requant finish. Status for %s.rc = <%d>\n" ${syncmv} $status
	            let Number=Number+1
             done
             do_mplex
	    fi
	  fi
      fi
}

do_label() {
    [ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_label"
    # Create Label
    if [ -x "$DVDCDLABELGEN" -a "$DVDCREATELABEL" = "yes" ]
    then	
	cd $LTEMPDIR

	printf "\t`date +"%T"` : Start Create label\n"
	# Label
	 > $LTEMPDIR/items.$$

	local category=""

	local Number=1
	until [ $Number -gt $DVDMENU_ENTRY_MAX ]
	do
		if [ -s ${UniqueDir[Number]}/info.vdr ]
		then
			nice -n $PRIO cat ${UniqueDir[Number]}/info.vdr|grep "^D "|cut -c3- > ${UniqueDir[Number]}/suma_label.txt
		elif [ -s ${UniqueDir[Number]}/summary.vdr ]
		then
			nice -n $PRIO cat ${UniqueDir[Number]}/summary.vdr > ${UniqueDir[Number]}/suma_label.txt
		else
			echo "${SubTitel[Number]} / ${Record[Number]}" > ${UniqueDir[Number]}/suma_label.txt
		fi

		if [ -z "$category" ]
		then
			local category="${SubTitel[Number]}"
		elif [ "$category" != "${SubTitel[Number]}" ]
		then
			# Subtitle not eqal, reset category
			local category="notequal"
		fi


		# Recode file
		#recode_file "${UniqueDir[Number]}/suma_label.txt" || ExitError

		# Calculate length of record (inclusive round up)
		local frames=""
		if [ -f "${UniqueDir[Number]}/FRAMES.txt" ]
		then
			# Precedence 1: take information from demuxer
			local frames=`cat ${UniqueDir[Number]}/FRAMES.txt`
		elif [ -f "${UniqueDir[Number]}/index.vdr" ]
		then
			# Precedence 2: take information from index.vdr
			local size="`stat "${UniqueDir[Number]}/index.vdr" | grep "Size:" | awk '{ print $2 }'`"
			local frames=$[ $size / 8 ]
		fi

		# Generate txt
		printf "%2d ) " $Number >> $LTEMPDIR/items.$$
		#echo "${SubTitel[Number]}" | fold -w 60 -s >> $LTEMPDIR/items.$$
		#echo "" >> $LTEMPDIR/items.$$
		#printf "\n" >> $LTEMPDIR/items.$$
		cat ${UniqueDir[Number]}/suma_label.txt | fold -w 60 -s >>$LTEMPDIR/items.$$



#		if [ -n "$frames" ]
#		then	
#			if [ -f "${UniqueDir[Number]}/FRAMERATE.txt" ]
#			then
#				local framerate=`cat ${UniqueDir[Number]}/FRAMERATE.txt`
#				# Calculate seconds
#				local minutes="`echo "($frames + $framerate - 1) / $framerate / 60" | bc`"
#			else
#				# Default depending on DVDNORM
#				local minutes="`echo "($frames + $DVDNORM_FRAMERATE_DIVIDEND / $DVDNORM_FRAMERATE_DIVISOR - 1) * $DVDNORM_FRAMERATE_DIVISOR / $DVDNORM_FRAMERATE_DIVIDEND / 60" | bc`"
#			fi
#
#			printf "\n$minutes min\n" >> $LTEMPDIR/items.$$
#		fi

		if [ $Number -lt $DVDMENU_ENTRY_MAX ]
		then
			printf "\n" >> $LTEMPDIR/items.$$
			printf "\n" >> $LTEMPDIR/items.$$
		fi

		local Number=$[ $Number + 1 ]
	done

	if [ "$category" = "notequal" ]
	then
		DVDCATEGORY="$DVDNAME"
	else
		DVDCATEGORY="$category"

		# Get subcategory: serial numbers or years
		local Number=1
		until [ $Number -gt $DVDMENU_ENTRY_MAX ]
		do
			local serial="`echo "${Record[Number]}" | sed 's/^\([0-9]\{1,4\}\).*/\1/'`"
			if [ -z "$subcategory" ]
			then
				local subcategory="$serial"
			else
				local subcategory="$subcategory + $serial"
			fi
			local Number=$[ $Number + 1 ]
		done

		DVDSUBCATEGORY="$subcategory"
	fi


	# cd $VDRCONVERTDIR

	DVDLABELTEMPLATE=""
	if [ -f "$UniqueTempDIR/preview/1/background-000000.ppm" -a -x "$DVDCDLABELCONV" -a "$DVDCDLABELGRAPH" = "yes" ]
	then
	        XRES=`pnmfile $UniqueTempDIR/preview/1/background-000000.ppm|awk '{print $4}'`
	        YRES=`pnmfile $UniqueTempDIR/preview/1/background-000000.ppm|awk '{print $6}'`
		local Y=$[ $YRES / 2 ]
	        local X=$[ $Y * 4 / 3 ]
		nice -n $PRIO convert -size ${XRES}x${YRES} $UniqueTempDIR/preview/1/background-000000.ppm -resize ${X}x${Y} $UniqueTempDIR/backgroundlabel.ppm
		nice -n $PRIO pnmtojpeg --quality=100 $UniqueTempDIR/backgroundlabel.ppm > $UniqueTempDIR/background
		
		$DVDCDLABELCONV $UniqueTempDIR/background
		DVDLABELTEMPLATE="$UniqueTempDIR/background.eps"
	fi

	local option_e=""
	[ -n "$DVDLABELTEMPLATE" ] && local option_e="-e $DVDLABELTEMPLATE"

        if [ -z "${SubTitel[1]}" ]
        then
                Image=$(echo "$DVD_DESTDIR/${first}"|sed 's/:/_/g'|sed 's/ /_/g')
        else
                ImageDir=$(echo "${SubTitel[1]}"|sed 's/:/_/g'|sed 's/ /_/g')
		[ -d "$DVD_DESTDIR/${ImageDir}" ] || mkdir -p "$DVD_DESTDIR/${ImageDir}"
                ImageName=$(echo "${first}"|sed 's/:/_/g'|sed 's/ /_/g')
	        Image=$DVD_DESTDIR/${ImageDir}/${ImageName}
        fi
    
        if [ -f "${Image}.iso" ]
	then
                let index=1
                until [ ! -f "${Image}-${index}.iso" ]
                do
                      let index=index+1
                done
                Image=${Image}-${index}
        fi

	if [ -f "${Image}.ps" ]
	then
		nice -n $PRIO rm -f ${Image}.ps
	fi

	if [ "$VERBOSE" = "yes" ]
	then
		echo "-----"
		cat $LTEMPDIR/items.$$
		echo "-----"
	fi

	nice -n $PRIO $DVDCDLABELGEN $DVDLABELOPTIONS -c "$DVDCATEGORY" -s "$DVDSUBCATEGORY" \
		-f $LTEMPDIR/items.$$ -d "$DVDLABELDATEFORMAT" $option_e > ${Image}.ps
	# [ -f $first/background.eps ] && $RM $first/background.eps 
	# [ -f $first/background.jpg ] && $RM $first/background.jpg 
	# [ -f $first/background ] && $RM $first/background 

	#exit 1

	$RM $LTEMPDIR/items.$$
	if [ ! -z "$DVDLABELPRINTER" ]
	then
		cat ${Image}.ps|$DVDLABELPRINTER
		[ "$DVDDELETELABEL" = "yes" ] && $RM ${Image}.ps
	fi
    fi
}


do_demux() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_demux"

	local Number=1
	#XXX : CMDLIN Ersetzen	
	for i in $CMDLIN
	do
        	printf "\n\t`date +"%T"` : Begin conversion %s\n" "$i"

		pushd ${UniqueDir[Number]} >>$STDOUT
		local pxfiles=""
		[ -f $i/marks.vdr ] && cp $i/marks.vdr ${UniqueDir[Number]}
		[ -f $i/summary.vdr ] && cp $i/summary.vdr ${UniqueDir[Number]}
		[ -f $i/info.vdr ] && cp $i/info.vdr ${UniqueDir[Number]}
		[ -f $i/index.vdr ] && cp $i/index.vdr ${UniqueDir[Number]}

 		for file in $i/*.srt
                do
                     [ -f $file ] && cp $file ${UniqueDir[Number]}
                done
 
		demux_prg=$DEMUXER
		#for demux_prg in $DEMUXER
		#do

		local LOG[Number]=${UniqueDir[Number]}/sync.log
		printf "\t`date +"%T"` : Start demux with %s\n" ${demux_prg}

		case $DEMUXER in
		    vdrsync)
			nice -n $PRIO $VDRSYNC -o ${UniqueDir[Number]} $i/ >${LOG[Number]} 2>&1
			local status=$?
			[ "$DVD_DEBUG" = "yes" ] && cat ${LOG[Number]} >>$LOGFILE
			if [ $status -ne 0 ]
			then
				echo "ERROR : $VDRSYNC  rc=$status"
				logger "$0 : ERROR : $VDRSYNC  rc=$status"
				ExitClean
			fi

			# Save aspect ratio
			strings ${LOG[Number]}|grep Aspect|awk '{print $3}' >${UniqueDir[Number]}/ASPECT.txt
			# Save resolution
			local hor=`strings ${LOG[Number]}|grep "Horizontal size"|awk '{print $3}'`
			local ver=`strings ${LOG[Number]}|grep "Vertical size"|awk '{print $3}'`
			printf "%sx%s\n" "$hor" "$ver" >${UniqueDir[Number]}/RESOLUTION.txt
			# Save number of frames
			local vstream=`strings ${LOG[Number]}|grep "video stream"|grep "info:"|awk '{print $3}'` 
			strings ${LOG[Number]}|grep " $vstream " |grep written|awk '{print $1}' >${UniqueDir[Number]}/FRAMES.txt

			echo "${Record[Number]}" >${UniqueDir[Number]}/Titel.txt
		      ;;
		    vdrsync2)
			nice -n $PRIO $VDRSYNC2 -basename 001 -script-output $VDRSYNC_OPTS -o ${UniqueDir[Number]} $i/ >${LOG[Number]} 2>&1
			local status=$?
			[ "$DVD_DEBUG" = "yes" ] && cat ${LOG[Number]} >>$LOGFILE
			if [ $status -ne 0 ]
			then
				echo "ERROR : $VDRSYNC2  rc=$status"
				logger "$0 : ERROR : $VDRSYNC2  rc=$status"
				ExitClean
			fi

			# Save aspect ratio
			strings ${LOG[Number]}|grep Aspect|cut -f2 -d '='|awk '{print $1}' >${UniqueDir[Number]}/ASPECT.txt
			# Save resolution
			local hor=`strings ${LOG[Number]}|grep "Horizontal_size"|cut -f2 -d '='|awk '{print $1}'`
			local ver=`strings ${LOG[Number]}|grep "Vertical_size"|cut -f2 -d '='|awk '{print $1}'`
			printf "%sx%s\n" "$hor" "$ver" >${UniqueDir[Number]}/RESOLUTION.txt
			# Save number of frames
			local vstream=`strings ${LOG[Number]}|grep Video_stream|cut -f1 -d'_'`
			strings ${LOG[Number]}|grep ${vstream}_Total_frames|cut -f2 -d '='|awk '{print $0}' >${UniqueDir[Number]}/FRAMES.txt

			echo "${Record[Number]}" >${UniqueDir[Number]}/Titel.txt
		      ;;
		    vdrsync3)
			nice -n $PRIO $VDRSYNC3 -basename 001 -script-output $VDRSYNC_OPTS -o ${UniqueDir[Number]} $i/ >${LOG[Number]} 2>&1
			local status=$?
			[ "$DVD_DEBUG" = "yes" ] && cat ${LOG[Number]} >>$LOGFILE
			if [ $status -ne 0 ]
			then
				echo "ERROR : $VDRSYNC3  rc=$status"
				logger "$0 : ERROR : $VDRSYNC3  rc=$status"
				ExitClean
			fi

			# Save aspect ratio
			strings ${LOG[Number]}|grep Aspect|cut -f2 -d '='|awk '{print $1}' >${UniqueDir[Number]}/ASPECT.txt
			# Save resolution
			local hor=`strings ${LOG[Number]}|grep "Horizontal_size"|cut -f2 -d '='|awk '{print $1}'`
			local ver=`strings ${LOG[Number]}|grep "Vertical_size"|cut -f2 -d '='|awk '{print $1}'`
			printf "%sx%s\n" "$hor" "$ver" >${UniqueDir[Number]}/RESOLUTION.txt
			# Save number of frames
			local vstream=`strings ${LOG[Number]}|grep Video_stream|cut -f1 -d'_'`
			strings ${LOG[Number]}|grep ${vstream}_Total_frames|cut -f2 -d '='|awk '{print $0}' >${UniqueDir[Number]}/FRAMES.txt

			echo "${Record[Number]}" >${UniqueDir[Number]}/Titel.txt
		      ;;
		    px)
			#XXX: if 001.vdr = 0 bytes Project X fail
			if [ -z "$VDRCONVERT_ONESHOT" -o "$DISPLAY_XVFB" = "yes" ]
			then
				# FIXME: display error if display is not available
				export DISPLAY=:${XVFB_ID}.0
			fi

			local vdrfiles=`$LS $i/[0-9][0-9][0-9].vdr`
			for l in $vdrfiles
			do
				local len=`$LS -Ls $l|awk '{print $1}'`
				[ $len -gt 1 ] && local pxfiles="${pxfiles} ${l}"
			done

			# Check for INI
			if [ ! -r "$PXINI" ];then
				echo "ERROR : can't read: $PXINI"
				logger "$0 : ERROR : can't read: $PXINI"
				ExitError
			fi

			# Project X starten
			if [ "$VERBOSE" = "yes" ]; then
				echo "INFO  : call ProjectX: $JAVA -jar $PX $PXINIOPT $PXINI $PXOUTOPT ${UniqueDir[Number]} $pxfiles"
			fi
			nice -n $PRIO $JAVA -jar $PX $PXINIOPT $PXINI $PXOUTOPT ${UniqueDir[Number]} $pxfiles >${LOG[Number]} 2>&1
			local status=$?

			[ "$DVD_DEBUG" = "yes" ] && cat ${LOG[Number]} >>$LOGFILE
			[ "$VERBOSE" = "yes" ] && cat ${LOG[Number]}

			if [ $status -ne 0 ]
			then
				echo "ERROR : $PX  rc=$status"
				logger "$0 : ERROR : $PX  rc=$status"
				ExitClean
			fi

			# Save aspect ratio
			strings ${LOG[Number]}|grep basics:|awk '{print $9}'|tail -n 1|tr -d "()" >${UniqueDir[Number]}/ASPECT.txt
			# Save resolution
			strings ${LOG[Number]}|grep "video basics"|awk '{print $4}'|tail -n 1|sed 's/*/x/' >${UniqueDir[Number]}/RESOLUTION.txt
			# Save number of frames
			strings ${LOG[Number]}|grep "Video:"|awk  '{print $10}'|cut -f1 -d '/' >${UniqueDir[Number]}/FRAMES.txt

			echo "${Record[Number]}" > ${UniqueDir[Number]}/Titel.txt
			# Umsetzen mpeg spuren
			let z=0
			for i in `cat ${LOG[Number]}|grep "found PES-ID 0xC"|awk '{print $4}'`
			do
			    let z=z+1
			    str=`cat ${LOG[Number]}|tr -d "\r"|grep ^Audio|grep -v "PTS"|grep "(mp2)"|awk '{print $8}'|head -n $z|tail -n 1|xargs basename`
			    strn=`echo $i|cut -f2 -d 'x'|awk '{ print tolower($1)'}`
			    mv ${UniqueDir[Number]}/${str}  ${UniqueDir[Number]}/${strn}.mpa
			done
		      ;;
		    pva)	
			# VDR Files zusammenführen
			nice -n ${PRIO} cat $i/[0-9][0-9][0-9].vdr >>${UniqueDir[Number]}/001.vdr
			# Winpfad erstellen
			local WINEPFAD=`echo ${UniqueDir[Number]}|sed 's/\//\\\/g'`
			local WINEFILE="demux \"Z:${WINEPFAD}\\001.vdr\" \"Z:${WINEPFAD}\\001.mpv\" \"Z:${WINEPFAD}\\001.mpa\""
			## Jobfile anlegen
			echo "offeryn pvas job v000001" > ${UniqueDir[Number]}/demux.ajb
			echo "\$JOB" >> ${UniqueDir[Number]}/demux.ajb
			echo "$WINEFILE" >> ${UniqueDir[Number]}/demux.ajb
			cat $VDRCONVERTDIR/share/vdrconvert/pva/demux.template >> ${UniqueDir[Number]}/demux.ajb
			
			#export DISPLAY=:${XVFB_ID}.0
			if [ -z "$VDRCONVERT_ONESHOT" -o "$DISPLAY_XVFB" = "yes" ]
			then
				# FIXME: display error if display is not available
				export DISPLAY=:${XVFB_ID}.0
			fi

			[ "$DVD_DEBUG" = "yes" ] && cat ${UniqueDir[Number]}/demux.ajb
			nice -n $PRIO $WINE $VDRCONVERTDIR/share/vdrconvert/pva/cPVAS.exe ${UniqueDir[Number]}/demux.ajb > ${LOG[Number]} 2>&1
			local status=$?
			[ "$DVD_DEBUG" = "yes" ] && cat ${LOG[Number]} >> $LOGFILE
			[ -f "${UniqueDir[Number]}/001.mpv.ac3" ] && nice -n $PRIO mv ${UniqueDir[Number]}/001.mpv.ac3 ${UniqueDir[Number]}/001.ac3

			# Save aspect ratio
			strings ${LOG[Number]}|grep Aspect|awk '{print $4}' >${UniqueDir[Number]}/ASPECT.txt
			# Save resolution
			local hor=`strings ${LOG[Number]}|grep Resolution|awk '{print $2}'`
			local ver=`strings ${LOG[Number]}|grep Resolution|awk '{print $4}'`
			printf "%sx%s\n" "$hor" "$ver" >${UniqueDir[Number]}/RESOLUTION.txt
			# Save number of frames
			strings ${LOG[Number]} |grep "Video 1:"|awk '{print $3}' >${UniqueDir[Number]}/FRAMES.txt

			echo "${Record[Number]}" > ${UniqueDir[Number]}/Titel.txt
		      ;;
		    *)
		      echo "No support for Demuxer $DEMUXER"
		      local status=1
		      ;;
		esac

		[ ! -s ${UniqueDir[Number]}/ASPECT.txt ] && ExitError "demux failed, ASPECT.txt empty"
		[ ! -s ${UniqueDir[Number]}/RESOLUTION.txt ] && ExitError "demux failed, RESOLUTION.txt empty"
		[ ! -s ${UniqueDir[Number]}/FRAMES.txt ] && ExitError "demux failed, FRAMES.txt empty"

		# Check audio
		local NAudio=0
		if [ $status -eq 0 ]
		then
			local NAudio=`$LS -l ${UniqueDir[Number]}/*.mpa ${UniqueDir[Number]}/*.ac3 2>/dev/null|wc -l|awk '{print $1}'`
			[ $NAudio -eq 0 ] && local status=1
		
		fi
		if [ $status -eq 0 ]
		then
			echo "$DEMUXER" >${UniqueDir[Number]}/TDMUXER.txt
	   	fi
		[ $status -ne 0 ] && Exit
		[ -f ${UniqueDir[Number]}/*.mpv ] && do_transcode ${UniqueDir[Number]}
		local Number=$[ $Number + 1 ]
	done
}

do_transcode() {
	UseDir=$1

	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_transcode"
	# Check if transcode in needing
	if [ "$RETRANSCODE" != "no" -o "$DVDFORCERECODE" = "yes" ]
	then
		transfile=`echo ${UseDir}/*.mpv`
		if [ -f $transfile ]
		then
			res=`$TRANSCODE -c 1,1 -i $transfile|grep "import frame"| awk '{print($6)}'|cut -f1 -d'x'`
			echo "Resolution $transfile = $res"
			need_transcode=1
			if [ "$DVDFORCERECODE" != "yes" ]
			then
				for width in $DVDALLOWEDWIDTH
				do
					[ "$res" = "$width" ] && need_transcode=0
				done
			fi

			if [ $need_transcode -ne 0 ]
			then
				mv $transfile ${transfile}.trans
				dvd_prof=`mktemp ${UseDir}/dvd.prof.XXXXXX`
				status=$?
				if [ $status -ne 0 ]
				then
					echo "ERROR : unable to create dvd.prof file"
					logger "ERROR : unable to create dvd.prof file"
					ExitClean
				fi
				echo "max_bitrate=$DVDTRANSCODEBITRATE" > $dvd_prof
				printf "`date +"%T"`\t: Start $TRANSCODE for %s\n" $transfile
				nice -n $PRIO $TRANSCODE -i ${transfile}.trans $DVDTRANSCODEOPTS -F 8,,${dvd_prof} -o $transfile
				#nice -n $PRIO $TRANSCODE -i ${transfile}.trans $DVDTRANSCODEOPTS -o $transfile
				status=$?
				if [ $status -ne 0 ]
				then
					echo "ERROR : $TRANSCODE rc=$status."
					logger "ERROR : $TRANSCODE rc=$status."
					ExitClean
				fi
				[ -f ${transfile}.m2v ] && mv ${transfile}.m2v $transfile
			fi
		fi
	fi
}

do_mplex() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_mplex"

	local Number=1
	for i in $CMDLIN
	do
		if [ -n "$SHORTCIRCUIT_PID" -a -r ${UniqueDir[Number]}/DVDINFO.txt ]; then
			# Get shortcircuit information
			source ${UniqueDir[Number]}/DVDINFO.txt
			local Number=$[ $Number + 1 ]
			continue
		fi

		local field=1
		local mfield=1
		NEWSTREAMS[Number]=""
		if [ ! -d ${UniqueMENUDIR}/Titel-${Number} ]
		then
			mkdir ${UniqueMENUDIR}/Titel-${Number} || ExitError "Can't create directory: ${UniqueMENUDIR}/Titel-${Number}"
		fi

		TDEMUXER[Number]="`cat ${UniqueDir[Number]}/TDMUXER.txt`"
		for k in $DVDUSESTREAMS
		do
			let pid=`echo $k|cut -f 1 -d ':'|cut -c5-`
			case `echo $k|cut -f 1 -d ':'` in
			   apid[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32])
	  			case ${TDEMUXER[Number]} in
				    vdrsync|px)
					j=`printf "c%d" $[ $pid-1 ]`
					jj="mpa"
					;;
				    vdrsync[2,3])
					j=`printf "%04d" $[ $pid+10-1 ]`
					jj="mpa"
					;;
				    pva) # Wrong lang possible
					[ $pid -eq 1 ] && j="001" || j=`printf "001-%02d" $[ $pid-1 ]`
					jj="mpa"
					;;
				    *)
					;;
				esac
				;;

			    dpid[1,2])
	  			case ${TDEMUXER[Number]} in
				    vdrsync)
					j="bd"
					jj="ac3"
					;;
				    *)
					j=`printf "%03d" $[ $pid ]`
					jj="ac3"
					;;
				esac
				;;
			    *)
				;;
			esac
			[ ! -z "${NEWSTREAMS[Number]}" ] && NEWSTREAMS[Number]="${NEWSTREAMS[Number]} $j.$jj:`echo $k|cut -f2 -d ':'`" || \
				NEWSTREAMS[Number]="$j.$jj:`echo $k|cut -f2 -d ':'`"
		done

		[ -f ${UniqueDir[Number]}/audio.txt ] && rm -f ${UniqueDir[Number]}/audio.txt
		for k in ${NEWSTREAMS[Number]}
		do
			j=`echo $k|cut -f 1 -d ':'|cut -f1 -d'.'` 
			jj=`echo $k|cut -f 1 -d ':'|cut -f2 -d'.'` 
			if [ -f ${UniqueDir[Number]}/$j.$jj ]
			then
				AO=`echo $k|cut -f 2 -d ':'`
				[ $mfield -gt 1 ] && printf "," >> ${UniqueDir[Number]}/audio.txt
				printf "%s" $AO >> ${UniqueDir[Number]}/audio.txt
				local mfield=$[ $mfield + 1 ]
			fi
			local field=$[ $field + 1 ]
		done
		printf "\n" >> ${UniqueDir[Number]}/audio.txt
		AUDIO_OPTS=`cat ${UniqueDir[Number]}/audio.txt`

		streams=`echo $AUDIO_OPTS|sed 's/,/ /g'|wc -w`
	  
		if [ $streams -eq 0 ]
		then
			echo "ERROR : Keine Audiospuren"
			# Cleaning
			cd $VDRCONVERTDIR
			local Number=1
 			until [ $Number -gt $DVDMENU_ENTRY_MAX ]
			do
				$RM -rf ${UniqueDir[Number]}
				local Number=$[ $Number + 1 ]
			done
			$RM -rf ${UniqueDVDDIR}
			Exit
		fi

		local field=0
		VideoStream=`echo ${UniqueDir[Number]}/*.mpv`
		MPLEXAUDIO=""
		DVDAUDIO[Number]=""

		case $MULTIPLEXER in
		    'tcmplex_panteltje')
			for k in ${NEWSTREAMS[Number]}
			do
				j=`echo $k|cut -f 1 -d ':'|cut -f1 -d'.'` 
				jj=`echo $k|cut -f 1 -d ':'|cut -f2 -d'.'` 
				if [ -f ${UniqueDir[Number]}/$j.$jj ]
				then
					MPLEXAUDIO=${MPLEXAUDIO}`echo "-$field ${UniqueDir[Number]}/$j.$jj "`
					[ ! -z "${DVDAUDIO[Number]}" ] && DVDAUDIO[Number]="${DVDAUDIO[Number]} $j.$jj" || \
		                        	DVDAUDIO[Number]="$j.$jj"
					local field=$[ $field + 1 ]
				fi
			done
			printf "\t`date +"%T"` : Start %s for ${Record[Number]} \n\tVideostream \t : %s\n\tAudio(s) \t : %s\n\tOptions \t : %s\n\n" "$TCMPLEX_PANTELTJE" "`echo $VideoStream|xargs basename`" "${DVDAUDIO[Number]}" "$DVDTCMPLEXOPTS"
			nice -n ${PRIO} $TCMPLEX_PANTELTJE -i $VideoStream $MPLEXAUDIO $DVDTCMPLEXOPTS $DVDTCMPLEXDELAY -o ${UniqueMENUDIR}/Titel-${Number}/mplex.mpg > /dev/null 2>&1
			status=$?
		        if [ $status -ne 0 ]
	        	then
				echo "ERROR : $TCMPLEX_PANTELTJE rc=$status"
				# Cleaning
				cd $VDRCONVERTDIR
				$RM -rf ${UniqueDir[Number]} ${UniqueDVDDIR}
				Exit
			fi
			;;
		    'tcmplex')
			for k in ${NEWSTREAMS[Number]}
			do
				j=`echo $k|cut -f 1 -d ':'|cut -f1 -d'.'` 
	            		jj=`echo $k|cut -f 1 -d ':'|cut -f2 -d'.'` 
				if [ -f ${UniqueDir[Number]}/$j.$jj ]
				then
					if [ $field -lt 2 ] 
					then
						MPLEXAUDIO=${MPLEXAUDIO}`[ $field -eq 0 ] && echo "-p ${UniqueDir[Number]}/$j.$jj " || echo "-s ${UniqueDir[Number]}/$j.$jj "`
						[ ! -z "${DVDAUDIO[Number]}" ] && DVDAUDIO[Number]="${DVDAUDIO[Number]} $j.$jj" || \
		                                          DVDAUDIO[Number]="$j.$jj" 
		      			fi
					local field=$[ $field + 1 ]
				fi
			done
			printf "\t`date +"%T"` : Start %s for ${Record[Number]} \n\tVideostream \t : %s\n\tAudio(s) \t : %s\n\tOptions \t : %s\n\n" "$TCMPLEX" "`echo $VideoStream|xargs basename`" "${DVDAUDIO[Number]}" "$DVDTCMPLEXOPTS"
			nice -n ${PRIO} $TCMPLEX -i $VideoStream $MPLEXAUDIO $DVDTCMPLEXOPTS $DVDTCMPLEXDELAY -o ${UniqueMENUDIR}/Titel-${Number}/mplex.mpg > /dev/null 2>&1
			status=$?
	        	if [ $status -ne 0 ]
	        	then
	           		echo "ERROR : $TCMPLEX rc=$status"
	            		# Cleaning
				cd $VDRCONVERTDIR
				$RM -rf ${UniqueDir[Number]} ${UniqueDVDDIR}
				Exit
			fi
			;;
		    'dvb_mplex')
                	AC3OPT=""
                	for k in ${NEWSTREAMS[Number]}
                	do
                    		j=`echo $k|cut -f 1 -d ':'|cut -f1 -d'.'`
                    		jj=`echo $k|cut -f 1 -d ':'|cut -f2 -d'.'`
                    		if [ -f ${UniqueDir[Number]}/$j.$jj ]
                    		then
                      			if [ $field -lt 2 ]
                      			then
                        			MPLEXAUDIO=${MPLEXAUDIO}`echo "${UniqueDir[Number]}/$j.$jj "`
                        			[ "$jj" = "ac3" ] && AC3OPT="-c $field"
						[ ! -z "${DVDAUDIO[Number]}" ] && DVDAUDIO[Number]="${DVDAUDIO[Number]} $j.$jj" || \
                                                          DVDAUDIO[Number]="$j.$jj"
                      			fi
                      			let field=field+1
                    		fi
                	done
                	printf "\t`date +"%T"`: Start $DVBMPLEX\n"
			printf "\t`date +"%T"` : Start %s for ${Record[Number]} \n\tVideostream \t : %s\n\tAudio(s) \t : %s\n\tOptions \t : %s\n\n" "$DVBMPLEX" "`echo $VideoStream|xargs basename`" "${DVDAUDIO[Number]}" "$DVD_DVBMPLEXOPTS"
                	nice -n ${PRIO} $DVBMPLEX -o ${UniqueMENUDIR}/Titel-${Number}/mplex.mpg $DVD_DVBMPLEXOPTS -i ES_STREAM $AC3OPT $MPLEXAUDIO $VideoStream
			status=$?
	        	if [ $status -ne 0 ]
	        	then
	           		echo "ERROR : $DVBMPLEX rc=$status"
	            		# Cleaning
				cd $VDRCONVERTDIR
				$RM -rf ${UniqueDir[Number]} ${UniqueDVDDIR}
				Exit
			fi
			;;
		    'mplex')
			for k in ${NEWSTREAMS[Number]}
			do
	        		j=`echo $k|cut -f 1 -d ':'|cut -f1 -d'.'` 
	          		jj=`echo $k|cut -f 1 -d ':'|cut -f2 -d'.'` 
		  		if [ -f ${UniqueDir[Number]}/$j.$jj ]
		  		then
		     			if [ $field -lt 2 ] 
		      			then
		          			MPLEXAUDIO=${MPLEXAUDIO}`[ $field -eq 0 ] && echo " ${UniqueDir[Number]}/$j.$jj " || echo " ${UniqueDir[Number]}/$j.$jj "`
		      				[ ! -z "${DVDAUDIO[Number]}" ] && DVDAUDIO[Number]="${DVDAUDIO[Number]} $j.$jj" || \
		                                          DVDAUDIO[Number]="$j.$jj" 
		      			fi
					local field=$[ $field + 1 ]
		    		fi
			done
			if [ "$VERBOSE" = "yes" ]; then
				DVD_MPLEXOPTS="$DVD_MPLEXOPTS -v 1"
			else
				DVD_MPLEXOPTS="$DVD_MPLEXOPTS -v 0"
			fi
			printf "\t`date +"%T"` : Start %s for ${Record[Number]} \n\tVideostream \t : %s\n\tAudio(s) \t : %s\n\tOptions \t : %s\n\n" "$MPLEX" "`echo $VideoStream|xargs basename`" "${DVDAUDIO[Number]}" "$DVD_MPLEXOPTS"
			nice -n ${PRIO} $MPLEX $DVD_MPLEXOPTS -o ${UniqueMENUDIR}/Titel-${Number}/mplex%d.mpg $VideoStream $MPLEXAUDIO
			status=$?
	        	if [ $status -ne 0 ]
		        then
			            echo "ERROR : $MPLEX rc=$status"
			            # Cleaning
	        		    cd $VDRCONVERTDIR
			            $RM -rf ${UniqueDir[Number]} ${UniqueDVDDIR}
	        		    Exit
			fi

			# rename first file
			nice -n $PRIO mv "${UniqueMENUDIR}/Titel-${Number}/mplex1.mpg" "${UniqueMENUDIR}/Titel-${Number}/mplex.mpg"

		        # concenate files if existing
        		local k=2
		        while [ $k -le 999 ]
			do
        		        local filename="`printf "mplex%d.mpg" $k`"
                		if [ -f "${UniqueMENUDIR}/Titel-${Number}/$filename" ]
				then
                        		echo "DEBUG : concenate mplexed MPEG file: ${UniqueMENUDIR}/Titel-${Number}/$filename"
	                        	nice -n ${PRIO} cat "${UniqueMENUDIR}/Titel-${Number}/$filename" >>"${UniqueMENUDIR}/Titel-${Number}/mplex.mpg"
	               	                rm "${UniqueMENUDIR}/Titel-${Number}/$filename"
        		        else
                		        # Last one
                        		break
		                fi
        		        local k=$[ $k + 1 ]
	        	done
			;;
		esac

                let DVDSUBTITLESTREAMS[Number]=0
                for k in $DVDUSESUBS
                do
                        Subtitellang=`echo $k|cut -f 1 -d ' '`

			# check for subtitle file
			if [ -f "${UniqueDir[Number]}/${Subtitellang}.srt" ]
			then
				# create xml file
			       echo "<subpictures>
<stream>
  <textsub filename=\"${UniqueDir[Number]}/${Subtitellang}.srt\" characterset=\"ISO8859-1\" />
</stream>
</subpictures>
" > "${UniqueDir[Number]}/subtitle${Subtitellang}.xml"
		
				nice -n $PRIO $SPUMUX -s ${DVDSUBTITLESTREAMS[Number]} ${UniqueDir[Number]}/subtitle${Subtitellang}.xml < ${UniqueMENUDIR}/Titel-${Number}/mplex.mpg > ${UniqueMENUDIR}/Titel-${Number}/mplex_sub.mpg
				nice -n $PRIO rm ${UniqueMENUDIR}/Titel-${Number}/mplex.mpg
				nice -n $PRIO mv ${UniqueMENUDIR}/Titel-${Number}/mplex_sub.mpg ${UniqueMENUDIR}/Titel-${Number}/mplex.mpg
	
				echo "${Subtitellang} " >>  ${UniqueDir[Number]}/subtitle.txt

				DVDSUBTITLELANG[Number]="${DVDSUBTITLELANG[Number]} ${Subtitellang}"

				let DVDSUBTITLESTREAMS[Number]=${DVDSUBTITLESTREAMS[Number]}+1
			fi
		done

		let DVDAUDIOSTREAMS[Number]=0
		let AStream=0
		for au in `echo "$AUDIO_OPTS"|sed 's/,/ /g'`
		do
			let AStream=AStream+1
			DVDAUDIOTitle[Number]="${DVDAUDIOTitle[Number]} `echo $au | cut -f1 -d'+'`"
			DVDLANGTitle[Number]="${DVDLANGTitle[Number]} `echo $au | cut -f2 -d'+'`"
		done
		let DVDAUDIOSTREAMS[Number]=AStream

		DVDNORMTitle[Number]=$DVDXMLNORM
		DVDASPECTTitle[Number]=`cat ${UniqueDir[Number]}/ASPECT.txt`

		# Store information for shortcircuit
		echo "DVDNORMTitle[$Number]=\"${DVDNORMTitle[Number]}\"" >${UniqueDir[Number]}/DVDINFO.txt
		echo "DVDASPECTTitle[$Number]=\"${DVDASPECTTitle[Number]}\"" >>${UniqueDir[Number]}/DVDINFO.txt
		echo "DVDAUDIOSTREAMS[$Number]=\"${DVDAUDIOSTREAMS[Number]}\"" >>${UniqueDir[Number]}/DVDINFO.txt
		echo "DVDLANGTitle[$Number]=\"${DVDLANGTitle[Number]}\"" >>${UniqueDir[Number]}/DVDINFO.txt
		echo "DVDAUDIOTitle[$Number]=\"${DVDAUDIOTitle[Number]}\"" >>${UniqueDir[Number]}/DVDINFO.txt

		local Number=$[ $Number + 1 ]
	done
}

do_framepreview() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_framepreview"

	local Number=1
	for i in $CMDLIN
	do
	        Page=$[ $[ $Number - 1 ] / $CHAPTER_PER_PAGE +1 ]
		let DVDPANIMFRAMES[Page]=1
		let DVDPANIMSUBFRAMES[Page]=1

		local Number=$[ $Number + 1 ]
	done

	local Number=1
	for i in $CMDLIN
	do
		if [ ! -d ${UniqueDir[Number]}/preview ]
		then
			mkdir ${UniqueDir[Number]}/preview
			local status=$?
			if [ $status -ne 0 ]
			then
				echo "ERROR : mkdir ${UniqueDir[Number]}/preview rc=$status"
				ExitClean
			fi
		fi
		if [ ! -d ${UniqueDir[Number]}/Titel-${Number} ]
		then
			mkdir ${UniqueDir[Number]}/Titel-${Number}
			local status=$?
			if [ $status -ne 0 ]
			then
				echo "ERROR : mkdir ${UniqueDir[Number]}/Titel-${Number} rc=$status"
				ExitClean
			fi
		fi
		local RESOLUTION=`cat ${UniqueDir[Number]}/RESOLUTION.txt|cut -f2 -d 'x'`
		local Y=$[ $RESOLUTION / 6 ]
		if [ "`cat ${UniqueDir[Number]}/ASPECT.txt`" = "4:3" ]
		then
	        	local X=$[ $Y * 4 / 3 ]
		else
			local X=$[ $Y * 16 / 9 ]
		fi
		local RES="${X}x${Y},fast"
		local cFrames=`echo ${DVD_TIMEFRAME}|cut -f $Number -d ';'`
		[ -z "$cFrames" ] && cFrames=`echo ${DVD_TIMEFRAME}|cut -f 1 -d ';'`

		[ "$VERBOSE" = "yes" ] && echo "Extract preview frames (entry=$Number, frames=$cFrames)"
		if [ "$DVD_DISABLEANIM" = "yes" ]
		then
			tFrames=$cFrames
			cframes="`echo $tFrames|cut -f 1 -d '-'`-`echo $tFrames|cut -f 1 -d '-'`.1"
		fi
		do_frame_video "frame" "${UniqueDir[Number]}/preview" "${UniqueMENUDIR}/Titel-${Number}/mplex.mpg" "${cFrames}.$DVDANIMFRAMES" "" "$RES"
	        let Page=$[ $[ $Number - 1 ] / $CHAPTER_PER_PAGE + 1 ]
		# XXX: Find Frames from transcode log. ( too many arguments error here possible )
		let LDVDANIMFRAMES=`$LS -l ${UniqueDir[Number]}/preview/frame*.ppm|wc -l|awk '{print $1}'`
		[ "$DVD_USEVIDEOBACKGROUND" != "yes" -a $LDVDANIMFRAMES -gt ${DVDPANIMFRAMES[Page]} ] && let DVDPANIMFRAMES[Page]=LDVDANIMFRAMES
		if [ ! -d ${UniqueDir[Number]}/bigpreview ]
		then
			mkdir ${UniqueDir[Number]}/bigpreview
			local status=$?
			if [ $status -ne 0 ]
			then
				echo "ERROR : mkdir ${UniqueDir[Number]}/bigpreview rc=$status"
				ExitClean
			fi
		fi

		local BRESOLUTION=`cat ${UniqueDir[Number]}/RESOLUTION.txt|cut -f2 -d 'x'`
		local BY=$[ $BRESOLUTION / 4 ]
		if [ "`cat ${UniqueDir[Number]}/ASPECT.txt`" = "4:3" ]
		then
			BX=$[ $BY * 4 / 3 ]
		else
			BX=$[ $BY * 16 / 9 ]
		fi
		local BRES="${BX}x${BY},fast"
		local cFrames=`echo ${DVD_TIMESUBFRAME}|cut -f $Number -d ';'`
		[ -z "$cFrames" ] && local cFrames=`echo ${DVD_TIMESUBFRAME}|cut -f 1 -d ';'`

		if [ "$DVD_DISABLEANIM" = "yes" ]
		then
			tFrames=$cFrames
			cframes="`echo $tFrames|cut -f 1 -d '-'`-`echo $tFrames|cut -f 1 -d '-'`.1"
		fi
		[ "$VERBOSE" = "yes" ] && echo "Extract bigpreview frames (entry=$Number, frames=$cFrames)"
		do_frame_video "frame" "${UniqueDir[Number]}/bigpreview" "${UniqueMENUDIR}/Titel-${Number}/mplex.mpg" "${cFrames}" "" "$BRES"

		# XXX: Find Frames from transcode log. ( too many arguments error here possible )
		let LDVDANIMSUBFRAMES=`$LS -l ${UniqueDir[Number]}/bigpreview/frame*.ppm|wc -l|awk '{print $1}'`
		[ "$DVD_USESUBVIDEOBACKGROUND" != "yes" -a $LDVDANIMSUBFRAMES -gt ${DVDPANIMSUBFRAMES[Page]} ] && let DVDPANIMSUBFRAMES[Page]=LDVDANIMSUBFRAMES


		local Number=$[ $Number + 1 ]
	done
}

do_init_chapters() {
	# FIXME: review
      [ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_init_chapters"
      let Number=1
      until [ $Number -gt $DVDMENU_ENTRY_MAX ]
      do
	  cd ${UniqueDir[Number]}
	  case $DVDAUTHORMODE in
	    5min)
		DVDAUTHORCHAPTERS=\
"00:00:00,00:05:00,00:10:00,00:15:00,00:20:00,00:25:00,00:30:00,00:35:00,\
00:40:00,00:45:00,00:50:00,00:55:00,01:00:00,01:05:00,01:10:00,01:15:00,\
01:20:00,01:25:00,01:30:00,01:35:00,01:40:00,01:45:00,01:50:00,01:55:00,\
02:00:00,02:05:00,02:10:00,02:15:00,02:20:00,02:25:00,02:30:00,02:35:00,\
02:40:00,02:45:00,02:50:00,02:55:00,03:00:00,03:05:00,03:10:00,03:15:00,\
03:20:00,03:25:00,03:30:00,03:35:00,03:40:00,03:45:00,03:50:00,03:55:00,\
04:00:00,04:05:00,04:10:00,04:15:00,04:20:00,04:25:00,04:30:00,04:35:00,\
04:40:00,04:45:00,04:50:00"
		;;
	    10min)
		DVDAUTHORCHAPTERS=\
"00:00:00,00:10:00,00:20:00,00:30:00,00:40:00,00:50:00,01:00:00,01:10:00,\
01:20:00,01:30:00,01:40:00,01:50:00,02:00:00,02:10:00,02:20:00,02:30:00,\
02:40:00,02:50:00,03:00:00,03:10:00,03:20:00,03:30:00,03:40:00,03:50:00,\
04:00:00,04:10:00,04:20:00,04:30:00,04:40:00,04:50:00"
		;;
	    marks)
		if [ -r marks.vdr ]
		then
	    	      printf "%s," 0 > chapters.vdr
	    	      marklines=`cat marks.vdr|wc -l|awk '{print $1}'`
	    	      let marklines=marklines-1
	    
	    	      for t in `cat marks.vdr|head -n $marklines|cut -f1 -d'.'`
	    	      do
	        	  printf "%s," $t >> chapters.vdr
	    	      done
	    	      for t in `cat marks.vdr|tail -n 1|cut -f1 -d'.'`
	    	      do
	        	  printf "%s\n" $t >> chapters.vdr
	    	      done
		      DVDAUTHORCHAPTERS=`cat chapters.vdr`
		else
                      DVDAUTHORCHAPTERS=\
"00:00:00,00:15:00,00:30:00,00:45:00,01:00:00,01:15:00,01:30:00,01:45:00,\
02:00:00,02:15:00,02:30:00,02:45:00,03:00:00,03:15:00,03:30:00,03:45:00,\
04:00:00,04:15:00,04:30:00,04:45:00"
		fi
		;;
	    *)
		DVDAUTHORCHAPTERS=\
"00:00:00,00:15:00,00:30:00,00:45:00,01:00:00,01:15:00,01:30:00,01:45:00,\
02:00:00,02:15:00,02:30:00,02:45:00,03:00:00,03:15:00,03:30:00,03:45:00,\
04:00:00,04:15:00,04:30:00,04:45:00"
		;;	
         esac
	 Chapters[Number]=$DVDAUTHORCHAPTERS
         # Set chapterframes
         TimeforFrames[Number]=""
         TimeforOrigFrames[Number]=""
         BlankforFrames=`echo $DVDAUTHORCHAPTERS|sed 's/,/ /g'` 
         for i in $BlankforFrames
         do
	   [ "${TimeforFrames[Number]}" = "" ] && \
		   TimeforFrames[Number]=${i}-${i}.${DVDANIMCHAPTERFRAMES} || \
		   TimeforFrames[Number]=${TimeforFrames[Number]},${i}-${i}.${DVDANIMCHAPTERFRAMES}

	   # Frames for Backgrounds. 10-39 = Main, 40-99 = Submenus, 100-199 = Scenes
	   [ "${TimeforOrigFrames[Number]}" = "" ] && TimeforOrigFrames[Number]=${i}-${i}.200
         done

         let Number=Number+1
      done
}


do_frame_chapters() {
	# FIXME: review
      [ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_frame_chapters"
      let Number=1
      until [ $Number -gt $DVDMENU_ENTRY_MAX ]
      do
      	    mkdir ${UniqueDir[Number]}/chapter
	    status=$?
	    if [ $status -ne 0 ]
	    then
	        echo "ERROR : mkdir ${UniqueDir[Number]}/chapter rc=$status"
	        # Cleaning
	        cd $VDRCONVERTDIR
	        $RM -rf ${UniqueDir[Number]} ${UniqueDVDDIR}
	        Exit
	    fi
	    cd ${UniqueDir[Number]}/chapter
	    RESOLUTION=`cat ${UniqueDir[Number]}/RESOLUTION.txt|cut -f2 -d 'x'`
	    Y=$((RESOLUTION/4))
	    if [ "`cat ${UniqueDir[Number]}/ASPECT.txt`" = "4:3" ]
	    then
	        X=$((Y*4/3))
	    else
	        X=$((Y*16/9))
	    fi
	    RES="${X}x${Y},fast"
	    nice -n $PRIO rm -f cframe*	
	    if [ "$DVD_DISABLEANIM" = "yes" ]
	    then
		tFrames=${TimeforFrames[Number]}
		TimeforFrames[Number]="`echo $tFrames|cut -f 1 -d '-'`-`echo $tFrames|cut -f 1 -d '-'`.1"
	    fi


	    if [ "$DVD_MPLAYERPPM" != "yes" ]
	    then
	    	nice -n $PRIO transcode -i ${UniqueMENUDIR}/Titel-${Number}/mplex.mpg -y ppm,null -F d \
			-Z $RES $DVDTRANSCODERGB -M 0 -c ${TimeforFrames[Number]} -o cframe || Exit
	    else
		[ $DVD_MPLAYERPPMFRAMES -gt 0 ] && lframes=$DVD_MPLAYERPPMFRAMES || \
		lframes=`nice -n $PRIO transcode -c ${TimeforFrames[Number]} -i ${UniqueMENUDIR}/Titel-${Number}/mplex.mpg -o /dev/null 2>&1| \
			grep encoded|tail -n 1|awk '{print($17)}'`
		[ -z "$lframes" ] && lframes=1
		mscale=`echo $RES|cut -f1 -d ','|sed 's/x/:/'`
		sframes=`echo ${TimeforFrames[Number]}|cut -f1 -d '-'`
		mplayer -vo pnm:outdir=temp -vf scale=$mscale -ss $sframes -frames $lframes ${UniqueMENUDIR}/Titel-${Number}/mplex.mpg
		if [ -d temp ]
		then
		    cd temp
		    for i in *
		    do
			let pre=`echo $i|cut -f1 -d '.'|bc`
			let pre=pre-1
			nfile=`printf "%06d" $pre`
			mv $i ../cframe${nfile}.ppm
		    done
		    cd -
		    rm -rf temp
		fi
	    fi

	    RESOLUTION=`cat ${UniqueDir[Number]}/RESOLUTION.txt|cut -f2 -d 'x'`
	    if [ "`cat ${UniqueDir[Number]}/ASPECT.txt`" = "4:3" ]
	    then
	        X=$((Y*4/3))
	    else
	        X=$((Y*16/9))
	    fi
	    RES="${X}x${Y},fast"
	    nice -n $PRIO rm -f origframe*

	    if [ "$DVD_DISABLEANIM" = "yes" ]
	    then
		tFrames=${TimeforOrigFrames[Number]}
		TimeforOrigFrames[Number]="`echo $tFrames|cut -f 1 -d '-'`-`echo $tFrames|cut -f 1 -d '-'`.1"
	    fi
	    if [ "$DVD_MPLAYERPPM" != "yes" ]
	    then
	        nice -n $PRIO transcode -i ${UniqueMENUDIR}/Titel-${Number}/mplex.mpg -y ppm,null -F d -Z $RES \
		    $DVDTRANSCODERGB -M 0 -c ${TimeforOrigFrames[Number]} \
		    -o origframe  >>$STDOUT 2>>$STDERR || Exit
	    else
		[ $DVD_MPLAYERPPMFRAMES -gt 0 ] && lframes=$DVD_MPLAYERPPMFRAMES || \
		lframes=`nice -n $PRIO transcode -c ${TimeforOrigFrames[Number]} -i ${UniqueMENUDIR}/Titel-${Number}/mplex.mpg -o /dev/null 2>&1| \
			grep encoded|tail -n 1|awk '{print($17)}'`
		mscale=`echo $RES|cut -f1 -d ','|sed 's/x/:/'`
		[ -z "$lframes" ] && lframes=1
		sframes=`echo ${TimeforOrigFrames[Number]}|cut -f1 -d '-'`
		mplayer -vo pnm:outdir=temp -vf scale=$mscale -ss $sframes -frames $lframes ${UniqueMENUDIR}/Titel-${Number}/mplex.mpg
		if [ -d temp ]
		then
		    cd temp
		    for i in *
		    do
			let pre=`echo $i|cut -f1 -d '.'|bc`
			let pre=pre-1
			nfile=`printf "%06d" $pre`
			mv $i ../origframe${nfile}.ppm
		    done
		    cd -
		    rm -rf temp
		fi
	    fi

	    let Number=Number+1
      done

}

# Create frames for animated preview
do_frame_video() {
	# prefix of frame file name
	local prefix="$1"
	# directory to store frames
	local dir_frames="$2"
	# MPG file name
	local file_mpg="$3"
	# Frame range
	local frame_range="$4"
	# Aspect ratio
	local asr="$5"
	# Resolution (optional), will overwrite asr
	local res="$6"

	case $DVDNORM in
	    pal)
		case $asr in
		    "4:3")
			local RES="720x576"
			local ASROPT=""
			;;
		    "16:9")
			local RES="720x432"
			# Black border top and bottom
			local ASROPT="-Y -72,0,-72,0"
			;;
		    *)
			local RES="720x576"
			local ASROPT="--keep_asr"
			;;
		esac
		;;
	    ntsc)
		case $ASR in
		    "4:3")
			local RES="720x480"
			local ASROPT=""
			;;
		    "16:9")
			local RES="720x360"
			# Black border top and bottom
			local ASROPT="-Y -60,0,-60,0"
			;;
		    *)
			local RES="720x480"
			local ASROPT="--keep_asr"
			;;
		esac
			;;
	esac

	if [ -n "$res" ]
	then
		local RES="$res"
		local ASROPT=""
	fi

	pushd "$dir_frames" >>$STDOUT || ExitError "Can't pushd to directory: $dir_frames"

	nice -n $PRIO rm -f $prefix*

	if [ "$DVD_DISABLEANIM" = "yes" ]
	then
		tFrames=$frame_range
		frame_range="`echo $tFrames|cut -f 1 -d '-'`-`echo $tFrames|cut -f 1 -d '-'`.1"
	fi
	if [ "$DVD_MPLAYERPPM" != "yes" ]
	then
	    [ "$VERBOSE" = "yes" ] && echo "transcode called with: -i "$file_mpg" -y ppm,null -F d $ASROPT -Z $RES $DVDTRANSCODERGB -M 0 -c $frame_range -o $prefix"
	    nice -n $PRIO transcode -i "$file_mpg" -y ppm,null -F d $ASROPT -Z $RES $DVDTRANSCODERGB -M 0 \
		-c $frame_range -o $prefix >>$STDOUT 2>>$STDERR
	else
	    [ $DVD_MPLAYERPPMFRAMES -gt 0 ] && lframes=$DVD_MPLAYERPPMFRAMES || \
	    lframes=`nice -n $PRIO transcode -c $frame_range -i "$file_mpg" -o /dev/null 2>&1| \
		grep encoded|tail -n 1|awk '{print($17)}'`
	    mscale=`echo $RES|cut -f1 -d ','|sed 's/x/:/'`
	    [ -z "$lframes" ] && lframes=1
	    sframes=`echo $frame_range|cut -f1 -d '-'`
	    mplayer -vo pnm:outdir=temp -vf scale=$mscale -ss $sframes -frames $lframes "$file_mpg"
	    if [ -d temp ]
	    then
		cd temp
		for i in *
		do
		    let pre=`echo $i|cut -f1 -d '.'|bc`
		    let pre=pre-1
		    nfile=`printf "%06d" $pre`
		    mv $i ../${prefix}${nfile}.ppm
		done
		cd -
		rm -rf temp
	    fi
	fi

	local status=$?

	popd >>$STDOUT || ExitError "Can't popd"

	local status=$?
	if [ $status -ne 0 ]
	then
		echo "ERROR : transcode rc=$status"
		ExitClean
	fi

	return $status
}

# Create frames for animated preview mainvideo
do_frame_mainvideo() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_frame_mainvideo"

	if [ "$DVD_USEVIDEOBACKGROUND" = "yes" ]
	then
		local Number=1
		until [ $Number -gt $DVDMENU_ENTRY_MAX ]
		do
			if [ ! -d ${UniqueDir[Number]}/mainvideo ]
			then
				mkdir ${UniqueDir[Number]}/mainvideo
				local status=$?
				if [ $status -ne 0 ]
				then
					echo "ERROR : mkdir ${UniqueDir[Number]}/mainvideo rc=$status"
					ExitClean
				fi
			fi
			local ASR="`cat ${UniqueDir[Number]}/ASPECT.txt`"
			local cFrames=`echo ${DVD_TIMEMAINBACKFRAME}|cut -f $Number -d ';'`
			[ -z "$cFrames" ] && local cFrames=`echo ${DVD_TIMEMAINBACKFRAME}|cut -f 1 -d ';'`

			[ "$VERBOSE" = "yes" ] && echo "Create mainvideo frames (entry=$Number)"
			do_frame_video "mainvideo" "${UniqueDir[Number]}/mainvideo" "${UniqueMENUDIR}/Titel-${Number}/mplex.mpg" "${cFrames}" "$ASR"
			# XXX: Find Frames from transcode log. ( too many arguments error here possible )
			let DVDANIMFRAMES=`$LS -l ${UniqueDir[Number]}/mainvideo/mainvideo*.ppm|wc -l|awk '{print $1}'`

			local Number=$[ $Number + 1 ]
		done
	fi
}

# Create frames for animated preview subvideo
do_frame_subvideo() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_frame_subvideo"

	if [ "$DVD_USESUBVIDEOBACKGROUND" = "yes" ]
	then
		local Number=1
		until [ $Number -gt $DVDMENU_ENTRY_MAX ]
		do
			if [ ! -d ${UniqueDir[Number]}/subvideo ]
			then
				mkdir ${UniqueDir[Number]}/subvideo
				local status=$?
				if [ $status -ne 0 ]
				then
					echo "ERROR : mkdir ${UniqueDir[Number]}/subvideo rc=$status"
					ExitClean
				fi
			fi
			local ASR="`cat ${UniqueDir[Number]}/ASPECT.txt`"
			local cFrames=`echo ${DVD_TIMESUBBACKFRAME}|cut -f $Number -d ';'`
			[ -z "$cFrames" ] && local cFrames=`echo ${DVD_TIMESUBBACKFRAME}|cut -f 1 -d ';'`

			[ "$VERBOSE" = "yes" ] && echo "Create subvideo frames (entry=$Number)"
			do_frame_video "subvideo" "${UniqueDir[Number]}/subvideo" "${UniqueMENUDIR}/Titel-${Number}/mplex.mpg" "${cFrames}" "$ASR"
			# XXX: Find Frames from transcode log. ( too many arguments error here possible )
			let DVDANIMSUBFRAMES=`$LS -l ${UniqueDir[Number]}/subvideo/subvideo*.ppm|wc -l|awk '{print $1}'`
			#let DVDANIMSUBFRAMES=`$LS -l ${UniqueDir[Number]}/subvideo|wc -l|awk '{print $1}'`
			local Number=$[ $Number + 1 ]
		done
	fi
}

do_prepare_chapters() {
	# FIXME: review
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_prepare_chapters"
	background_directory=`echo $CMDLINE|awk '{print $1}'`
	chapter=${UniqueTempDIR}/cbackground.pnm
	chapter_action=${UniqueTempDIR}/action_cbackground.pnm

	let Number=1
        until [ $Number -gt $DVDMENU_ENTRY_MAX ]
        do
	    chapter_directory=${SourceDir[Number]}
	    chapter=${UniqueDir[Number]}/chapter.pnm

	    if [ -z "$DVDCHAPTERBACKFILE" ]
	    then
	        if [ -r "$chapter_directory/chapter.pnm" ] 
	        then
		    nice -n $PRIO cp $chapter_directory/chapter.pnm $chapter
	        fi
	    else
	        if [ -r "$chapter_directory/chapter.pnm" ]
	        then
		    nice -n $PRIO cp $chapter_directory/chapter.pnm $chapter
	        else
	            if [ -r "$DVDCHAPTERBACKFILE" ]
	            then
		        nice -n $PRIO cp $DVDCHAPTERBACKFILE $chapter
		    fi
	        fi
	    fi

	    if [ ! -f $chapter ]
	    then
	
		if [ -f ${UniqueDir[Number]}/chapter/origframe000030.ppm ]
		then
		    nice -n $PRIO cp ${UniqueDir[Number]}/chapter/origframe000030.ppm $chapter
		else
	            ppmmake $DVDFILE_CHAPTERBACKGROUND_COLOR $DVDNORM_XRES $DVDNORM_YRES > $chapter
		fi
	    fi
    
	    # Check resolution and correct
	    XRES=`pnmfile $chapter|awk '{print $4}'`
	    YRES=`pnmfile $chapter|awk '{print $6}'`
	    if [ $XRES -ne $DVDNORM_XRES -o $YRES -ne $DVDNORM_YRES ]
	    then
		    nice -n $PRIO mv $chapter $chapter.old && pnmtile $DVDNORM_XRES $DVDNORM_YRES $chapter.old > $chapter
		    [ -f $chapter.old ] && $RM $chapter.old
	    fi

	    let chapter_pages[Number]=0

	    if [ -d ${UniqueDir[Number]}/chapter ]
	    then
	        FILES=`ls -l  ${UniqueDir[Number]}/chapter|wc -l|awk '{print $1}'`
	        let chapter_pages[Number]=$[ $FILES / $DVDANIMCHAPTERFRAMES ]
	    fi
	    let Number=Number+1
	done
}

do_chapters() {
	# FIXME: review
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_chapters"
	mbutton=${UniqueTempDIR}/mbutton
	sbutton=${UniqueTempDIR}/sbutton
	abutton=${UniqueTempDIR}/abutton
	sabutton=${UniqueTempDIR}/sabutton
	# Chapter Navigation Buttons
	cmbutton=${UniqueTempDIR}/cmbutton
	csbutton=${UniqueTempDIR}/csbutton
	cabutton=${UniqueTempDIR}/cabutton

        let Number=1
        until [ $Number -gt $DVDMENU_ENTRY_MAX ]
        do
	    Page=$[ $[ $Number - 1 ] / $CHAPTER_PER_PAGE ]
	    chapter=${UniqueDir[Number]}/chapter.pnm
	    chapter_action=${UniqueDir[Number]}/action_chapter.pnm
	    # Animation Chapter(s)
	    [ ! -d ${UniqueDir[Number]}/chapters/${Page} ] && mkdir -p ${UniqueDir[Number]}/chapters/${Page}
	    status=$?
	    #
	    ## check
	    #
	    let vc=0
	    let count=0
	    [ "$VERBOSE" = "yes" ] && echo "Put Chapters"
	    while [ $count -lt $DVDANIMCHAPTERFRAMES ]
	    do
	      [ "$VERBOSE" = "yes" ] && printf "%05d (%05d)\r" $[ $count +1 ] $DVDANIMCHAPTERFRAMES
	      #let vc=count*2
	      let vc=count
	    [ $vc -gt $[ $DVDNORM_XRES - $LOGO_XSIZE - 10 - 30 ] ] && vc=$DVDNORM_XRES
	      tcount=`printf "%06d" $count`
	      [ ! -f ${UniqueDir[Number]}/chapters/${Page}/chapter-${tcount}.ppm ] && nice -n $PRIO cp $chapter ${UniqueDir[Number]}/chapter/${Page}/chapter-${tcount}.ppm

		# TODO: optimizing
	      if [ "$DVD_ANIMATEVERSION" = "yes" ]
	      then
		if [ "$DVD_ANIMATELOGO" = "yes" -a -r "$DVD_ANIMATELOGO_FILE" ]; then
                	put_file ${UniqueDir[Number]}/chapters/${Page}/chapter-${tcount}.ppm \
                        	$[ $vc + 30 ] $[ $DVDNORM_YRES - 30 - $LOGO_YSIZE / 2 ] \
				$DVD_ANIMATELOGO_FILE || Exit
		fi
		put_text ${UniqueDir[Number]}/chapters/${Page}/chapter-${tcount}.ppm \
		       $font_version "" "$DVDMAINCOLFG" "$DVDCOLBG" \
		       $[ $vc + $LOGO_XSIZE + 10 + 30 ] $[ $DVDNORM_YRES - 40 ] "$generatedvd_version"
	      fi
	      let count=count+1
	      done

	      let Number=Number+1
	done
}

do_submenus() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_submenus"

	# Button Rahmen
	local mbutton=${UniqueTempDIR}/mbutton.ppm
	local rightmbutton=${UniqueTempDIR}/rightmbutton.ppm
	local leftmbutton=${UniqueTempDIR}/leftmbutton.ppm
	local playmbutton=${UniqueTempDIR}/playmbutton.ppm
	local backmbutton=${UniqueTempDIR}/backmbutton.ppm
	# Transparenz fuer Button Rahmen inneres
	local sabutton=${UniqueTempDIR}/sabutton.ppm

        local rightbutton_imagewidth=`pnmfile $DVDBUTTONDIR/right-000000.ppm|awk '{print $4}'`
        local rightbutton_imageheight=`pnmfile $DVDBUTTONDIR/right-000000.ppm|awk '{print $6}'`

        local leftbutton_imagewidth=`pnmfile $DVDBUTTONDIR/left-000000.ppm|awk '{print $4}'`
        local leftbutton_imageheight=`pnmfile $DVDBUTTONDIR/left-000000.ppm|awk '{print $6}'`

        local playbutton_imagewidth=`pnmfile $DVDBUTTONDIR/play-000000.ppm|awk '{print $4}'`
        local playbutton_imageheight=`pnmfile $DVDBUTTONDIR/play-000000.ppm|awk '{print $6}'`

        local backbutton_imagewidth=`pnmfile $DVDBUTTONDIR/back-000000.ppm|awk '{print $4}'`
        local backbutton_imageheight=`pnmfile $DVDBUTTONDIR/back-000000.ppm|awk '{print $6}'`

        let Number=1
	let bimagewidth=0
	let bimageheight=0
        until [ $Number -gt $DVDMENU_ENTRY_MAX ]
        do
            tmp_but_image="${UniqueDir[Number]}/bigpreview/frame000000.ppm"

            imagewidth=`pnmfile $tmp_but_image|awk '{print $4}'`
	    [ $bimagewidth -lt $imagewidth ] && let bimagewidth=imagewidth
            imageheight=`pnmfile $tmp_but_image|awk '{print $6}'`
	    [ $bimageheight -lt $imageheight ] && let bimageheight=imageheight
            let Number=Number+1
	done

	# Create buttons
	local active_x_offset=12
	local active_y_offset=12

	local size_xbutton=$[ $rightbutton_imagewidth + $active_x_offset ]
	local size_ybutton=$[ $rightbutton_imageheight + $active_y_offset ]
	nice -n $PRIO ppmmake $DVDBUTTONCOLOR   $size_xbutton $size_ybutton > $rightmbutton || ExitError "ppmake"
	nice -n $PRIO ppmmake '#ffffff'         $rightbutton_imagewidth $rightbutton_imageheight > $sabutton || ExitError "ppmake"
        put_file $rightmbutton $[ $active_x_offset / 2 ] $[ $active_y_offset / 2 ]  $sabutton || ExitError "ppmmake"

	local size_xbutton=$[ $leftbutton_imagewidth + $active_x_offset ]
	local size_ybutton=$[ $leftbutton_imageheight + $active_y_offset ]
	nice -n $PRIO ppmmake $DVDBUTTONCOLOR   $size_xbutton $size_ybutton > $leftmbutton || ExitError "ppmmake"
	nice -n $PRIO ppmmake '#ffffff'         $leftbutton_imagewidth $leftbutton_imageheight > $sabutton || ExitError "ppmmake"
        put_file $leftmbutton $[ $active_x_offset / 2 ] $[ $active_y_offset / 2 ]  $sabutton || ExitError "ppmmake"

	local size_xbutton=$[ $playbutton_imagewidth + $active_x_offset ]
	local size_ybutton=$[ $playbutton_imageheight + $active_y_offset ]
	nice -n $PRIO ppmmake $DVDBUTTONCOLOR   $size_xbutton $size_ybutton > $playmbutton || ExitError "ppmmake"
        nice -n $PRIO ppmmake '#ffffff'         $playbutton_imagewidth $playbutton_imageheight > $sabutton || ExitError "ppmmake"
        put_file $playmbutton $[ $active_x_offset / 2 ] $[ $active_y_offset / 2 ]  $sabutton || ExitError "ppmmake"

	local size_xbutton=$[ $backbutton_imagewidth + $active_x_offset ]
	local size_ybutton=$[ $backbutton_imageheight + active_y_offset ]
	nice -n $PRIO ppmmake $DVDBUTTONCOLOR   $size_xbutton $size_ybutton > $backmbutton || ExitError
	nice -n $PRIO ppmmake '#ffffff'         $backbutton_imagewidth $backbutton_imageheight > $sabutton || ExitError
        put_file $backmbutton $[ $active_x_offset / 2 ] $[ $active_y_offset / 2 ]  $sabutton || ExitError


	local left_offset=80
	local right_offset=80
	local upper_offset=70
	local lower_offset=0
	local frame_offset=$[ $active_y_offset * 3 ]

	#NOTUSED# let entryx=`echo "$left_offset+$bimagewidth"|bc`
	#NOTUSED# let entryy=`echo "$upper_offset"|bc`
	local deltax=$[ $bimagewidth + $active_x_offset + 2 ]
	local deltay=$[ $bimageheight + $frame_offset ]
	#NOTUSED# local x1=$right_offset
	#NOTUSED# local y1=$upper_offset

	local Number=1
	until [ $Number -gt $DVDMENU_ENTRY_MAX ]
	do
		local Page=1
		until [ $Page -gt ${epg_pages[Number]} ]
		do
			[ "$VERBOSE" = "yes" ] && echo "Create sub menu text picture (entry=$Number page=$Page)"

			if [ ! -d ${UniqueDir[Number]}/submenu/${Page} ]
			then
				mkdir -p ${UniqueDir[Number]}/submenu/${Page} || ExitError
			fi

			# Create empty black picture
			nice -n $PRIO ppmmake '#000000' $DVDNORM_XRES $DVDNORM_YRES >${UniqueDir[Number]}/submenu/${Page}/text.ppm || ExitError
			nice -n $PRIO ppmmake '#000000' $DVDNORM_XRES $DVDNORM_YRES | nice -n $PRIO ppmtopgm >${UniqueDir[Number]}/submenu/${Page}/text_alpha.pgm || ExitError

			EPGText=`cat ${UniqueDir[Number]}/epg_text-${Page}`

			# Create EPG text picture
			text_to_pnm ${UniqueDir[Number]}/submenu/${Page}/epg.ppm ${UniqueDir[Number]}/submenu/${Page}/epg_alpha.pgm \
				$font_big_additional "$DVDSUBCOLFG" "$DVDCOLBG" \
				"$EPGText" \
				--wrap $[ $DVDNORM_XRES - 150 ] \
				-s $DVDBUTTONDIR/epgstyle || ExitError

			# Merge pictures
			nice -n $PRIO pnmpaste ${UniqueDir[Number]}/submenu/${Page}/epg.ppm \
				75 40 \
				${UniqueDir[Number]}/submenu/${Page}/text.ppm >${UniqueDir[Number]}/submenu/${Page}/tmp.ppm || ExitError

			nice -n $PRIO pnmpaste ${UniqueDir[Number]}/submenu/${Page}/epg_alpha.pgm \
				75 40 \
				${UniqueDir[Number]}/submenu/${Page}/text_alpha.pgm >${UniqueDir[Number]}/submenu/${Page}/tmp_alpha.pgm || ExitError

			nice -n $PRIO mv ${UniqueDir[Number]}/submenu/${Page}/tmp.ppm ${UniqueDir[Number]}/submenu/${Page}/text.ppm || ExitError
			nice -n $PRIO mv ${UniqueDir[Number]}/submenu/${Page}/tmp_alpha.pgm ${UniqueDir[Number]}/submenu/${Page}/text_alpha.pgm || ExitError

			if [ "$DVD_DISPLAY_PAGETEXT" = "yes" -a ${epg_pages[Number]} -gt 1 ]
			then
				# Display "page <page> / <pages>"

				local px=$[ $DVDNORM_XRES / 2 + $DVDNORM_XRES / 4 + 10 ]
				local py=$[ $DVDNORM_YRES - 80 ]

				# Create text picture
				text_to_pnm ${UniqueDir[Number]}/submenu/${Page}/page.ppm ${UniqueDir[Number]}/submenu/${Page}/page_alpha.pgm \
					"$font_info"  "$DVDMAINCOLFG" "$DVDCOLBG" \
			      		"$DVD_PAGETEXT ${Page} / ${epg_pages[Number]}" \
					-s $DVDBUTTONDIR/style || ExitError

				# Merge pictures
				nice -n $PRIO pnmpaste ${UniqueDir[Number]}/submenu/${Page}/page.ppm \
					$px $py \
					${UniqueDir[Number]}/submenu/${Page}/text.ppm >${UniqueDir[Number]}/submenu/${Page}/tmp.ppm || ExitError

				nice -n $PRIO pnmpaste ${UniqueDir[Number]}/submenu/${Page}/page_alpha.pgm \
					$px $py \
					${UniqueDir[Number]}/submenu/${Page}/text_alpha.pgm >${UniqueDir[Number]}/submenu/${Page}/tmp_alpha.pgm || ExitError

				nice -n $PRIO mv ${UniqueDir[Number]}/submenu/${Page}/tmp.ppm ${UniqueDir[Number]}/submenu/${Page}/text.ppm || ExitError
				nice -n $PRIO mv ${UniqueDir[Number]}/submenu/${Page}/tmp_alpha.pgm ${UniqueDir[Number]}/submenu/${Page}/text_alpha.pgm || ExitError
			fi

			# Create frames
			[ "$VERBOSE" = "yes" ] && echo "Create sub menu animation frames (entry=$Number page=$Page)"
			[ "$DVD_USESUBVIDEOBACKGROUND" != "yes" ] && let DVDANIMSUBFRAMES=${DVDPANIMSUBFRAMES[Page]}
			local count=0
			while [ $count -lt $DVDANIMSUBFRAMES ]
			do
				[ "$VERBOSE" = "yes" ] && printf "%05d (%05d)\r" $[ $count +1 ] $DVDANIMSUBFRAMES

				local vx=$count
				[ $vx -gt $[ $DVDNORM_XRES - $LOGO_XSIZE - 10 - 30 ] ] && vx=$[ $DVDNORM_XRES - $LOGO_XSIZE - 10 - 30 ]

				local tcount=`printf "%06d" $count`

				if [ "$DVD_USESUBVIDEOBACKGROUND" = "yes" ]
				then
					local menu_src=${UniqueDir[Number]}/subvideo/subvideo${tcount}.ppm
					[ ! -f ${UniqueDir[Number]}/subvideo/subvideo${tcount}.ppm ] && cp ${UniqueDir[Number]}/subbackground.pnm ${UniqueDir[Number]}/subvideo/subvideo${tcount}.ppm
				else
					local menu_src=${UniqueDir[Number]}/subbackground.pnm
					#[ ! -f ${UniqueDir[Number]}/submenu/${Page}/subbackground-${tcount}.ppm ] && cp $menu_src ${UniqueDir[Number]}/submenu/${Page}/subbackground-${tcount}.ppm
					[ ! -f ${UniqueDir[Number]}/submenu/${Page}/subbackground-${tcount}.ppm ] && cp $menu_src ${UniqueDir[Number]}/submenu/${Page}/subbackground-${tcount}.ppm
				fi

				if [ "$DVD_ANIMATEVERSION" = "yes" ]
				then
					if [ "$DVD_ANIMATELOGO" = "yes" -a -r "$DVD_ANIMATELOGO_FILE" ]; then
						# paste logo pict into menu pict | paste text pict (with alpha channel) >background-${tcount}.ppm
						nice -n $PRIO pnmpaste $DVD_ANIMATELOGO_FILE \
							$[ $vx + 30 ] $[ $YRES - 30 - $LOGO_YSIZE / 2 ] \
							$menu_src | nice -n $PRIO pnmcomp -xoff=$[ $vx + $LOGO_XSIZE + 10 + 30 ] -yoff=$[ $YRES - 40 ] -alpha=$version_main_alpha_pnm $version_main_pnm >${UniqueDir[Number]}/submenu/${Page}/tmp.ppm || ExitError
					else
						# paste version pict (with alpha channel) into menu pict >background-${tcount}.ppm
						nice -n $PRIO pnmcomp -xoff=$[ $vx + $LOGO_XSIZE + 10 + 30 ] -yoff=$[ $YRES - 40 ] -alpha=$version_main_alpha_pnm $version_main_pnm $menu_src >${UniqueDir[Number]}/submenu/${Page}/tmp.ppm || ExitError
					fi

					# Put title text picture into background picture
					nice -n $PRIO pnmcomp -alpha=${UniqueDir[Number]}/submenu/${Page}/text_alpha.pgm ${UniqueDir[Number]}/submenu/${Page}/text.ppm ${UniqueDir[Number]}/submenu/${Page}/tmp.ppm >${UniqueDir[Number]}/submenu/${Page}/subbackground-${tcount}.ppm || ExitError

					nice -n $PRIO rm -f ${UniqueDir[Number]}/submenu/${Page}/tmp.ppm
				else
					# paste title text pict (with alpha channel) into menu pict >background-${tcount}.ppm
					nice -n $PRIO pnmcomp -alpha=${UniqueDir[Number]}/submenu/${Page}/text_alpha.pgm ${UniqueDir[Number]}/submenu/${Page}/text.ppm $menu_src >${UniqueDir[Number]}/submenu/${Page}/subbackground-${tcount}.ppm || ExitError
				fi

				local count=$[ $count + 1 ]
			done
			[ "$VERBOSE" = "yes" ] && echo

			local Page=$[ $Page + 1 ]
		done


		#NOTUSED# local stextjust="right"
		#NOTUSED# local smenuwidth=`pnmfile ${UniqueDir[Number]}/submenu/${Page}/subbackground-000000.ppm|awk '{print $4}'`
		#NOTUSED# local smenuheight=`pnmfile ${UniqueDir[Number]}/submenu/${Page}/subbackground-000000.ppm|awk '{print $6}'`
		#NOTUSED# local simagewidth=`pnmfile ${UniqueDir[Number]}/bigpreview/frame000000.ppm|awk '{print $4}'`
		#NOTUSED# local simageheight=`pnmfile ${UniqueDir[Number]}/bigpreview/frame000000.ppm|awk '{print $6}'`

		local left_frames=`$LS -l $DVDBUTTONDIR/left-*.ppm|wc -l|awk '{print $1}'`
		local right_frames=`$LS -l $DVDBUTTONDIR/right-*.ppm|wc -l|awk '{print $1}'`
		local play_frames=`$LS -l $DVDBUTTONDIR/play-*.ppm|wc -l|awk '{print $1}'`
		local back_frames=`$LS -l $DVDBUTTONDIR/back-*.ppm|wc -l|awk '{print $1}'`

		local py=$[ $DVDNORM_YRES - $bimageheight - $lower_offset ]

		local px_back=$left_offset
		local px_preview=$[ $px_back + $backbutton_imagewidth + $active_x_offset * 2 ]
		local px_play=$[ $px_preview + $bimagewidth + $active_x_offset * 2 ]
		local px_left=$[ $px_play + $playbutton_imagewidth + $active_x_offset * 2 ]
		local px_right=$[ $px_left + $leftbutton_imagewidth + $active_x_offset * 2 ]

		local Page=1
		until [ $Page -gt ${epg_pages[Number]} ]
		do
			[ "$VERBOSE" = "yes" ] && echo "Put sub menu buttons (entry=$Number page=$Page)"

			local count=0
			local bcount=0
			local pcount=0
			local rcount=0
			local lcount=0

			while [ $count -lt $DVDANIMSUBFRAMES ]
			do
				[ "$VERBOSE" = "yes" ] && printf "%05d (%05d)\r" $[ $count +1 ] $DVDANIMSUBFRAMES

				local tcount=`printf "%06d" $count`
				local btcount=`printf "%06d" $bcount`
				local ptcount=`printf "%06d" $pcount`
				local rtcount=`printf "%06d" $rcount`
				local ltcount=`printf "%06d" $lcount`

				[ ! -f ${UniqueDir[Number]}/bigpreview/frame${tcount}.ppm ] && cp ${UniqueDir[Number]}/bigpreview/frame000000.ppm ${UniqueDir[Number]}/bigpreview/frame${tcount}.ppm


				if [ ${epg_pages[Number]} -gt 1 ]
				then
					if [ $Page -gt 1 ]
					then
						if [ $Page -lt ${epg_pages[Number]} ]
						then
							# Buttons: back, play, left, right
							nice -n $PRIO pnmpaste \
								$DVDBUTTONDIR/back-${btcount}.ppm \
								$px_back $py \
								${UniqueDir[Number]}/submenu/${Page}/subbackground-${tcount}.ppm | nice -n $PRIO pnmpaste \
									$DVDBUTTONDIR/play-${ptcount}.ppm \
									$px_play $py | nice -n $PRIO pnmpaste \
										$DVDBUTTONDIR/left-${ltcount}.ppm \
										$px_left $py | nice -n $PRIO pnmpaste \
											$DVDBUTTONDIR/right-${rtcount}.ppm \
											$px_right $py \
								>${UniqueDir[Number]}/submenu/${Page}/tmp.ppm || ExitError
						else
							# Buttons: back, play, left
							nice -n $PRIO pnmpaste \
								$DVDBUTTONDIR/back-${btcount}.ppm \
								$px_back $py \
								${UniqueDir[Number]}/submenu/${Page}/subbackground-${tcount}.ppm | nice -n $PRIO pnmpaste \
									$DVDBUTTONDIR/play-${ptcount}.ppm \
									$px_play $py | nice -n $PRIO pnmpaste \
										$DVDBUTTONDIR/left-${ltcount}.ppm \
										$px_left $py \
								>${UniqueDir[Number]}/submenu/${Page}/tmp.ppm || ExitError
						fi
					else
						# Buttons: back, play, right
						nice -n $PRIO pnmpaste \
							$DVDBUTTONDIR/back-${btcount}.ppm \
							$px_back $py \
							${UniqueDir[Number]}/submenu/${Page}/subbackground-${tcount}.ppm | nice -n $PRIO pnmpaste \
								$DVDBUTTONDIR/play-${ptcount}.ppm \
								$px_play $py | nice -n $PRIO pnmpaste \
									$DVDBUTTONDIR/right-${rtcount}.ppm \
									$px_right $py \
							>${UniqueDir[Number]}/submenu/${Page}/tmp.ppm || ExitError
					fi
				else
					# Buttons: back, play
					nice -n $PRIO pnmpaste \
						$DVDBUTTONDIR/back-${btcount}.ppm \
						$px_back $py \
						${UniqueDir[Number]}/submenu/${Page}/subbackground-${tcount}.ppm | nice -n $PRIO pnmpaste \
							$DVDBUTTONDIR/play-${ptcount}.ppm \
							$px_play $py \
						>${UniqueDir[Number]}/submenu/${Page}/tmp.ppm || ExitError
				fi

				nice -n $PRIO mv ${UniqueDir[Number]}/submenu/${Page}/tmp.ppm ${UniqueDir[Number]}/submenu/${Page}/subbackground-${tcount}.ppm

				if  [ "$DVD_USESUBVIDEOBACKGROUND" != "yes" ]
				then
				    put_file ${UniqueDir[Number]}/submenu/${Page}/subbackground-${tcount}.ppm \
					$px_preview $[ $py - $active_y_offset ] \
					${UniqueDir[Number]}/bigpreview/frame${tcount}.ppm || ExitError
	    
				fi
				local count=$[ $count + 1 ]
				local bcount=$[ $bcount + 1 ]
				local pcount=$[ $pcount + 1 ]
				local rcount=$[ $rcount + 1 ]
				local lcount=$[ $lcount + 1 ]

				[ $bcount -ge $back_frames ] && local bcount=0
				[ $pcount -ge $play_frames ] && local pcount=0
				[ $rcount -ge $right_frames ] && local rcount=0
				[ $lcount -ge $left_frames ] && local lcount=0
			done
			[ "$VERBOSE" = "yes" ] && echo


			# Create action picture
			submenu_action=${UniqueTempDIR}/action-${Number}-${Page}-subbackground.pnm
			submenu_actionp=${UniqueTempDIR}/action-${Number}-${Page}-subbackground.png
			nice -n $PRIO ppmmake '#ffffff' $DVDNORM_XRES $DVDNORM_YRES >$submenu_action

			# Action picture "back"
			put_file   $submenu_action \
				$[ $px_back - $active_x_offset / 2 ] $[ $py - $active_y_offset / 2 ] \
				$backmbutton || ExitError

			# Action picture "play"
			put_file   $submenu_action \
				$[ $px_play - $active_x_offset / 2 ] $[ $py - $active_y_offset / 2 ] \
				$playmbutton || ExitError

			if [ $Page -gt 1 ]
			then
				# Action picture "left"
				put_file   $submenu_action \
					$[ $px_left - $active_x_offset / 2 ] $[ $py - $active_y_offset / 2 ] \
					$leftmbutton || ExitError
			fi

			if [ ${epg_pages[Number]} -gt 1 -a $Page -lt ${epg_pages[Number]} ]
			then
				# Action picture "right"
				put_file   $submenu_action \
					$[ $px_right - $active_x_offset / 2 ] $[ $py - $active_y_offset / 2 ] \
					$rightmbutton || ExitError
			fi

			[ "$VERBOSE" = "yes" ] && echo "Multiplex sub menu page (number=$Number page=$Page)"

			# Generate mpg
			nice -n ${PRIO} pnmtopng -transparent '#ffffff' $submenu_action >$submenu_actionp  2>>$STDERR

			nice -n ${PRIO} cat ${UniqueDir[Number]}/submenu/${Page}/subbackground-*.ppm >${UniqueDir[Number]}/submenu/${Page}/submenu.ppm
			nice -n ${PRIO} ppmtoy4m -n $DVDANIMSUBFRAMES $DVDNORM_PPMTOY4M -I t -L -r -v 0 $CHROMASUB ${UniqueDir[Number]}/submenu/${Page}/submenu.ppm | nice -n ${PRIO} mpeg2enc -q 2 -a 2 -n p -f 8 -v 0 -o ${UniqueDir[Number]}/submenu/submenu-${Page}.m2v >>$STDOUT 2>>$STDERR

			# Multiplex menu
			# Calculate duration of silence file
			case $DVDNORM in
			    "pal")
				local duration=$[ ( $DVDANIMSUBFRAMES + 24 ) / 25 ]
				;;
			    "ntsc")
				local duration=$[ ( $DVDANIMSUBFRAMES + 29 ) * 1001 / 30000 ]
				;;
			esac
			if [ $duration -lt 1 ]; then
				local duration=1
			fi

			if [ -z "$DVDSUBSILENCEFILE" ]
			then
				if [ ! -f ${UniqueTempDIR}/silence-${duration}s.mp2 ]
				then
					[ "$VERBOSE" = "yes" ] && echo "INFO  : submenu mpg duration=${duration}s DVDANIMSUBFRAMES=$DVDANIMSUBFRAMES"
					nice -n $PRIO $ARECORD -f dat -t wav -d ${duration} ${UniqueTempDIR}/silence-${duration}s.wav >>$STDOUT 2>>$STDERR || ExitError
					nice -n $PRIO $MP2ENC -r 48000 -o ${UniqueTempDIR}/silence-${duration}s.mp2 <${UniqueTempDIR}/silence-${duration}s.wav >>$STDOUT 2>>$STDERR || ExitError
				fi
				SILENCE=${UniqueTempDIR}/silence-${duration}s.mp2
			else
				SILENCE=$DVDSUBSILENCEFILE
			fi

			nice -n ${PRIO} $MPLEX -v 0 -f 8 -l $duration -o /dev/stdout ${UniqueDir[Number]}/submenu/submenu-${Page}.m2v $SILENCE >${UniqueDir[Number]}/submenu/submenu-${Page}.mpg || Exit
			local Page=$[ $Page + 1 ]
		done
		local Number=$[ $Number + 1 ]
	done
}


do_prepare_titelmenu() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_prepare_titelmenu"
	# FIXME: where to get CMDLINE
	local background_directory=`echo $CMDLINE|awk '{print $1}'`
	local menu=${UniqueTempDIR}/background.pnm

	if [ -z "$DVDMAINBACKFILE" ]
	then
		if [ -r "$background_directory/background.pnm" ] 
		then
			cp $background_directory/background.pnm $menu
		fi
	else
		if [ -r "$background_directory/background.pnm" ]
		then
			cp $background_directory/background.pnm $menu
		else
			if [ -r "$DVDMAINBACKFILE" ]
			then
				cp $DVDMAINBACKFILE $menu
			fi
		fi
	fi

	if [ ! -f $menu -o "$DVDMAINBACKFILE_USE" != "yes" ]
	then
		nice -n $PRIO ppmmake $DVDFILE_MAINBACKGROUND_COLOR $DVDNORM_XRES $DVDNORM_YRES >$menu
	fi

	# Check resolution and correct
	XRES=`pnmfile $menu|awk '{print $4}'`
	YRES=`pnmfile $menu|awk '{print $6}'`
	if [ $XRES -ne $DVDNORM_XRES -o $YRES -ne $DVDNORM_YRES ]
	then
		nice -n $PRIO mv $menu $menu.old && pnmtile $DVDNORM_XRES $DVDNORM_YRES $menu.old >$menu
		[ -f $menu.old ] && $RM $menu.old
	fi
}

do_titelmenu() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_titelmenu"

	if [ ! -d ${UniqueTempDIR}/preview ]
	then
		mkdir ${UniqueTempDIR}/preview
		local status=$?
		[ $status -ne 0 ] && Exit
	fi

	# Button file names
	local mbutton=${UniqueTempDIR}/mbutton.ppm
	local downmbutton=${UniqueTempDIR}/downmbutton.ppm
	local upmbutton=${UniqueTempDIR}/upmbutton.ppm
	# Transparenz fuer Button Rahmen inneres
	local sabutton=${UniqueTempDIR}/sabutton.ppm

	# Get size of frames
	local downbutton_imagewidth=`pnmfile $DVDBUTTONDIR/down-000000.ppm|awk '{print $4}'`
	local downbutton_imageheight=`pnmfile $DVDBUTTONDIR/down-000000.ppm|awk '{print $6}'`

	local upbutton_imagewidth=`pnmfile $DVDBUTTONDIR/up-000000.ppm|awk '{print $4}'`
	local upbutton_imageheight=`pnmfile $DVDBUTTONDIR/up-000000.ppm|awk '{print $6}'`

	# Find max size of preview images
	local Number=1
	local bimagewidth=0
	local bimageheight=0
        until [ $Number -gt $DVDMENU_ENTRY_MAX ]
        do
		local tmp_but_image="${UniqueDir[Number]}/preview/frame000000.ppm"

		local imagewidth=`pnmfile $tmp_but_image|awk '{print $4}'`
		[ $bimagewidth -lt $imagewidth ] && local bimagewidth=$imagewidth
		local imageheight=`pnmfile $tmp_but_image|awk '{print $6}'`
		[ $bimageheight -lt $imageheight ] && local bimageheight=$imageheight
		local Number=$[ $Number + 1 ]
	done

	# Frame width 
	local active_x_offset=12
	local active_y_offset=12

	# Create buttons
	local size_xbutton=$[ $downbutton_imagewidth + $active_x_offset ]
	local size_ybutton=$[ $downbutton_imageheight + $active_y_offset ]
	nice -n $PRIO ppmmake $DVDBUTTONCOLOR   $size_xbutton $size_ybutton >$downmbutton || ExitError
        nice -n $PRIO ppmmake '#ffffff'         $downbutton_imagewidth $downbutton_imageheight >$sabutton || ExitError
        put_file $downmbutton $[ $active_x_offset / 2 ] $[ $active_y_offset / 2 ] $sabutton || ExitError

	local size_xbutton=$[ $upbutton_imagewidth + $active_x_offset ]
	local size_ybutton=$[ $upbutton_imageheight + $active_y_offset ]
	nice -n $PRIO ppmmake $DVDBUTTONCOLOR   $size_xbutton $size_ybutton >$upmbutton || ExitError
        nice -n $PRIO ppmmake '#ffffff'         $upbutton_imagewidth $upbutton_imageheight >$sabutton || ExitError
        put_file $upmbutton $[ $active_x_offset / 2 ] $[ $active_y_offset / 2 ] $sabutton || ExitError

	local left_offset=80
	local right_offset=80
	local upper_offset=45
	local lower_offset=50
	local frame_offset=$[ $active_y_offset * 3 ]

	local entryx=$[ $left_offset + $bimagewidth ]
	#NOTUSED# local entryy=$[ $upper_offset ]
	local deltax=$[ $bimagewidth + $active_x_offset + 2 ]
	local deltay=$[ $bimageheight + $frame_offset ]

	# Remove old contents
	nice -n $PRIO rm -f ${UniqueTempDIR}/preview/*/*

	## Create text pictures per entry
	local x1=$right_offset
	local y1=$upper_offset
	local Number=1
	until [ $Number -gt $DVDMENU_ENTRY_MAX ]
	do
		local Page=$[ ($Number - 1) / $menu_images_in_col + 1 ]

	        [ "$VERBOSE" = "yes" ] && echo "Create title menu text picture (page=$Page title=$Number)"

		if [ ! -d ${UniqueTempDIR}/preview/${Page} ]
		then
			mkdir ${UniqueTempDIR}/preview/${Page}
			local status=$?
			[ $status -ne 0 ] && Exit
		fi

		if [ ! -f ${UniqueTempDIR}/preview/${Page}/text.ppm ]
		then
			# Create empty black picture
			nice -n $PRIO ppmmake '#000000' $DVDNORM_XRES $DVDNORM_YRES >${UniqueTempDIR}/preview/${Page}/text.ppm || ExitError
			nice -n $PRIO ppmmake '#000000' $DVDNORM_XRES $DVDNORM_YRES | nice -n $PRIO ppmtopgm >${UniqueTempDIR}/preview/${Page}/text_alpha.pgm || ExitError
		fi

		local Titel="`echo "${Record[Number]}"|cut -c -100`"
		local STitel="`echo "${SubTitel[Number]}"|cut -c -24`"

		# Calculate length of record
		local frames=`cat ${UniqueDir[Number]}/FRAMES.txt`
		# TODO: fix NTSC FIXME: where to get the information
		local seconds=$[ ( $frames + 24 ) / 25 ]
		local minutes=$[ ( $seconds + 59 ) / 60 ]

		local ytext_offset=0

		# Subtitle (optional)
		if [ ! -z "${SubTitel[Number]}" -a "$DVD_DISPLAY_SUBTITLE" = "yes" ]
		then
			local fontsize=`echo $font_title|cut -f2 -d '/'`
			# Create text picture
			text_to_pnm ${UniqueTempDIR}/preview/${Page}/subtitle-${Number}.ppm ${UniqueTempDIR}/preview/${Page}/subtitle-${Number}_alpha.pgm \
				$font_title  "$DVDMAINSUBTITLECOLFG" "$DVDCOLBG" \
				"$STitel" \
				-w $[ $DVDNORM_XRES - $bimagewidth - 150 ] \
				-s $DVDBUTTONDIR/subtitlestyle || ExitError

			# Merge pictures
			nice -n $PRIO pnmpaste ${UniqueTempDIR}/preview/${Page}/subtitle-${Number}.ppm \
				$[ $x1 + $deltax ] $[ $y1 + $ytext_offset ] \
				${UniqueTempDIR}/preview/${Page}/text.ppm >${UniqueTempDIR}/preview/${Page}/tmp.ppm || ExitError

			nice -n $PRIO pnmpaste ${UniqueTempDIR}/preview/${Page}/subtitle-${Number}_alpha.pgm \
				$[ $x1 + $deltax ] $[ $y1 + $ytext_offset ] \
				${UniqueTempDIR}/preview/${Page}/text_alpha.pgm >${UniqueTempDIR}/preview/${Page}/tmp_alpha.pgm || ExitError

			nice -n $PRIO mv ${UniqueTempDIR}/preview/${Page}/tmp.ppm       ${UniqueTempDIR}/preview/${Page}/text.ppm || ExitError
			nice -n $PRIO mv ${UniqueTempDIR}/preview/${Page}/tmp_alpha.pgm ${UniqueTempDIR}/preview/${Page}/text_alpha.pgm || ExitError

			local ytext_offset=$[ $ytext_offset + $fontsize + $fontsize / 2 ]
		fi

		# Title
		local fontsize=`echo $font_title|cut -f2 -d '/'`
		if [ $ytext_offset -gt 0 ]; then
			local ytext_offset=$[ $ytext_offset + $fontsize / 2 ]
		fi

		# Create text picture
		text_to_pnm ${UniqueTempDIR}/preview/${Page}/title-${Number}.ppm ${UniqueTempDIR}/preview/${Page}/title-${Number}_alpha.pgm \
			$font_menu  "$DVDMAINTITLECOLFG" "$DVDCOLBG" \
			"$Titel    ($minutes ${DVD_MINUTESTEXT})" \
			-w $[ $DVDNORM_XRES - $bimagewidth - 150 ] \
			-s $DVDBUTTONDIR/titlestyle || ExitError

		# Merge pictures
		nice -n $PRIO pnmpaste ${UniqueTempDIR}/preview/${Page}/title-${Number}.ppm \
			$[ $x1 + $deltax + $fontsize ] $[ $y1 +  $ytext_offset ] \
			${UniqueTempDIR}/preview/${Page}/text.ppm >${UniqueTempDIR}/preview/${Page}/tmp.ppm || ExitError

		nice -n $PRIO pnmpaste ${UniqueTempDIR}/preview/${Page}/title-${Number}_alpha.pgm \
			$[ $x1 + $deltax + $fontsize ] $[ $y1 +  $ytext_offset ] \
			${UniqueTempDIR}/preview/${Page}/text_alpha.pgm >${UniqueTempDIR}/preview/${Page}/tmp_alpha.pgm || ExitError

		nice -n $PRIO mv ${UniqueTempDIR}/preview/${Page}/tmp.ppm       ${UniqueTempDIR}/preview/${Page}/text.ppm || ExitError
		nice -n $PRIO mv ${UniqueTempDIR}/preview/${Page}/tmp_alpha.pgm ${UniqueTempDIR}/preview/${Page}/text_alpha.pgm || ExitError

		local Number=$[ $Number + 1 ]
		local NPage=$[ ($Number - 1 ) / $menu_images_in_col + 1 ]
		if [ $Page -ne $NPage ]
		then
			local x1=$right_offset
			local y1=$upper_offset
		else
			local y1=$[ $y1 + $deltay ]
		fi
	done

	## Create title menu background per page
	local Page=1
	until [ $Page -gt $DVDMENU_PAGE_MAX ]
	do
	        [ "$VERBOSE" = "yes" ] && echo "Create title menu background (page=$Page)"

		local vy=$[ $DVDNORM_YRES - 50 ]

		if [ ! -f ${UniqueTempDIR}/preview/${Page}/action-background.ppm ]
		then
			ppmmake '#ffffff' $DVDNORM_XRES $DVDNORM_YRES > ${UniqueTempDIR}/preview/${Page}/action-background.ppm || ExitError
			local TitlesPage[Page]=1
		else
			local TitlesPage[Page]=$[ $TitlesPage[Page] + 1 ]
		fi

		local firstfrompage=$[ ($Page - 1) * $menu_images_in_col + 1 ]

		# Create page text
		if [ $DVDMENU_PAGE_MAX -gt 1 ]
		then
			if [ "$DVD_DISPLAY_PAGETEXT" = "yes" ]
			then
				# Display "page <page> / <pages>"

				local px=$[ $DVDNORM_XRES / 2 + $DVDNORM_XRES / 4 + 10 ]
				local py=$[ $DVDNORM_YRES - 80 ]

				# Create text picture
				text_to_pnm ${UniqueTempDIR}/preview/${Page}/page.ppm ${UniqueTempDIR}/preview/${Page}/page_alpha.pgm \
					"$font_info" "$DVDMAINPAGETEXTCOLFG" "$DVDCOLBG" \
					"$DVD_PAGETEXT ${Page} / $DVDMENU_PAGE_MAX" \
					-s $DVDBUTTONDIR/style || ExitError

				# Merge pictures
				nice -n $PRIO pnmpaste ${UniqueTempDIR}/preview/${Page}/page.ppm \
					$px $py \
					${UniqueTempDIR}/preview/${Page}/text.ppm >${UniqueTempDIR}/preview/${Page}/tmp.ppm || ExitError

				nice -n $PRIO pnmpaste ${UniqueTempDIR}/preview/${Page}/page_alpha.pgm \
					$px $py \
					${UniqueTempDIR}/preview/${Page}/text_alpha.pgm >${UniqueTempDIR}/preview/${Page}/tmp_alpha.pgm || ExitError

				nice -n $PRIO mv ${UniqueTempDIR}/preview/${Page}/tmp.ppm       ${UniqueTempDIR}/preview/${Page}/text.ppm || ExitError
				nice -n $PRIO mv ${UniqueTempDIR}/preview/${Page}/tmp_alpha.pgm ${UniqueTempDIR}/preview/${Page}/text_alpha.pgm || ExitError
			fi

			if [ "$DVD_PUTNUMBERTOBUTTONS" != "yes" -a "$DVD_USENUMBERFORTITLES" = "yes" ]
			then
				local fontsize=`echo $font_additional|cut -f2 -d '/'`
				local py=$[ $DVDNORM_YRES - $lower_offset - $downbutton_imageheight - $fontsize - 20 ] 

				if [ $Page -lt $DVDMENU_PAGE_MAX ]
				then
					# Display "<pageX> - <pageY>" for down (next) button (not on the last page)

					local FromTitle=$[ $Page * $menu_images_in_col + 1 ]
					local ToTitle=$DVDMENU_ENTRY_MAX
					if [ $FromTitle = $ToTitle ]
					then
						local text="$ToTitle"
					else
						local text="${FromTitle}-${ToTitle}"
					fi

                          		text_to_pnm ${UniqueTempDIR}/preview/${Page}/down.ppm ${UniqueTempDIR}/preview/${Page}/down_alpha.pgm \
						$font_additional  "$DVDBUTTONTEXTCOLFG" "$DVDCOLBG" \
						"$text" \
						-s $DVDBUTTONDIR/style || ExitError

					local down_imagewidth=`pnmfile ${UniqueTempDIR}/preview/${Page}/down.ppm | awk '{print $4}'`
					local px=$[ $DVDNORM_XRES / 2 - $downbutton_imagewidth / 2 - $down_imagewidth / 2 ]
					local px_down=$[ $DVDNORM_XRES / 2 ]

					# Merge pictures
					nice -n $PRIO pnmpaste ${UniqueTempDIR}/preview/${Page}/down.ppm \
						$px_down $py \
						${UniqueTempDIR}/preview/${Page}/text.ppm >${UniqueTempDIR}/preview/${Page}/tmp.ppm || ExitError

					nice -n $PRIO pnmpaste ${UniqueTempDIR}/preview/${Page}/down_alpha.pgm \
						$px_down $py \
						${UniqueTempDIR}/preview/${Page}/text_alpha.pgm >${UniqueTempDIR}/preview/${Page}/tmp_alpha.pgm || ExitError

					nice -n $PRIO mv ${UniqueTempDIR}/preview/${Page}/tmp.ppm \
						${UniqueTempDIR}/preview/${Page}/text.ppm || ExitError
					nice -n $PRIO mv ${UniqueTempDIR}/preview/${Page}/tmp_alpha.pgm \
						${UniqueTempDIR}/preview/${Page}/text_alpha.pgm || ExitError
				fi

				if [ $Page -gt 1 ]
				then
					# Display "<pageX> - <pageY>" for up (back) button

					local FromTitle=1
					local ToTitle=$[ ($Page - 1) * $menu_images_in_col ]
					if [ $FromTitle = $ToTitle ]
					then
						local text="$ToTitle"
					else
						local text="${FromTitle}-${ToTitle}"
					fi

                          		text_to_pnm ${UniqueTempDIR}/preview/${Page}/up.ppm ${UniqueTempDIR}/preview/${Page}/up_alpha.pgm \
						$font_additional  "$DVDBUTTONTEXTCOLFG" "$DVDCOLBG" \
						"$text" \
						-s $DVDBUTTONDIR/style || ExitError

					local up_imagewidth=`pnmfile ${UniqueTempDIR}/preview/${Page}/up.ppm | awk '{print $4}'`
					local px=$[ $DVDNORM_XRES / 2 + $upbutton_imagewidth + $upbutton_imagewidth / 2 - $up_imagewidth / 2 ]
					local px_up=$[ $DVDNORM_XRES / 2 + $upbutton_imagewidth + $upbutton_imagewidth ]

					# Merge pictures
					nice -n $PRIO pnmpaste ${UniqueTempDIR}/preview/${Page}/up.ppm \
						$px_up $py \
						${UniqueTempDIR}/preview/${Page}/text.ppm >${UniqueTempDIR}/preview/${Page}/tmp.ppm || ExitError

					nice -n $PRIO pnmpaste ${UniqueTempDIR}/preview/${Page}/up_alpha.pgm \
						$px_up $py \
						${UniqueTempDIR}/preview/${Page}/text_alpha.pgm >${UniqueTempDIR}/preview/${Page}/tmp_alpha.pgm || ExitError

					nice -n $PRIO mv ${UniqueTempDIR}/preview/${Page}/tmp.ppm \
						${UniqueTempDIR}/preview/${Page}/text.ppm || ExitError
					nice -n $PRIO mv ${UniqueTempDIR}/preview/${Page}/tmp_alpha.pgm \
						${UniqueTempDIR}/preview/${Page}/text_alpha.pgm || ExitError
				fi
			fi
		fi

		# Create frames
	        [ "$VERBOSE" = "yes" ] && echo "Create title menu animation frames (page=$Page)"
		local count=0

		[ "$DVD_USEVIDEOBACKGROUND" != "yes" ] && let DVDANIMFRAMES=${DVDPANIMFRAMES[Page]}
	        while [ $count -lt $DVDANIMFRAMES ]
	        do
			[ "$VERBOSE" = "yes" ] && printf "%05d (%05d)\r" $[ $count +1 ] $DVDANIMFRAMES

			local vx=$count
			[ $vx -gt $[ $DVDNORM_XRES - $LOGO_XSIZE - 10 - 30 ] ] && vx=$DVDNORM_XRES

			local tcount=`printf "%06d" $count`

			if [ "$DVD_USEVIDEOBACKGROUND" = "yes" ]
			then
				local menu_src=${UniqueDir[firstfrompage]}/mainvideo/mainvideo${tcount}.ppm
			else
				local menu_src=${UniqueTempDIR}/background.pnm
				#[ ! -f ${UniqueTempDIR}/preview/${Page}/background-${tcount}.ppm ] && cp $menu_src ${UniqueTempDIR}/preview/${Page}/background-${tcount}.ppm
				[ ! -f ${UniqueDir[firstfrompage]}/preview/${Page}/background-${tcount}.ppm ] && cp $menu_src ${UniqueDir[firstfrompage]}/preview/background-${tcount}.ppm
			fi

			if [ "$DVD_ANIMATEVERSION" = "yes" ]
			then
				if [ "$DVD_ANIMATELOGO" = "yes" -a -r "$DVD_ANIMATELOGO_FILE" ]; then
					# paste logo pict into menu pict | paste text pict (with alpha channel) >background-${tcount}.ppm
					nice -n $PRIO pnmpaste $DVD_ANIMATELOGO_FILE \
						$[ $vx + 30 ] $[ $YRES - 30 - $LOGO_YSIZE / 2 ] \
						$menu_src | nice -n $PRIO pnmcomp -xoff=$[ $vx + $LOGO_XSIZE + 10 + 30 ] -yoff=$[ $YRES - 40 ] -alpha=$version_main_alpha_pnm $version_main_pnm >${UniqueTempDIR}/preview/${Page}/tmp.ppm || ExitError
				else
					# paste version pict (with alpha channel) into menu pict >background-${tcount}.ppm
					nice -n $PRIO pnmcomp -xoff=$[ $vx + $LOGO_XSIZE + 10 + 30 ] -yoff=$[ $YRES - 40 ] -alpha=$version_main_alpha_pnm $version_main_pnm $menu_src >${UniqueTempDIR}/preview/${Page}/tmp.ppm || ExitError
				fi

				# Put title text picture into background picture
				nice -n $PRIO pnmcomp -alpha=${UniqueTempDIR}/preview/${Page}/text_alpha.pgm ${UniqueTempDIR}/preview/${Page}/text.ppm ${UniqueTempDIR}/preview/${Page}/tmp.ppm >${UniqueTempDIR}/preview/${Page}/background-${tcount}.ppm || ExitError

				nice -n $PRIO rm -f ${UniqueDir[Number]}/submenu/${Page}/tmp.ppm
			else
				# paste title text pict (with alpha channel) into menu pict >background-${tcount}.ppm
				nice -n $PRIO pnmcomp -alpha=${UniqueTempDIR}/preview/${Page}/text_alpha.pgm ${UniqueTempDIR}/preview/${Page}/text.ppm $menu_src >${UniqueTempDIR}/preview/${Page}/background-${tcount}.ppm || ExitError
			fi

			local count=$[ $count + 1 ]
		done
		[ "$VERBOSE" = "yes" ] && echo

		local Page=$[ $Page + 1 ]
	done


	## Create preview pictures per entry
	local x1=$right_offset
	local y1=$upper_offset
	local Number=1
	until [ $Number -gt $DVDMENU_ENTRY_MAX ]
	do
		Page=`echo "($Number-1)/$menu_images_in_col+1"|bc`

		# Put preview pictures into title background
		[ "$VERBOSE" = "yes" ] && echo "Put title menu preview pictures (page=$Page entry=$Number)"

		local count=0
		while [ $count -lt $DVDANIMFRAMES ]
		do
			[ "$VERBOSE" = "yes" ] && printf "%05d (%05d)\r" $[ $count +1 ] $DVDANIMFRAMES

			local tcount=`printf "%06d" $count`
[ ! -f ${UniqueDir[Number]}/preview/frame${tcount}.ppm ] && cp ${UniqueDir[Number]}/preview/frame000000.ppm ${UniqueDir[Number]}/preview/frame${tcount}.ppm
		
			if [ "$DVD_PUTNUMBERTOTITLE" = "yes" ]
			then
				if [ $count -eq 0 ]; then
					# Create number picture
					text_to_pnm ${UniqueDir[Number]}/preview/number.ppm ${UniqueDir[Number]}/preview/number_alpha.ppm \
						"$font_info" "$DVDMAINNUMTITLECOLFG" "$DVDCOLBG" \
						"$Number" \
						-s $DVDBUTTONDIR/style || ExitError
				fi

				# paste number pict (with alpha channel) into preview pict | paste into background pict >${UniqueTempDIR}/preview/${Page}/background1-${tcount}.ppm
				nice -n $PRIO pnmcomp \
					-xoff=4 -yoff=2 \
					-alpha=${UniqueDir[Number]}/preview/number_alpha.ppm \
					${UniqueDir[Number]}/preview/number.ppm ${UniqueDir[Number]}/preview/frame${tcount}.ppm | nice -n $PRIO pnmpaste /dev/stdin \
						 $x1 $y1 \
						 ${UniqueTempDIR}/preview/${Page}/background-${tcount}.ppm >${UniqueTempDIR}/preview/${Page}/tmp.ppm || ExitError
			else
				# paste preview pict into background pict >${UniqueTempDIR}/preview/${Page}/background1-${tcount}.ppm
				nice -n $PRIO pnmpaste ${UniqueDir[Number]}/preview/frame${tcount}.ppm \
					$x1 $y1 \
					${UniqueTempDIR}/preview/${Page}/background-${tcount}.ppm >${UniqueTempDIR}/preview/${Page}/tmp.ppm || ExitError
			fi

			nice -n $PRIO mv ${UniqueTempDIR}/preview/${Page}/tmp.ppm ${UniqueTempDIR}/preview/${Page}/background-${tcount}.ppm || ExitError

			local count=$[ $count + 1 ]
		done
		[ "$VERBOSE" = "yes" ] && echo

		## Put Active Preview frames
		# Get size of preview frame
		local tmp_but_image="${UniqueDir[Number]}/preview/frame000000.ppm"
		local imagewidth=`pnmfile $tmp_but_image|awk '{print $4}'`
		local imageheight=`pnmfile $tmp_but_image|awk '{print $6}'`
		local size_xbutton=$[ $imagewidth + $active_x_offset ]
		local size_ybutton=$[ $imageheight + $active_y_offset ]
		# Create buttons
		nice -n $PRIO ppmmake $DVDBUTTONCOLOR $size_xbutton $size_ybutton >${UniqueTempDIR}/preview/${Page}/mbutton-${Number}.ppm || ExitError
		nice -n $PRIO ppmmake '#ffffff' $imagewidth $imageheight >${UniqueTempDIR}/preview/${Page}/sabutton-${Number}.ppm || ExitError
		# Create framed button
		put_file ${UniqueTempDIR}/preview/${Page}/mbutton-${Number}.ppm \
			$[ $active_x_offset / 2 ] $[ $active_y_offset / 2 ] \
			${UniqueTempDIR}/preview/${Page}/sabutton-${Number}.ppm || ExitError
		# Put framed button into active background picture
		put_file ${UniqueTempDIR}/preview/${Page}/action-background.ppm \
			$[ $x1 - $active_x_offset / 2 ] $[ $y1 - $active_y_offset / 2 ] \
			${UniqueTempDIR}/preview/${Page}/mbutton-${Number}.ppm || ExitError

		local Number=$[ $Number + 1 ]
		local NPage=$[ ($Number - 1 ) / $menu_images_in_col + 1 ]
		if [ $Page -ne $NPage ]
		then
			local x1=$right_offset
			local y1=$upper_offset
		else
			local y1=$[ $y1 + $deltay ]
		fi
	done

	## Put down/up (next/back) Buttons (only if more than 1 page)
	if [ $DVDMENU_PAGE_MAX -gt 1 ]
	then
		# Prepare buttons

		# Expect that all buttons have equal height
		local py=$[ $DVDNORM_YRES - $lower_offset - $upbutton_imageheight ] 

		local px_up=$[ $DVDNORM_XRES / 2 + $upbutton_imagewidth + $upbutton_imagewidth ]
		local px_down=$[ $DVDNORM_XRES / 2 ]
		local px=$[ $DVDNORM_XRES / 2 - $downbutton_imagewidth ]

		# Copy buttons per page
		local Page=1
		until [ $Page -gt $DVDMENU_PAGE_MAX ]
		do
			nice -n $PRIO cp $DVDBUTTONDIR/up-*.ppm \
				${UniqueTempDIR}/preview/${Page}
			local up_frames=`$LS -l $DVDBUTTONDIR/up-*.ppm|wc -l|awk '{print $1}'`

			nice -n $PRIO cp $DVDBUTTONDIR/down-*.ppm \
				${UniqueTempDIR}/preview/${Page}
			local down_frames=`$LS -l $DVDBUTTONDIR/down-*.ppm|wc -l|awk '{print $1}'`

			local count=0
			local ucount=0
			local dcount=0

			[ "$VERBOSE" = "yes" ] && echo "Put title menu buttons (page=$Page)"

			while [ $count -lt $DVDANIMFRAMES ]
			do
				[ "$VERBOSE" = "yes" ] && printf "%05d (%05d)\r" $[ $count +1 ] $DVDANIMFRAMES

				local tcount=`printf "%06d" $count`
				local utcount=`printf "%06d" $ucount`
				local dtcount=`printf "%06d" $dcount`

				if [ $Page -lt $DVDMENU_PAGE_MAX ]
				then
					# down (next) button
					if [ "$DVD_PUTNUMBERTOBUTTONS" = "yes" -a "$DVD_USENUMBERFORTITLES" = "yes" ]
					then
						if [ $count -lt $down_frames ]
						then
							# Put number into down button  
							local FromTitle=$[ $Page * $menu_images_in_col + 1 ]
							local ToTitle=$DVDMENU_ENTRY_MAX
							if [ $FromTitle = $ToTitle ]
							then
								local text="$ToTitle"
							else
								local text="${FromTitle}-${ToTitle}"
							fi

							put_text_just ${UniqueTempDIR}/preview/${Page}/down-${dtcount}.ppm \
								$font_additional  "$DVDBUTTONTEXTCOLFG" "$DVDCOLBG" \
								1 1 \
								"left" \
								"$text" \
								-s $DVDBUTTONDIR/style || ExitError
						fi
					fi

					put_file ${UniqueTempDIR}/preview/${Page}/background-${tcount}.ppm  \
						$px_down $py \
						${UniqueTempDIR}/preview/${Page}/down-${dtcount}.ppm || ExitError
				fi

				if [ $Page -gt 1 ]
				then
					# up (back) button
					if [ "$DVD_PUTNUMBERTOBUTTONS" = "yes" -a "$DVD_USENUMBERFORTITLES" = "yes" ]
					then
						if [ $count -lt $up_frames ]
						then
							# Put number into up button  
							local FromTitle=1
							local ToTitle=$[ ($Page - 1) * $menu_images_in_col ]
							if [ $FromTitle = $ToTitle ]
							then
								local text="$ToTitle"
							else
								local text="${FromTitle}-${ToTitle}"
							fi

							put_text_just ${UniqueTempDIR}/preview/${Page}/up-${utcount}.ppm \
								$font_additional  "$DVDBUTTONTEXTCOLFG" "$DVDCOLBG" \
								1 1 \
								"left" \
								"$text" \
								-s $DVDBUTTONDIR/style || ExitError
						fi
					fi

					put_file ${UniqueTempDIR}/preview/${Page}/background-${tcount}.ppm  \
						$px_up $py \
						${UniqueTempDIR}/preview/${Page}/up-${utcount}.ppm || ExitError
				fi

				local count=$[ $count + 1 ]
				local ucount=$[ $ucount + 1 ]
				local dcount=$[ $dcount + 1 ]
				[ $ucount -ge $up_frames ] && local ucount=0
				[ $dcount -ge $down_frames ] && local dcount=0
			done
			[ "$VERBOSE" = "yes" ] && echo

			# Put button in action background
			if [ $Page -lt $DVDMENU_PAGE_MAX ]
			then
				ButtonsMain=$[ $ButtonsMain + 1 ]
				ButtonsMainInfo[ButtonsMain]="jump titleset $ButtonsMain menu"
				put_file ${UniqueTempDIR}/preview/${Page}/action-background.ppm \
					$[ $px_down - $active_x_offset / 2 ] $[ $py - $active_y_offset / 2] \
					$downmbutton || ExitError
			fi

			if [ $Page -gt 1 ]
			then
				ButtonsMain=$[ $ButtonsMain + 1 ]
				ButtonsMainInfo[ButtonsMain]="jump titleset $ButtonsMain menu"
				put_file ${UniqueTempDIR}/preview/${Page}/action-background.ppm \
					$[ $px_up - $[ $active_x_offset/2 ] ] $[ $py - $[ $active_y_offset/2] ] \
					$upmbutton || ExitError
			fi

			local Page=$[ $Page + 1 ]
		done
	fi

	## Multiplex menu
	local Page=1
	until [ $Page -gt $DVDMENU_PAGE_MAX ]
	do
		[ "$VERBOSE" = "yes" ] && echo "Multiplex menu (page=$Page)"

		# Convert active background to PNG
		nice -n $PRIO pnmtopng -transparent '#ffffff' ${UniqueTempDIR}/preview/${Page}/action-background.ppm > ${UniqueTempDIR}/preview/${Page}/action-background.png  2>>$STDERR 

		# Create still image mainmenu movie
		nice -n $PRIO cat ${UniqueTempDIR}/preview/${Page}/background-*.ppm >${UniqueTempDIR}/preview/${Page}/mainmenu.ppm || ExitError
		# Convert still image mainmenu movie to m2v
		nice -n $PRIO ppmtoy4m -n $DVDANIMFRAMES $DVDNORM_PPMTOY4M -I t -L -r -v 0 $CHROMASUB ${UniqueTempDIR}/preview/${Page}/mainmenu.ppm | nice -n $PRIO mpeg2enc -q 2 -a 2 -n p -f 8 -v 0 -o ${UniqueTempDIR}/mainmenu-${Page}.m2v >>$STDOUT 2>>$STDERR || ExitError

		# Calculate duration of silence file
		case $DVDNORM in
		    "pal")
			local duration=$[ ( $DVDANIMFRAMES + 24 ) / 25 ]
			;;
		    "ntsc")
			local duration=$[ ( $DVDANIMFRAMES + 29 ) * 1001 / 30000 ]
			;;
		esac
		if [ $duration -lt 1 ]; then
			local duration=1
		fi

		if [ -z "$DVDMAINSILENCEFILE" ]
		then
			if [ ! -f ${UniqueTempDIR}/silence-${duration}s.mp2 ]
			then
				set -x
				[ "$VERBOSE" = "yes" ] && echo "INFO  : title menu mpg duration=${duration}s DVDANIMFRAMES=$DVDANIMFRAMES"
                		nice -n $PRIO $ARECORD -f dat -t wav -d ${duration} ${UniqueTempDIR}/silence-${duration}s.wav >>$STDOUT 2>>$STDERR || ExitError
				nice -n $PRIO $MP2ENC -r 48000 -o ${UniqueTempDIR}/silence-${duration}s.mp2 <${UniqueTempDIR}/silence-${duration}s.wav >>$STDOUT 2>>$STDERR || ExitError
			fi
			SILENCE=${UniqueTempDIR}/silence-${duration}s.mp2
		else
			SILENCE=$DVDMAINSILENCEFILE
		fi

		nice -n ${PRIO} $MPLEX -v 0 -f 8 -l $duration -o /dev/stdout ${UniqueTempDIR}/mainmenu-${Page}.m2v $SILENCE >${UniqueTempDIR}/mainmenu-${Page}.mpg || ExitError

		local Page=$[ $Page + 1 ]
	done
}
# End of do_titelmenu()

do_prepare_submenus() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_prepare_submenus"

	local Number=1
        until [ $Number -gt $DVDMENU_ENTRY_MAX ]
	do
		local subbackground_directory=${SourceDir[Number]}
		local submenu=${UniqueDir[Number]}/subbackground.pnm

		if [ -z "$DVDSUBBACKFILE" ]
		then
			if [ -r "$subbackground_directory/subbackground.pnm" ] 
			then
				nice -n $PRIO cp $subbackground_directory/subbackground.pnm $submenu
			fi
		else
			if [ -r "$subbackground_directory/subbackground.pnm" ]
			then
				nice -n $PRIO cp $subbackground_directory/subbackground.pnm $submenu
			else
				if [ -r "$DVDSUBBACKFILE" ]
				then
					nice -n $PRIO cp $DVDSUBBACKFILE $submenu
				fi
			fi
		fi

		if [ ! -f $submenu -o "$DVDSUBBACKFILE_USE" != "yes" ]
		then
			nice -n $PRIO ppmmake $DVDFILE_SUBBACKGROUND_COLOR $DVDNORM_XRES $DVDNORM_YRES >$submenu
		fi
    
		# Check resolution and correct
		local XRES=`pnmfile $submenu|awk '{print $4}'`
		local YRES=`pnmfile $submenu|awk '{print $6}'`
		if [ $XRES -ne $DVDNORM_XRES -o $YRES -ne $DVDNORM_YRES ]
		then
			nice -n $PRIO mv $submenu ${submenu}.old
			nice -n $PRIO pnmtile $DVDNORM_XRES $DVDNORM_YRES ${submenu}.old > $submenu || ExitError
			[ -f $submenu.old ] && $RM ${submenu}.old
		fi
    
		epg_pages[Number]=0
		if [ -s ${UniqueDir[Number]}/info.vdr ]
		then
			nice -n $PRIO cat ${UniqueDir[Number]}/info.vdr|grep "^D "|cut -c3- | nice -n $PRIO fold -w $DVD_EPGCHARSPERLINE -s >${UniqueDir[Number]}/suma.txt
		elif [ -s ${UniqueDir[Number]}/summary.vdr ]
		then
			nice -n $PRIO cat ${UniqueDir[Number]}/summary.vdr | nice -n $PRIO fold -w $DVD_EPGCHARSPERLINE -s >${UniqueDir[Number]}/suma.txt
		else
			echo "${Record[Number]}" >${UniqueDir[Number]}/suma.txt
		fi

		# Recode file if needed
		# get charset
		local charset_suma="`file -b "${UniqueDir[Number]}/suma.txt" | awk '{ print $1 }'`"
		# check local charset
		#if ! echo $LANG | grep -q $charset_suma
		#then
			# recode required
			# adjust charset
			#if [ "$charset_suma" = "ISO-8859" ]
			#then
                        #       # force to ISO-8859-1
                        #       local charset_suma="${charset_suma}-1"
			#fi
			#LANG="UTF-8" nice -n $PRIO $RECODE "${charset_suma}..UTF-8" "${UniqueDir[Number]}/suma.txt" || ExitError
		#fi
 
		local LINES=`cat ${UniqueDir[Number]}/suma.txt | wc -l | awk '{print $1}'`
		local PNumber=0
		while [ $PNumber -le $LINES ]
		do
			local Zeilen=$[ $LINES - $PNumber ]
			if [ $Zeilen -gt 0 ]
			then
				epg_pages[Number]=$[ ${epg_pages[Number]} + 1 ]
				cat ${UniqueDir[Number]}/suma.txt | tail -n $[ $Zeilen+1 ] | head -n $DVD_EPGLINESPERPAGE >${UniqueDir[Number]}/epg_text-${epg_pages[Number]}
			fi
    
			local PNumber=$[ $PNumber + $DVD_EPGLINESPERPAGE ]
		done
		local Number=$[ $Number + 1 ]
	done
}

do_mainspumux() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_mainspumux"
        local Page=1
        until [ $Page -gt $DVDMENU_PAGE_MAX ]
        do
		cat << SPUEOF > ${UniqueTempDIR}/mainspumux-${Page}.xml
<?xml version="${XML_VERSION}" encoding="${XML_ENCODING}"?>
<subpictures>
  <stream>
    <spu 
         highlight="${UniqueTempDIR}/preview/${Page}/action-background.png"
         autooutline="infer"
         autoorder="rows"/>
  </stream>
</subpictures>
SPUEOF
		[ "$DVD_DEBUG" = "yes" ] && cat ${UniqueTempDIR}/mainspumux-${Page}.xml

		nice -n $PRIO $SPUMUX ${UniqueTempDIR}/mainspumux-${Page}.xml \
			< ${UniqueTempDIR}/mainmenu-${Page}.mpg \
			> ${UniqueMENUDIR}/spu-mainmenu-${Page}.mpg 2>>$STDERR || ExitError "spumux"
		local Page=$[ $Page + 1 ]
	done
}

do_subspumux() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_subspumux"
        local Number=1
        until [ $Number -gt $DVDMENU_ENTRY_MAX ]
        do
		local Page=1
		until [ $Page -gt ${epg_pages[Number]} ]
		do
			cat << SPUEOF > ${UniqueDir[Number]}/subspumux-${Page}.xml
<?xml version="${XML_VERSION}" encoding="${XML_ENCODING}"?>
<subpictures>
  <stream>
    <spu 
         highlight="${UniqueTempDIR}/action-${Number}-${Page}-subbackground.png"
         autooutline="infer"
         autoorder="rows"/>
  </stream>
</subpictures>
SPUEOF
			[ "$DVD_DEBUG" = "yes" ] && cat ${UniqueDir[Number]}/subspumux-${Page}.xml
 			nice -n $PRIO $SPUMUX ${UniqueDir[Number]}/subspumux-${Page}.xml \
				< ${UniqueDir[Number]}/submenu/submenu-${Page}.mpg \
				> ${UniqueMENUDIR}/Titel-${Number}/spu-submenu-${Page}.mpg 2>>$STDERR || ExitError "spumux"
			local Page=$[ $Page + 1 ]
		done
		local Number=$[ $Number + 1 ]
	done
}

do_xmlfile() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_xmlfile"

	let Menues=1
	let Titlesets=1
        let Number=1
        until [ $Number -gt $DVDMENU_ENTRY_MAX ]
        do
	    if [ $Titlesets -gt $menu_images_in_col ]
	    then
	          let Titlesets=1
	    	  let Menues=Menues+1
	    fi
	    let TitlesMenue[Menues]=Titlesets
	    let Titlesets=Titlesets+1
	    let Number=Number+1
	done
	if [ "$DVDDISABLEMENU" != "yes" ]
	then

	cat << TOPEOF > ${UniqueMENUDIR}/dvd.xml
<?xml version="${XML_VERSION}" encoding="${XML_ENCODING}"?>
<dvdauthor dest="${UniqueDVDDIR}" jumppad="1">
    <!-- The top level menu -->
    <vmgm>
TOPEOF
	if [ "$DVD_INIT" = "play" ]
	then
	    cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
      <fpc>jump title 1 chapter 1;</fpc>
TOPEOF
	fi

	cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
        <menus>
	    <video format="$DVDXMLNORM" aspect="$DVDXMLASPECT" />
	    <audio format="$DVDXMLAUDIO" channels="$DVDXMLCHANNELS" samplerate="$DVDXMLSAMPLERATE" />
TOPEOF
	let MenueNumber=1
	until [ $MenueNumber -gt $Menues ]
	do
	    if [ $MenueNumber -eq 1 ]
	    then
		    cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
	        <pgc entry="title">
TOPEOF
	    else
		cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
	        <pgc>
TOPEOF

	    fi
	    cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
                <pre> { g1=0;
	 	    if (g2 lt 1024) button=1024;
		    if (g2 gt 1024) button=g2;
		    button=1024;
		   }
	        </pre>
TOPEOF
	    cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
		  <vob file="${UniqueMENUDIR}/spu-mainmenu-${MenueNumber}.mpg" pause="$DVDMENUEPAUSE"></vob>
TOPEOF

	    let nrbutton=1
	    let i=1
	    until [ $i -gt ${TitlesMenue[MenueNumber]} ]
	    do
		ts=`echo "(${MenueNumber}-1)*${menu_images_in_col}+$i"|bc`
		if [ "$DVDDISABLESUBMENU" != "yes" ]
		then
		    button_info=`echo "jump titleset $ts menu"` 
		else
		    button_info=`echo "jump  title $ts chapter 1"`
		fi
		  cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
		  <button name="${nrbutton}"> { g2=button ; $button_info ; }</button>
TOPEOF
		let i=i+1
		let nrbutton=nrbutton+1
	    done

	    if [ $MenueNumber -lt $DVDMENU_PAGE_MAX -a ${TitlesMenue[MenueNumber]} -eq $menu_images_in_col ]
	    then
	      cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
		  <button name="$nrbutton">jump vmgm menu $[ MenueNumber + 1 ];</button>
TOPEOF
	      let nrbutton=nrbutton+1
            fi
	    if [ $MenueNumber -gt 1 ]
	    then
	      cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
		  <button name="$nrbutton">jump vmgm menu $[ MenueNumber - 1 ];</button>
TOPEOF
            fi
	    if [ "$DVD_MAINLOOP" != "no" ]
	    then
	        cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
                  <post>jump cell 1;</post>
TOPEOF
	    fi
	    cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
		</pgc>
TOPEOF
	    let MenueNumber=MenueNumber+1
	done
	cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
	</menus>
    </vmgm>
TOPEOF

        let Number=1
        until [ $Number -gt $DVDMENU_ENTRY_MAX ]
        do
	      let ThisMenue=$[ $[ $Number - 1 ] / menu_images_in_col + 1 ]
	      cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
	  <!-- The chapter menu and chapter for titleset $Number   -->
	  <titleset>
TOPEOF
if [ "$DVDDISABLESUBMENU" != "yes" ]
then
	      cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml

	      <menus>
    		<video format="$DVDXMLNORM" aspect="$DVDXMLASPECT" />
    		<audio format="$DVDXMLAUDIO" channels="$DVDXMLCHANNELS" samplerate="$DVDXMLSAMPLERATE" />
TOPEOF
	      let i=1
	      while [ $i -le ${epg_pages[Number]} ]
	      do
	          let nrbutton=1
	          cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
                  <pgc>
                  <pre> button=2048; </pre>
                    <vob file="${UniqueMENUDIR}/Titel-${Number}/spu-submenu-${i}.mpg" pause="$DVDSUBMENUPAUSE"></vob>
                    <button name="$nrbutton">jump vmgm menu $ThisMenue;</button>
                    <button name="$[ $nrbutton+1 ]">jump title 1 chapter 1;</button>
TOPEOF
		  let nrbutton=nrbutton+2

	          if [ $i -eq 1 -a ${epg_pages[Number]} -gt 1 ]
	          then
	            cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
	            <button name="$nrbutton">jump menu $[ i + 1 ];</button>
TOPEOF
		  let nrbutton=nrbutton+1
	          elif [ $i -gt 1 -a $i -lt ${epg_pages[Number]} ]
	          then
	            cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
	            <button name="$nrbutton">jump menu $[ i - 1 ];</button>
	            <button name="$[ $nrbutton+1 ]">jump menu $[ i + 1 ];</button>
TOPEOF
		  let nrbutton=nrbutton+2
	          elif [ $i -eq ${epg_pages[Number]} -a ${epg_pages[Number]} -gt 1 ]
	          then
	            cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
	            <button name="$nrbutton">jump menu $[ i - 1 ];</button>
TOPEOF
		    let nrbutton=nrbutton+1
	          fi
	          cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
                    <post>jump cell 1;</post>
                  </pgc>
TOPEOF
		  let i=i+1
	      done
	      cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
                </menus>

TOPEOF
else
	      cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
	      <menus />
TOPEOF
fi
	      cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
              <titles>
                <video format="${DVDNORMTitle[Number]}" aspect="${DVDASPECTTitle[Number]}" />
TOPEOF
	      let AStream=1
	      while [ $AStream -le ${DVDAUDIOSTREAMS[Number]} ]
	      do
		  audiofield=`echo ${DVDAUDIOTitle[Number]}|cut -f $AStream -d ' '`
		  langfield=`echo ${DVDLANGTitle[Number]}|cut -f $AStream -d ' '`
	          cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
                <audio format="$audiofield" lang="$langfield" />
TOPEOF
	          let AStream=AStream+1
	      done

                let SubtitleStream=1
		while [ $SubtitleStream -le ${DVDSUBTITLESTREAMS[Number]} ]
		do
			langfield=`echo ${DVDSUBTITLELANG[Number]}|cut -f $SubtitleStream -d ' '`

			cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
			<subpicture lang="$langfield" />
TOPEOF
			let SubtitleStream=SubtitleStream+1
		done

	      let ntbutton=1
	      cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
                <pgc>
                  <vob file="${UniqueMENUDIR}/Titel-${Number}/mplex.mpg" chapters="${Chapters[Number]}" pause="$DVDTITELPAUSE"></vob>
TOPEOF
	      if [ "$DVD_POST" = "menu" ]
	      then
	          post=`echo "call vmgm menu $ThisMenue;"` 
	      elif [ "$DVD_POST" = "loop" ]
	      then
		  post=`echo "jump  titleset ${Number} title 1;"`
	      else
		  let ts=Number+1
		  [ $ts -gt $DVDMENU_ENTRY_MAX ] && let ts=1
		  post=`echo "jump  titleset ${ts} title 1;"`
	      fi
	      cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
                  <post>${post}</post>
                </pgc>
              </titles>
            </titleset>
TOPEOF

	      let Number=Number+1
	 done
	 cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
</dvdauthor>
TOPEOF
	else
		echo "generate simple xml without menus"
	cat << TOPEOF > ${UniqueMENUDIR}/dvd.xml
<?xml version="${XML_VERSION}" encoding="${XML_ENCODING}"?>
<dvdauthor dest="${UniqueDVDDIR}">
    <!-- The top level menu -->
    <vmgm>
        <menus>
        </menus>
    </vmgm>
TOPEOF
        let Number=1
        until [ $Number -gt $DVDMENU_ENTRY_MAX ]
        do
	      cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
	  <!-- The chapter menu and chapter for titleset $Number   -->
	  <titleset>
	      <menus>
	      </menus>
              <titles>
                <video format="${DVDNORMTitle[Number]}" aspect="${DVDASPECTTitle[Number]}" />
TOPEOF
	      let AStream=1
	      while [ $AStream -le ${DVDAUDIOSTREAMS[Number]} ]
	      do
		  audiofield=`echo ${DVDAUDIOTitle[Number]}|cut -f $AStream -d ' '`
		  langfield=`echo ${DVDLANGTitle[Number]}|cut -f $AStream -d ' '`
	          cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
                <audio format="$audiofield" lang="$langfield" />
TOPEOF
	          let AStream=AStream+1
	      done

	      let ntbutton=1
	      cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
                <pgc>
                  <vob file="${UniqueMENUDIR}/Titel-${Number}/mplex.mpg" chapters="${Chapters[Number]}" pause="$DVDTITELPAUSE"></vob>
                </pgc>
              </titles>
            </titleset>
TOPEOF
	      let Number=Number+1
	 done
	 cat << TOPEOF >> ${UniqueMENUDIR}/dvd.xml
</dvdauthor>
TOPEOF
	fi
}

do_final() {
	[ "$DVD_DEBUG" = "yes" -o "$VERBOSE" = "yes" ] && echo "Enter do_final"
	printf "\t`date +"%T"` : Parts from List : \n"
	local part=1
	for i in $CMDLIN
	do
		printf "\t\t %5d) %s\n" $part "$i"
		local part=$[ $part + 1 ]
	done
	$RM -rf ${UniqueTempDIR}
	printf "\t`date +"%T"` : completed\n"
	cp $NewJobs $NewJobs.$$
	grep -x -v "$CMDLIN" $NewJobs.$$ > $NewJobs 
	$RM $NewJobs.$$
}

# END MENUES

[ -d $DVD_DESTDIR ] || mkdir -p $DVD_DESTDIR  || ExitError
[ -d $LTEMPDIR ] || mkdir -p $LTEMPDIR || ExitError

if [ -z "$SHORTCIRCUIT_PID" ]; then
	# Create shortcircuit file
	echo "SHORTCIRCUIT_PID=$$" >$LTEMPDIR/SHORTCIRCUIT.txt
fi

if [ ! -r $VDRCONVERTDIR/bin/helperfunctions.sh ]; then
	echo "FATAL : can't read: $VDRCONVERTDIR/bin/helperfunctions.sh"
	exit 1
fi

. $VDRCONVERTDIR/bin/helperfunctions.sh

## Main
if [ -w ${LTEMPDIR} -a -w ${DVD_DESTDIR} ]
then
	NLLINES=`cat $VCOQUEUEDIR/${JOBFIL}|nl|wc -l|awk '{ print $1 }'`
	ALINES=`cat $VCOQUEUEDIR/${JOBFIL}|wc -l|awk '{ print $1 }'`

	if [ $ALINES -ge 1 ]
	then
		if [ -z "$SHORTCIRCUIT_PID" ]; then
			# Regular call
			TEMPJOBFILE=/$LTEMPDIR/${JOBFIL}.u.$$
		else
			# Shortcircuit call
			TEMPJOBFILE=/$LTEMPDIR/${JOBFIL}.u.$SHORTCIRCUIT_PID
		fi

		> $TEMPJOBFILE
		printf "%s\n" "`cat $VCOQUEUEDIR/${JOBFIL}|head -n 1`" > $NewJobs
		LINE=2
		while [ $LINE -le $ALINES ]
		do
			printf "%s\n" "`cat $VCOQUEUEDIR/${JOBFIL}|head -n $LINE|tail -n 1`" >> $TEMPJOBFILE
			LINE=$[ $LINE + 1 ]
		done
		[ $NLLINES -gt $ALINES ] && printf "%s" "`cat $VCOQUEUEDIR/${JOBFIL}|tail -n 1`" >> $TEMPJOBFILE
		nice -n $PRIO cp $TEMPJOBFILE $VCOQUEUEDIR/${JOBFIL} && $RM $TEMPJOBFILE

		while [ `cat $NewJobs|grep ^${VDRROOT}|wc -l` -gt 0 ]
		do

			if [ -z "$SHORTCIRCUIT_PID" ]
			then
				CMDLIN=`head -n 1 $NewJobs`   # Job auslesen
				# Store CMDLIN in SHORTCIRCUIT.txt
				echo "CMDLIN=\"$CMDLIN\"" >>$LTEMPDIR/SHORTCIRCUIT.txt
			else
				# Reread SHORTCIRCUIT.txt to fill CMDLI
				source $LTEMPDIR/SHORTCIRCUIT.txt
			fi

			if [ ! -z "$CMDLIN" ]
			then
				do_init
				if [ -z "$SHORTCIRCUIT_PID" ]
				then
					do_demux
				fi

				do_prepare_titelmenu
				do_mplex
				do_init_chapters
				if [ "$DVDDISABLEMENU" != "yes" ]
				then
					do_frame_mainvideo
					do_framepreview
					do_titelmenu
					do_mainspumux

					if [ "$DVDDISABLESUBMENU" != "yes" ]
					then
						do_frame_subvideo
						do_prepare_submenus
						do_submenus
						do_subspumux
					fi

					#do_frame_chapters
					#do_prepare_chapters
					#do_chapters
					#do_chapterspumux
				fi

				#do_language_menu

				do_xmlfile
				do_label
				do_checkshrink
				do_dvdauthor
				do_mkisofs
				do_final
			fi
		done
      
		$RM $NewJobs
		if [ "$DVD_MOVELOG" = "yes" ]
		then
			cat $LOGDIR/$JOBFIL.log | strings > ${first}/`basename ${Image}`.log
			[ -f ${first}/`basename ${Image}`.log ] && < /dev/null > $LOGDIR/$JOBFIL.log
			printf "\t\t`date` : Last log moved to %s.log\n" "${first}/`basename %s${Image}`"
			$COMPRESS ${first}/`basename ${Image}`.log 
		fi
	fi
fi

printf "`date +"%d-%m-%2Y %T"` : Session %s end\n" "$0"
Exit
