#!/bin/bash
#
#   dvdwizard - create a DVD image from mpeg stream(s) with
#               chapters and menus without further user interaction
#
#   Copyright (C) 2004-2008 W. Wershofen <itconsult at wershofen.de>
#   Copyright (C) 2009 Joo Martin <joomart2009 at users.sf.net>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This package is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#   2004-01-26  Wolfgang Wershofen
#               * initial version
#   2004-09-22  Stefan Becker
#               * pass Subpicture Information to dvdauthor (-s)
#               * pass Palette File to dvdauthor (-P)
#               * Widescreen-Options (-WS) and for titlesets (-ws)
#   2004-09-22  Wolfgang Wershofen
#               * change allocation of language and audiotracks
#               * add new option --audio-seq
#   2006-08-31  Wolfgang Wershofen
#               * change location of temporary files (make use of $TMPDIR)
#               * now title will only be printed if -T is explicitly used,
#				  so --notitle is obsolete
#               * introduce system-wide config-file /etc/dvdwizard.conf
#               * now config file is now mandatory
#   2009-01-17  Joo Martin
#               * add aspect ratio option (-ar) to correct detected value
#               * add pause option (-W)
#   2009-06-23  Joo Martin
#               * add debug option (-D) for testings
#               * check video aspect ratio for menu background image
#               * check whether TVSIZE is inside range
#   2009-09-10  Joo Martin
#               * check used audio codec (should be ac3 or mp2)
#   2009-12-11  Joo Martin
#               * while restart use existing chapter screenshots
#
# -------------------------------------------------------------------------

# We need some sub-routines from dvdwizardrc
# This file must reside in the same directory as the called script
# Should maybe go into a directory like /usr/local/share/dvdwizard
#
rcfile="@DW_RC_FILE@"
if [ -e "$rcfile" -a -r "$rcfile" ]; then
	. "$rcfile"
else
	echo "dvdwizardrc not found or is not readable. Aborting" >&2
    exit 1
fi

# ------------------------------
# Open console logging lines
#
conslog()
{
	echo "${DW_NAME} - version ${DW_VERSION3}  ${DW_DATE}"
	echo "Send bugs to ${BUGADDR}"
	echo "Copyright ${COPYNAME}"
	echo "${COPYLINE1}"
	echo "${COPYLINE2}"
}

# ------------------------------
# Function specification
#
usage()
{
	cat <<EOF

syntax:	`basename $0` [options] mpeg-file(s)
	`basename $0` -h|--help
	`basename $0` -v|--version

general processing:
-------------------
-C  | --config-file	filename of dvdwizard-configuration file.
			[~/.dvdwizard/dvdwizard.conf]
-o  | --output		Path where the final DVD will be stored.
			[\$BASEDIR/dvd]
-x  | --xml		Print dvdauthor XML-specs into this file.
			[\$BASEDIR/dvdwizard.xml]
-l  | --logfile		Write Log-Messages to this file. 
			[\$BASEDIR/dvdwizard.log]
-y  | --yes		Allow all target directories to be overwritten.
-D  | --debug		Logging with console debug infos.
-h  | --help   		print this lot out.
-v  | --version		print version and exit.
--restart <step>	Do not start from beginning but from step.
			Step may be dvdcpics, mk_vmgm, mk_vtsm, author.
--xmlonly		Do not author final DVD, only create menus and xml
			and remove temporary DVD structure.
--xmlkeep		Like --xmlonly, but keep temporary DVD structure.

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

DVD-specific options:
---------------------
-T  | --vmgm <string>	Titlestring for the whole DVD; if not specified
			no title will be printed on the main menu.
-N  | --tvnorm		TV-Norm to use <PAL|NTSC>         [PAL]
-V  | --tvsize		Visible Area on TV-Screen <XxY>   [660x530]
-M  | --menu		Language to use in menu items.    [en]
			Strings are defined in config file.
-WS         		Widescreen-Option (nopanscan or noletterbox) 
			for whole DVD may be overwritten by -ws for a 
			specific titleset.
-P  | --palette  	Name of palette File, needed i. E. for subpictures.
-A  | --Audio		Language for audiotracks. <lang1,lang2,...,langn> 
			[en]; languages are applied to audiotracks in order they 
			appear in the mpeg stream. Applies to all titlesets on the 
			DVD, may be overwritten by -a for a specific titleset.
-I  | --intro		MPEG-File to be played when inserting the DVD in 
			the player.
-L  | --loop		Playback mode of the DVD. Possible values:
			 0 - return to vmgm menu after each title,
			-1 - display vmgm menu before the first and after 
			     the last title,
			-2 - display vmgm menu only before first title and 
			     loop all titles endlessly,
			1...9 - suppress vmgm menu and loop all titles 
			     endlessly, starting from specified title.
-MS | --vmgmsound	Soundfile to be used as background sound for all 
			menus (may be overwritten for specific titlesets with
			-ms|--vtsmsound). If empty, a silent audio track will be
			produced. Can be any format, ffmpeg recognizes and will be
			converted to ac3, if neccessary.
-W  | --pause		Wait a number of seconds as pause at the end of each
			titleset.

Title-specific options:
-----------------------
-t  | --vts		Create a new titleset on the DVD with the subsequent
			options and mpeg-files.
			-t must be followed by a filename or a string or the
			word "auto"; "auto" determines title-string from 
			filename of first mpeg-file, if -t is followed by an
			existing filename, that file is considered to be the
			first mpeg in this titleset, else the string is used
			as movie title for this titleset.
-c  | --chapters	Chapter-Specification <0|file|timecodes|interval> 
			[300]; 0 means no chaptering except for different 
			mpeg-files.
-b  | --vtsmbg		Background picture for all menus concerning this 
			titleset.
-ar | --aspect		Aspect-Ratio-Option for correcting (4:3 or 16:9).
-ws             	Widescreen-Option (nopanscan or noletterbox) for 
			this titleset.
-a  | --audio		Language for audiotrack of this titleset. [en]
-s  | --subpic   	pass subpicture information to dvdauthor.
                	This is a string like "en" for english, "de" for 
                	german etc.
                	More Languages by comma separation, i.e. "-s de,en".
                	Each language may be followed by an optional "+hi" 
                	to indicate a subpicture track for hearing impaired,
                	i.e. "-s de,de+hi".
-i  | --info <file>  	points to a text file containing description and the
			like for the movie.
-ms | --vtsmsound	see -MS, but only applies to this titleset.

Note: Every new "-t" creates a new titleset on the DVD. Subsequent options 
  -c, -b, -a, -ar and mpeg-file(s) apply only to that titleset. To create 
  a DVD with two titlesets and a special background, use for example:

  dvdwizard -t auto -c 30 title1.mpg -t auto -b bckgrnd.ppm title2.mpg

EOF
	exit 1
}

# ------------------------------
# Check, if all Parms are valid
#
checkParms()
{
	mk_check_dir "$BASEDIR" "OLD" "\$BASEDIR"
	[ -z $restart ] && mk_check_dir "$DESTDIR" "NEW" "\$DESTDIR -o|--output"
	mk_check_file "$XMLFILE" "NEW" "\$XMLFILE -x|--xml"
	mk_check_file "$LOGFILE" "NEW" "\$LOGFILE -l|--logfile"
	mk_check_file "$CMDFILE" "NEW" "\$CMDFILE"

	#
	# Open console Log
	#
	conslog
	IM_ADDINFO=''
	if [ "$IM_VERSION4" \> "6.5.8-3" ]; then
		IM_ADDINFO=' (NOT TESTED with ImageMagick > 6.5.8-3)'
	fi
	echo "Using ImageMagick ${IM_VERSION4} ${IM_ADDINFO}"
	echo ' '

	#
	# Open file Log
	#
	cat <<EOF >> "$LOGFILE"
Logfile from ${DW_NAME} ${DW_VERSION3} ${DW_DATE} run at `date +%d.%m.%Y\ -\ %H:%M:%S`
Using ImageMagick ${IM_VERSION4} ${IM_ADDINFO}
DVDwizard invoked with  `basename $0` "$allargs"
Default processing options read from $confFile
-----------------------------------------------------------------
EOF

	#
	# Check input files
	#
	[ ! -z "$PALETTE" ] && mk_check_file "$PALETTE" "OLD" "\$PALETTE -P|--palette"
	[ ! -z "$INTROMPG" ] && mk_check_file "$INTROMPG" "OLD" "\$INTROMPG -I|--intro"
	[ ! -z "$MENUSOUND" ] && mk_check_file "$MENUSOUND" "OLD" "\$MENUSOUND -MS|--vmgmsound"

	for i in $(seq 1 $vts); do
		eval vtsbg=\$VTSMBG_$i
		[ ! -z "$vtsbg" ] && mk_check_file "$vtsbg" "OLD" "\$vtsbg -b|--vtsmbg for titleset #$i"
		eval vtsmsound=\$VTSMSOUND_$i
		[ ! -z "$vtsmsound" ] && mk_check_file "$vtsmsound" "OLD" "\$vtsmsound -ms|--vtsmsound for titleset #$i"
		eval fcount=\$VTSM_"$i"_FILES
		if [ $fcount -eq 0 ]; then
			echo "No input files specified for titleset $i. Aborting"
			echo "See $thisscript -h for more infos"
			exit 1
		fi >&2

		for j in $(seq 1 $fcount); do
			eval mk_check_file \"\$VTSM_"$i"_FILE_$j\" "OLD" "MPEG #$j for titleset #$i"
		done
		eval probeFile=\"\$VTSM_${i}_FILE_1\"
		audiotracks=$(nice -n $NICE mpgprobe "$probeFile" | grep Audio: | awk -F: '{print $2}') || error_out
		if [ $(echo $audiotracks | grep -c "0x0") -gt 0 ]; then
			echo "*** Warning: Unsupported codec for audio stream: $audiotracks"; echo ""
		fi
		acount=$(echo "$audiotracks" | wc -w)
		if [ "$acount" -eq 0 ]; then
			echo "*** Warning: Cannot determine audio tracks for title $i."
		fi
		# read all attributs of the specified video stream
		vattribs=$(nice -n $NICE mpgprobe "$probeFile" | grep Video:) || error_out
		vres=$(echo "$vattribs" | cut -d' ' -f1 | cut -d':' -f2)
		if [ -z "$vres" ]; then
			echo "*** Warning: Cannot determine video resolution for title $i."
		fi
		vratio=$(echo "$vattribs" | cut -d' ' -f2)
		if [ -z "$vratio" ];then
			echo "*** Warning: Cannot determine aspect ratio for title $i."
			echo "*** .......: Assuming $THUMBRATIO for chapter thumbs."
		fi
		eval VTSM_${i}_ATRACKS=\"\$audiotracks\"
		eval VTSM_${i}_ACOUNT=\"\$acount\"
		eval VTSM_${i}_VRES=\$vres
		eval VTSM_${i}_VRATIO=\$vratio
		eval vtsinfo=\$VTSMINFO_${i}
		[ ! -z "$vtsinfo" ] && mk_check_file "$vtsinfo" "OLD" "\$vtsinfo -i|--info"
	done

	#
	# Let's handle the title(s) of the DVD
	#
	for i in $(seq 1 $vts); do
		eval tstring=\"\$VTSTITLE_${i}\"
		if [ "$(echo "$tstring" | tr a-z A-Z)" == "AUTO" ]; then
			eval vtstitle=\"\$VTSM_${i}_FILE_1\"
			tstring=`nice -n $NICE dvdtguess "$vtstitle"`
		fi
		eval vratio=\"\$VTSM_${i}_VRATIO\"
		echo -e "Title #${i}: ${tstring} \t (${vratio})"
		eval VTSTITLE_${i}=\"\${tstring}\"
	done
	if [ -z "$VMGMTITLE" ]; then
		VMGMTITLE=$VTSTITLE_1
		echo "DVD-Title: $VMGMTITLE"
	fi

	#
	# Check Playback-Mode
	#
	if ! let x=$LOOP+0 ; then
		if [ ! $LOOP -eq 0 ]; then
			echo "Playback mode $LOOP (-L|--loop \$LOOP) is not numeric"
			error_out
		fi
	fi
	if [ $LOOP -lt -2 -o $LOOP -gt $vts ]; then
		echo "Playback mode $LOOP (-L|--loop \$LOOP) invalid."
		echo "Must be between -2 and number of titles on dvd ($vts)"
		error_out
	fi

	#
	# Check Pause length
	#
	if ! let x=$PAUSE+0 ; then
		if [ ! $PAUSE -eq 0 ]; then
			echo "Pause time $PAUSE (-W|--pause \$PAUSE) is not numeric"
			error_out
		fi
	fi
	if [ $PAUSE -lt 0 -o $PAUSE -gt 120 ]; then
		echo "Pause time $PAUSE (-W|--pause \$PAUSE) invalid."
		echo "Must be between 0 and 120 seconds!"
		error_out
	fi

	#
	# Check TVSIZE is in the range
	#
	# default: PAL
	normX=720
	normY=576
	# alternative: NTSC
	[ "$TVNORM" == "NTSC" ] && normX=720
	[ "$TVNORM" == "NTSC" ] && normY=480
	TVWidth=$(echo "$TVSIZE" | cut -d'x' -f 1)
	TVHeight=$(echo "$TVSIZE" | cut -d'x' -f 2)
	let miniX="${normX}*2/3"
	let miniY="${normY}*2/3"
	if [ "${TVWidth}" \< "${miniX}" -o "${TVHeight}" \< "${miniY}" ]; then
		myWarn="Defined TVSIZE ${TVWidth}x${TVHeight} is to small, set to ${miniX}x${miniY}."
		echo "$myWarn"; echo "*** Warning: $myWarn" >> "$LOGFILE"
		TVWidth=$miniX; TVHeight=$miniY
	fi
	let maxiX="${normX}-14"
	let maxiY="${normY}-10"
	if [ "${TVWidth}" \> "${maxiX}" -o "${TVHeight}" \> "${maxiY}" ]; then
		myWarn="Defined TVSIZE ${TVWidth}x${TVHeight} is to large, set to ${maxiX}x${maxiY}."
		echo "$myWarn"; echo "*** Warning: $myWarn" >> "$LOGFILE"
		TVWidth=$maxiX; TVHeight=$maxiY
	fi
	TVSIZE="${TVWidth}x${TVHeight}"

	return 0
}

# ------------------------------
# Create Chapter-Pics
#
call_dvdcpics()
{
	echo -n Capturing Chapter-Screenshots from temporary DVD...
	cat <<EOF >> "$LOGFILE"
+-------------------------------------+
| Calling dvdcpics                    |
| Capture Screenshots from Chapters   |
+-------------------------------------+
EOF
	for i in $(seq 1 $vts); do
		echo "Capturing Chapters from Titleset $i" >> "$LOGFILE"
		eval fopt=\${VTSM_"$i"_VRES:+"-f "}
		mk_check_dir "$BASEDIR/cpics/VTS$i" "NEW" "\$BASEDIR/cpics/VTS$i"
		cmd="nice -n $NICE dvdcpics -b -i \"$DESTDIR\" -t $i -o \"$BASEDIR/cpics/VTS$i\" \$fopt \$VTSM_"$i"_VRES"
		[ ! -z $TVNORM ] && cmd="${cmd} -N $TVNORM"
		[ -e "$confFile" ] && cmd="${cmd} -C \"$confFile\""
		cmdecho=$(eval echo "$cmd")
		# debug logging
		[ ! -z $DEBUG ] && echo -e "\n$cmdecho"
		echo "$cmdecho" >> "$CMDFILE"
		eval $cmd >> "$LOGFILE" 2>&1 || error_out
		eval cshots=( $(ls -QS "$BASEDIR/cpics/VTS$i") )
		eval VTSM_PIC_$i=\"\$BASEDIR/cpics/VTS$i/\${cshots[0]}\"
	done
	echo "...done"

	return 0
}

# ------------------------------
# Use exiting Chapter-Pics
#
call_dvdcpics_upd()
{
	echo -n Use existing Chapter-Screenshots...
	cat <<EOF >> "$LOGFILE"
+-------------------------------------+
| Calling dvdcpics                    |
| Use existing Chapter-Screenshots    |
+-------------------------------------+
EOF
	for i in $(seq 1 $vts); do
		eval cshots=( $(ls -QS "$BASEDIR/cpics/VTS$i") )
		eval VTSM_PIC_$i=\"\$BASEDIR/cpics/VTS$i/\${cshots[0]}\"
	done
	echo "...done"

	return 0
}

# ------------------------------
# Create DVD-Main-Menu
#
call_mk_vmgm()
{
	echo -n "Building VMGM-Menu..."
	cat <<EOF >> "$LOGFILE"
+-------------------------------------+
| Calling mk_vmgm                     |
| Creating VMGM-Menu                  |
+-------------------------------------+
EOF

	#
	# If restarting, delete xml beyond the restart mark
	#
	restartmark="call_mk_vmgm"
	sed -i '/^<!-- '$restartmark' \/\/-->/,/\n$/d' "$XMLFILE"
	echo "<!-- $restartmark //-->" >> "$XMLFILE"

	#
	# Assemble the needed command
	#
	mk_check_dir "$BASEDIR/vmgm" "NEW" "\$BASEDIR/vmgm"
	cmd="nice -n $NICE mk_vmgm -o \"$BASEDIR/vmgm\" -x \"$XMLFILE\" -N $TVNORM -V $TVSIZE -M $MENU -L $LOOP -MS \"$MENUSOUND\" "
	[ -e "$confFile" ] && cmd="${cmd} -C \"$confFile\""
	[ "$NOTITLE" -eq 0 ] && cmd="${cmd} -T \"$VMGMTITLE\""
	[ ! -z "$INTROMPG" ] && cmd="${cmd} -I \"$INTROMPG\""

	for i in $(seq 1 $vts); do
		eval title=\"\$VTSTITLE_$i\"
		cmd="${cmd} -t \"$title\""
		eval bgpic=\"\$VTSMBG_$i\"
		[ -e "$bgpic" ] && pic="$bgpic" || eval pic=\"\$VTSM_PIC_$i\"
		cmd="${cmd} -b \"$pic\""
		eval vratio=\$VTSM_"$i"_VRATIO
		cmd="${cmd} -r \"$vratio\""
		eval vtsmsound=\"\$VTSMSOUND_$i\"
		[ -z "$vtsmsound" ] && vtsmsound="$MENUSOUND"
		cmd="${cmd} -ms \"$vtsmsound\""
		eval acount=\$VTSM_"$i"_ACOUNT
		[ "$acount" -gt 1 ] && cmd="${cmd} --hasaudio"
		eval subtracks=\"\$VTSMSUBS_"$i"\"
		[ ! -z "$subtracks" ] && cmd="${cmd} --hassubtitle"
		eval infotxt=\"\$VTSMINFO_"$i"\"
		[ ! -z "$infotxt" ] && cmd="${cmd} --hasinfo"
	done

	# debug logging
	[ ! -z "$DEBUG" ] && echo -e "\n$cmd"
	echo "$cmd" >> "$CMDFILE"
	eval $cmd >> "$LOGFILE" 2>&1 || error_out
	echo "...done"

	return 0
}

# ------------------------------
# Create the Titlesets
#
call_mk_vtsm()
{
  #
  # If restarting, delete xml beyond the restart mark
  #
  restartmark="call_mk_vtsm"
  sed -i '/^<!-- '$restartmark' \/\/-->/,/\n$/d' "$XMLFILE"
  echo "<!-- $restartmark //-->" >> "$XMLFILE"

  for title in $(seq 1 $vts); do
    echo "Creating Titleset #$title..."
    echo -e "\t<titleset>" >> "$XMLFILE"
    echo -e "\t\t<menus>" >> "$XMLFILE"

	#
	# Get audio characteristics of the title
	#
    echo -e "\tAssigning Languages to Audio-Tracks..." | tee -a "$LOGFILE"
    eval vtsaudio=\"\$VTSMAUDIO_${title}\"
    [ -z "$vtsaudio" ] && vtsaudio="$DVDAUDIO"
    eval audiotracks=\"\$VTSM_${title}_ATRACKS\"
    acount=$(echo "$audiotracks" | wc -w)
    audioparm=""
    langlist=$(echo "$vtsaudio" | tr ',' ' ')
    lcount=$(echo "$langlist" | wc -w)
	for i in $audiotracks; do
		eval langptr_$i=1
	done
    langptr_all=1
    disind=1
    alangs=""
    for i in $audiotracks; do
	    this_langptr="$langptr_all"
		alang=$(echo "$langlist" | cut -d' ' -f"$this_langptr" | tr [a-z] [A-Z])
		alangs="$alangs $alang"
		audioparm="${audioparm}${alang}+${i},"
		eval "language=\$"$alang
		[ -z "$language" ] && language="unknown"
		echo -e "\t$disind. audio-track ($i) will be assigned to language ${alang} ($language)" | tee -a "$LOGFILE"
		let "disind+=1"
		[ "$this_langptr" -lt "$lcount" ] && let "this_langptr+=1"
		langptr_all="$this_langptr"
    done
    audioparm="${audioparm%,}"
	eval subtracks=\"\$VTSMSUBS_"$title"\"
	eval infotxt=\"\$VTSMINFO_"$title"\"

	#
	# Create the vtsm-menu(s)
	#
	echo -en "\tBuilding VTSM-Menu(s)..."
	cat <<EOF >> "$LOGFILE"
+-------------------------------------+
| Calling mk_vtsm                     |
| Creating VTSM-Menu(s)               |
+-------------------------------------+
EOF
	#
	# First create the Chapter Selection Menu
	#
	mk_check_dir "$BASEDIR/vtsm/vts$title" "NEW" "\$BASEDIR/vtsm/vts$title"
	echo -n "Chapters..."
	# parameter for mk_vtsm
	parm="-t \"$title\" -o \"$BASEDIR/vtsm/vts$title\" -x \"$XMLFILE\" -N $TVNORM -V $TVSIZE -M $MENU"
	[ -e "$confFile" ] && parm="${parm} -C \"$confFile\""
	eval bgpic=\"\$VTSMBG_${title}\"
	[ -e "$bgpic" ] && pic="$bgpic" || eval pic=\"\$VTSM_PIC_${title}\"
	parm="${parm} -b \"$pic\""
	eval rparm=\"\$VTSM_${title}_VRATIO\"
	parm="${parm} -r \"${rparm}\""
	eval vtsmsound=\"\$VTSMSOUND_${title}\"
	[ -z "$vtsmsound" ] && vtsmsound="$MENUSOUND"
	parm="${parm} -ms \"$vtsmsound\""
	[ "$acount" -gt 1 ] && parm="${parm} --hasaudio"
	[ ! -z "$subtracks" ] && parm="${parm} --hassubtitle"
	[ ! -z "$infotxt" ] && parm="${parm} --hasinfo"
	# parameter for mk_vtsm_lang and mk_vtsm_info
	vtsparms="$parm"
	cmd="nice -n $NICE mk_vtsm ${parm}"
	cmd="${cmd} \"$BASEDIR/cpics/VTS$title/\"chapter*.jpg"
	# debug logging
	[ ! -z "$DEBUG" ] && echo -e "\n$cmd"
	echo "$cmd" >> "$CMDFILE"
	eval $cmd >> "$LOGFILE" 2>&1 || error_out
	#
	# If VTS has more than one Audio-Track, create Audio Track Selection Menu
	#
	if [ "$acount" -gt 1 ]; then
    	echo -n "Audio..."
		cmd="nice -n $NICE mk_vtsm_lang --audio ${vtsparms} $audioparm"
    	echo "$cmd" >> "$CMDFILE"
    	eval $cmd >> "$LOGFILE" 2>&1 || error_out
	fi
	#
	# If VTS has Subtitle tracks to choose...
	#
	if [ ! -z "$subtracks" ]; then
    	echo -n "Subtitles..."
		cmd="nice -n $NICE mk_vtsm_lang --subtitle ${vtsparms} $subtracks"
    	echo "$cmd" >> "$CMDFILE"
    	eval $cmd >> "$LOGFILE" 2>&1 || error_out
	fi
	#
	# If VTS has an Info Text to display
	#
	if [ ! -z "$infotxt" ]; then
    	echo -n "Info..."
		cmd="nice -n $NICE mk_vtsm_info ${vtsparms} $infotxt"
    	echo "$cmd" >> "$CMDFILE"
    	eval $cmd >> "$LOGFILE" 2>&1 || error_out
	fi

    echo -e "\t\t</menus>" >> "$XMLFILE"
    echo "...done"

	#
	# Now, create the title
	#
	echo -en "\tWriting titleset XML..."
	echo -e "\t\t<titles>" >> "$XMLFILE"
	# Video informations
	eval vres=\"\$VTSM_"$title"_VRES\"
	eval vratio=\"\$VTSM_"$title"_VRATIO\"
	# correcting aspect ratio
	eval vts_ar=\"\$VTSMAR_"$title"\"
	[ ! -z $vts_ar ] && vratio="$vts_ar"
	[ ! -z $DVD_WS ] && wscreen="widescreen=\"$DVD_WS\"" || wscreen=""
	eval vts_ws=\"\$VTSMWS_"$title"\"
	[ ! -z $vts_ws ] && wscreen="widescreen=\"$vts_ws\""
	echo -n -e "\t\t\t<video format=\"$TVNORM\"" >>"$XMLFILE"
	if [ -n "$vratio" ];then echo -n -e " aspect=\"$vratio\"" >>"$XMLFILE" ; fi
	if [ -n "$vres" ];then echo -n -e " resolution=\"$vres\"" >>"$XMLFILE" ; fi
	echo " $wscreen />" >> "$XMLFILE"
	# Audio informations
	for i in $alangs; do
		echo -e "\t\t\t<audio lang=\"$i\" />" >> "$XMLFILE"
	done
	# Subtitle informations
	if [ ! -z "$subtracks" ]; then
		for i in $(echo "$subtracks" | tr ',' ' '); do
			sublang=$(echo $i | cut -d'+' -f1)
			echo -e "\t\t\t<subpicture lang=\"$sublang\" />" >> "$XMLFILE"
		done
	fi
	[ ! -z $PALETTE ] && paltag="palette=\"$PALETTE\"" || paltag=""
    echo -e "\t\t\t<pgc $paltag pause=\"0\">" >> "$XMLFILE"
    echo -e "\t\t\t\t<pre> g1=9; </pre>" >> "$XMLFILE"

	#
	# Loop through MPEG-Files
	#
	eval cspec=\"\$CHAPTERSPEC_$title\"
	eval mpegfiles=\$VTSM_${title}_FILES
	for i in $(seq 1 $mpegfiles); do
    	eval mf=\"\$VTSM_${title}_FILE_$i\"
		eval chapters=\"\$VTSM_${title}_CHAPTERS_$i\"
		
		#
		# Recalculate Chapters if we have had a restart
		#
		if [ -z "$chapters" ]; then
			duration=$(ffmpeg -i $mf 2>&1 | grep Duration | cut -d' ' -f4 | cut -d'.' -f1)
			durHH=$(echo $duration | cut -d':' -f1)
			durMM=$(echo $duration | cut -d':' -f2)
			durSS=$(echo $duration | cut -d':' -f3)
			mpglen=$(echo "$durHH*3600+$durMM*60+$durSS+1" | bc)
		    chapters=$(nice -n $NICE chaptercheck -N $TVNORM -L $mpglen $cspec) || error_out
		fi
		[ $i -eq $mpegfiles ] && vobpause=$PAUSE || vobpause=0
        echo -e "\t\t\t\t<vob file=\"$mf\" chapters=\"$chapters\" pause=\"$vobpause\" />" >> "$XMLFILE"
 	done
 	if [ $title -lt $vts ]; then
 		vmgmreg="g5=g5+1"
 		[ $LOOP -eq 0 ] && loopreg="g8=0" || loopreg="g8=$(( $title+1 ))"
 	else
 		vmgmreg="g5=101"
 		[ $LOOP -eq -1 -o $LOOP -eq 0 ] && loopreg="g8=0" || loopreg="g8=1"
	fi
    echo -e "\t\t\t\t<post> { $vmgmreg; $loopreg; call vmgm menu entry title; } </post>" >> "$XMLFILE"
    echo -e "\t\t\t</pgc>"  >> "$XMLFILE"
    echo -e "\t\t</titles>"  >> "$XMLFILE"
    echo -e "\t</titleset>"  >> "$XMLFILE"
    echo -e "\t...done"
    echo "Finished Titleset #$title"
  done

  #
  # Create a last titleset for playing an intro movie if requested
  #
  if [ ! -z "$INTROMPG" ]; then
  cat << EOF >> "$XMLFILE"
        <titleset>
          <!-- Titleset for FirstPlayChain (Intro) --> 
          <titles>
            <pgc>
              <vob file="$INTROMPG" pause="$PAUSE" />
              <post> call vmgm menu entry title; </post>
            </pgc>
          </titles>
        </titleset>
EOF
  fi

  return 0
}

# ------------------------------
# Final Authoring of the DVD
#
call_author()
{
	#
	# If restarting, delete xml beyond the restart mark
	#
	restartmark="call_author"
	sed -i '/^<!-- '$restartmark' \/\/-->/,/\n$/d' "$XMLFILE"
	echo "<!-- $restartmark //-->" >> "$XMLFILE"

	#
	# Print xml trailer records
	#
	echo -n "Finishing XML creation..."
	echo "</dvdauthor>" >> "$XMLFILE"
	echo "<!-- xml-file creation ended at `date +%d.%m.%Y\ -\ %H:%M:%S` //-->" >> "$XMLFILE"
	echo "...done"

	#
	# Now author the final DVD
	#
	if [ "$XMLONLY" -eq 0 ]; then
		echo "Authoring DVD into $DESTDIR..."
		cat <<EOF >> "$LOGFILE"
+-------------------------------------+
| Calling dvdauthor                   |
| Final authoring of DVD              |
+-------------------------------------+
EOF
		[ -e "$DESTDIR" ] && rm -R "$DESTDIR"
		echo "nice -n $NICE dvdauthor -x \"$XMLFILE\"" >> "$CMDFILE"
		nice -n $NICE dvdauthor -x "$XMLFILE" >> "$LOGFILE" 2>&1  || error_out
		echo "...done"
	else
		echo -n "Only XML-file creation chosen. "
		if [ "$XMLONLY" -eq 1 ];then
		  echo -n "Removing"
		rm -R "$DESTDIR"
		else
		  echo -n "Keeping"
		fi
		echo " temporary DVD structure."
		echo "You may find the dvdauthor XML in a file called $XMLFILE"
	fi
	echo ' '
	echo 'DVDwizard finished successfully. Bye ;-)'
	echo "DVDwizard finished successfully at `date +%d.%m.%Y\ -\ %H:%M:%S`" >> "$LOGFILE"

	return 0
}

# ------------------------------------------------------------------------------
# Main Processing
#-------------------------------------------------------------------------------

#
# Is help wanted or version?
#
if [ $# -eq 0 ];then usage; fi
case "$1" in
  	-h|--help)
        conslog
   	    usage
  	;;
 	-v|--version)
   	   	conslog
        exit 0
  	;;
esac

#
# Ok, first define some default values
#
set_defaults "$@"
export permission="Ask"		# Ask user before deleting a directory
vts=""
allargs="$*"
restart=""
NOTITLE=1

#
# Check for all needed tools
#
check_tools

#
# Now deal with command line arguments
#
while [ -n "$*" ]; do
    case "$1" in
  		-C|--config-file)
	    	shift
			# -C and it's following parm already processed in set_defaults()
    	    shift
	  	;;
		-o|--output)
 	    	shift
	    	DESTDIR="$1"
	    	shift
  		;;
  		-x|--xml)
	    	shift
   	    	XMLFILE="$1"
   	    	shift
 	 	;;
  		-l|--logfile)
	    	shift
   	    	LOGFILE="$1"
   	    	shift
  		;;
		-y|--yes)
		    export permission="Yes"
	    	shift
	  	;;
		--xmlonly)
		    if [ "$XMLONLY" -eq 0 ];then XMLONLY=1;fi
	    	shift
	  	;;
		--xmlkeep)
		    XMLONLY=2
	    	shift
	  	;;
		-D|--debug)
		    export DEBUG=0
		    shift
		;;
  		-T|--vmgm)
	    	shift
	   	    VMGMTITLE="$1"
			NOTITLE=0
   	    	shift
		;;
  		-N|--tvnorm)
	    	shift
	   	    TVNORM=$(echo "$1" | tr [a-z] [A-Z])
            if [ "$TVNORM" == "PAL" -o "$TVNORM" == "NTSC" ]; then
    	    	:
	    	else
        		echo "Incorrect TV-Norm $TVNORM specified, only PAL and NTSC are supported. Aborting" >&2
    			echo "See $thisscript -h for more infos"
    			exit 1
            fi
	   	    shift
  		;;
	  	-V|--tvsize)
		    shift
		    TVSIZE="$1"
		    shift
  		;;
	  	-M|--menu)
		    shift
			defMenu=$MENU
	   	    MENU=$(echo "$1" | tr 'a-z' 'A-Z')
			eval testtxt=\"\$TXT_VMGM_PLAY_$MENU\"
			if [ -z "$testtxt" ]; then
				echo "Text elements for menu language $1 does not seem to be defined correctly. Aborting" >&2
		        echo "See $thisscript -h for more infos"
		        exit 1
			fi
   		    shift
	  	;;
	  	-WS)
		    shift
   	    	DVD_WS=$(echo "$1" | tr [a-z] [A-Z])
		    if [ "$DVD_WS" == "NOPANSCAN" -o "$DVD_WS" == "NOLETTERBOX" ]; then
		    	:
	    	else
	    		echo "Incorrect Widescreen-Option $DVD_WS specified, only NOPANSCAN or NOLETTERBOX are supported. Aborting" >&2
		        echo "See $thisscript -h for more infos"
		        exit 1
	    	fi
	   	    shift
  		;;
	  	-P|--palette)
		    shift
		    PALETTE="$1"
   		    shift
	  	;;
  		-A|--Audio)
	    	shift
		    DVDAUDIO="$1"
   		    shift
	  	;;
  		-I|--intro)
	    	shift
		    INTROMPG="$1"
   		    shift
	  	;;
  		-L|--LOOP)
	    	shift
		    LOOP="$1"
   		    shift
	  	;;
  		-MS|--vmgmsound)
	    	shift
		    MENUSOUND="$1"
   		    shift
	  	;;
  		-W|--pause)
	    	shift
	   	    PAUSE="$1"
   	    	shift
		;;
	  	-t|--vts)
		    shift
    	    if [ -z "$vts" ]; then
    			vts=1
            else
        		let "vts+=1"
            fi
		    eval CHAPTERSPEC_$vts=\"\$CHAPTERSPEC\"
    	    eval VTSMBG_$vts=\"\$VTSMBG\"
            eval VTSMAUDIO_$vts=""
		    eval VTSMWS_$vts=""
	    	eval VTSMAR_$vts=""
	    	eval VTSMSUBS_$vts=""
	    	eval VTSMINFO_$vts=""
	    	eval VTSMSOUND_$vts=""
		    if [ -e "$1" ]; then
				eval VTSTITLE_$vts=\"\$VTSTITLE\"
	        	eval VTSM_"$vts"_FILES=1
		        eval VTSM_"$vts"_FILE_1=\"\$1\"
   		    else
   	    		eval VTSTITLE_$vts=\"\$1\"
        		eval VTSM_"$vts"_FILES=0
     	    fi
	   	    shift
  		;;
	  	-c|--chapters)
		    shift
            if [ -z "$vts" ]; then
        		vts=1
				eval VTSTITLE_$vts=\"\$VTSTITLE\"
				eval VTSMBG_$vts=\"\$VTSMBG\"
				eval VTSMAUDIO_$vts=""
				eval VTSM_"$vts"_FILES=0
		    	eval VTSMWS_$vts=""
		    	eval VTSMAR_$vts=""
		    	eval VTSMSUBS_$vts=""
		    	eval VTSMINFO_$vts=""
		    	eval VTSMSOUND_$vts=""
            fi
	    	eval CHAPTERSPEC_$vts=\"\$1\"
	   	    shift
  		;;
	  	-b|--vtsmbg)
		    shift
            if [ -z "$vts" ]; then
        		vts=1
				eval VTSTITLE_$vts=\"\$VTSTITLE\"
				eval CHAPTERSPEC_$vts=\"\$CHAPTERSPEC\"
				eval VTSMAUDIO_$vts=""
				eval VTSM_"$vts"_FILES=0
		    	eval VTSMWS_$vts=""
		    	eval VTSMAR_$vts=""
		    	eval VTSMSUBS_$vts=""
		    	eval VTSMINFO_$vts=""
		    	eval VTSMSOUND_$vts=""
			fi
		    eval VTSMBG_$vts=\"\$1\"
   		    shift
	  	;;
  		-ws)
	    	shift
            if [ -z "$vts" ]; then
        		vts=1
				eval VTSTITLE_$vts=\"\$VTSTITLE\"
				eval VTSMBG_$vts=\"\$VTSMBG\"
				eval CHAPTERSPEC_$vts=\"\$CHAPTERSPEC\"
				eval VTSMAUDIO_$vts=""
				eval VTSM_"$vts"_FILES=0
		    	eval VTSMAR_$vts=""
	    		eval VTSMSUBS_$vts=""
		    	eval VTSMINFO_$vts=""
		    	eval VTSMSOUND_$vts=""
            fi
		    VTSMWS=$(echo "$1" | tr [a-z] [A-Z])
		    if [ "$VTSMWS" == "NOPANSCAN" -o "$VTSMWS" == "NOLETTERBOX" ]; then
	    		eval VTSMWS_$vts=\"\$VTSMWS\"
		    else
		    	echo "Incorrect Widescreen-Option $1 specified, only NOPANSCAN or NOLETTERBOX are supported. Aborting" >&2
		        echo "See $thisscript -h for more infos"
		        exit 1
		    fi
   		    shift
	  	;;
  		-ar)
	    	shift
            if [ -z "$vts" ]; then
        		vts=1
				eval VTSTITLE_$vts=\"\$VTSTITLE\"
				eval VTSMBG_$vts=\"\$VTSMBG\"
				eval CHAPTERSPEC_$vts=\"\$CHAPTERSPEC\"
				eval VTSMAUDIO_$vts=""
				eval VTSM_"$vts"_FILES=0
		    	eval VTSMWS_$vts=""
	    		eval VTSMSUBS_$vts=""
		    	eval VTSMINFO_$vts=""
		    	eval VTSMSOUND_$vts=""
            fi
		    VTSMAR=$(echo "$1")
		    if [ "$VTSMAR" == "16:9" -o "$VTSMAR" == "4:3" ]; then
	    		eval VTSMAR_$vts=\"\$VTSMAR\"
		    else
		    	echo "Incorrect Aspect-Ratio-Option $1 specified, only 16:9 or 4:3 are supported. Aborting" >&2
		        echo "See $thisscript -h for more infos"
		        exit 1
		    fi
   		    shift
	  	;;
  		-a|--audio)
	    	shift
            if [ -z "$vts" ]; then
        		vts=1
				eval VTSTITLE_$vts=\"\$VTSTITLE\"
				eval CHAPTERSPEC_$vts=\"\$CHAPTERSPEC\"
				eval VTSMBG_$vts=\"\$VTSMBG\"
				eval VTSM_"$vts"_FILES=0
		    	eval VTSMWS_$vts=""
		    	eval VTSMAR_$vts=""
		    	eval VTSMSUBS_$vts=""
		    	eval VTSMINFO_$vts=""
		    	eval VTSMSOUND_$vts=""
            fi
	   	    eval VTSMAUDIO_$vts=\"\$1\"
   		    shift
	  	;;
  		-s|--subpic)
	    	shift
            if [ -z "$vts" ]; then
        		vts=1
				eval VTSTITLE_$vts=\"\$VTSTITLE\"
				eval CHAPTERSPEC_$vts=\"\$CHAPTERSPEC\"
				eval VTSMBG_$vts=\"\$VTSMBG\"
				eval VTSM_"$vts"_FILES=0
		    	eval VTSMWS_$vts=""
		    	eval VTSMAR_$vts=""
   		    	eval VTSMAUDIO_$vts=""
		    	eval VTSMINFO_$vts=""
		    	eval VTSMSOUND_$vts=""
            fi
	    	eval VTSMSUBS_$vts=\"\$1\"
	   	    shift
  		;;
  		-i|--info)
	    	shift
            if [ -z "$vts" ]; then
        		vts=1
				eval VTSTITLE_$vts=\"\$VTSTITLE\"
				eval CHAPTERSPEC_$vts=\"\$CHAPTERSPEC\"
				eval VTSMBG_$vts=\"\$VTSMBG\"
				eval VTSM_"$vts"_FILES=0
		    	eval VTSMWS_$vts=""
		    	eval VTSMAR_$vts=""
   		    	eval VTSMAUDIO_$vts=""
		    	eval VTSMSUBS_$vts=""
		    	eval VTSMSOUND_$vts=""
            fi
	    	eval VTSMINFO_$vts=\"\$1\"
	   	    shift
  		;;
  		-ms|--vtsmsound)
	    	shift
            if [ -z "$vts" ]; then
        		vts=1
				eval VTSTITLE_$vts=\"\$VTSTITLE\"
				eval CHAPTERSPEC_$vts=\"\$CHAPTERSPEC\"
				eval VTSMBG_$vts=\"\$VTSMBG\"
				eval VTSM_"$vts"_FILES=0
		    	eval VTSMWS_$vts=""
		    	eval VTSMAR_$vts=""
   		    	eval VTSMAUDIO_$vts=""
		    	eval VTSMSUBS_$vts=""
		    	eval VTSMINFO_$vts=""
            fi
	    	eval VTSMSOUND_$vts=\"\$1\"
	   	    shift
  		;;
	  	--restart)
		    shift
            case "$1" in
    			dvdcpics|mk_vmgm|mk_vtsm|author)
        		    restart="$1"
	    		;;
    			*)
        		    echo "Incorrect Restart-Parameter specified: $1" >&2
			        echo "See $thisscript -h for more infos"
			        exit 1
				;;
    	    esac
   	    	shift
	  	;;
  		*)
            if [ -z "$vts" ]; then
    			vts=1
				eval VTSTITLE_$vts=\"\$VTSTITLE\"
				eval CHAPTERSPEC_$vts=\"\$CHAPTERSPEC\"
				eval VTSMBG_$vts=\"\$VTSMBG\"
				eval VTSMAUDIO_$vts=""
				eval VTSM_"$vts"_FILES=0
		    	eval VTSMWS_$vts=""
		    	eval VTSMSUBS_$vts=""
		    	eval VTSMINFO_$vts=""
		    	eval VTSMSOUND_$vts=""
    	    fi
    	    eval fnum=\$VTSM_"$vts"_FILES
    	    let "fnum+=1"
    	    eval VTSM_"$vts"_FILES=\$fnum
    	    eval VTSM_"$vts"_FILE_"$fnum"=\"\$1\"
   	    	shift
	  	;;
    esac
done

#
# Clear the log if we are not restarting
#
[ -z "$restart" ] && rm -f "$LOGFILE"

#
# Let's see, if all options are correct so far
#
checkParms

#
# If restart was specified, start with the given step
#
case "$restart" in
	dvdcpics)
		call_dvdcpics
	    call_mk_vmgm
    	call_mk_vtsm
	    call_author
	;;
	mk_vmgm)
		call_dvdcpics_upd
		call_mk_vmgm
	    call_mk_vtsm
    	call_author
	;;
	mk_vtsm)
		call_dvdcpics_upd
		call_mk_vtsm
	    call_author
	;;
	author)
    	call_author
	;;
#
# Start from the very beginning
# Save Commands generated from dvdwizard
#
	*)
		echo "`basename $0` $allargs" > "$CMDFILE"
		# global variable $LANG
		if [ $(echo $LANG | grep -c -i "utf.8") -eq 1 ]
		then ENCODE="UTF-8"
		else ENCODE="ISO-8859-1"
		fi
		cat <<EOF > "$XMLFILE"
<?xml version="1.0" encoding="$ENCODE"?>
<!-- dvdauthor xml-file created with `basename $0` at `date +%d.%m.%Y\ -\ %H:%M:%S`
     Called with `basename $0` "$( echo $allargs | sed -e s/--/-/g)" //-->
<dvdauthor dest="$DESTDIR">
EOF

#
# First step: Create temporary DVD-image with chapters for chapter-menu-creation
# This step is to speed up generation of chapter thumbnails for the vtsm
# I do not know any CLI program which can extract single frames at a specified position of an mpeg stream
# except to transcode. But transcode is very slow in seeking (runs at approx 35fps on my Athlon1.4 - would take
# 90 minutes to seek a 2 hour movie). In DVD chapter mode, transcode is much faster because it reads from the first
# few frames only and so the 10 minutes to author the temporary DVD pay back with better overall performance
#
		echo -n Creating temporary DVD-structure...
		cat <<EOF >> "$LOGFILE"
+-------------------------------------+
| Calling mk_tmpdvd                   |
| Creating temporary DVD-structure    |
+-------------------------------------+
EOF

#
# Since enabling multi-title DVD-creation, mk_tmpdvd has been "degraded" from a stand-alone script to an
# internal function in dvdwizardrc.
# The script is of little use outside dvdwizard and parsing all needed parms would have resulted in a
# calling syntax nearly as complicated as using dvdauthor without xml, so I cut that. ;-)
#
		mk_tmpdvd >> "$LOGFILE" 2>&1 || error_out
		echo "...done."

#
# Ok, now process restartable steps one by one
#
		call_dvdcpics
		call_mk_vmgm
	    call_mk_vtsm
    	call_author
	;;
esac

# Cleanup temporary directory if script was called directly
#
cleanup_tmpdir

exit 0
