#!/usr/bin/env bash
#
#   dvdwizard 
#     - create a DVD  directory from mpeg stream(s) with
#       chapters and menus without further user interaction.
#
#   Copyright (C) 2004-2008 W. Wershofen <itconsult at wershofen.de>
#   Copyright (c) 2010-2011 Markus Kohm <kohm at users.sf.net>
#   Copyright (C) 2009-2012 Joo Martin <joomart2009 at users.sf.net>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This package is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Changes:
#
#   2004-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)
#   2010-06-21  Markus Kohm
#               * renamed dvdwizardrc into dvdwizard_common
#               * moved some functions to dvdwizard_common
#               * usage of gettext features for multilanguage ui
#                 -several `echo' replaced by `printf'
#   2010-08-03  Markus Kohm
#               * audio tracks may be mono or stereo
#   2010-09-29  Markus Kohm
#               * tested with ImageMagick 6.5.4-8
#   2011-01-01  Markus Kohm
#               * added VIDEO_FORMAT to call of dvdauthor
#   2012-03-18  Joo Martin
#               * user config file always in $HOME/.config/dvdwizard/
#
# -------------------------------------------------------------------------

#
# i18n
#
export TEXTDOMAIN=dvdwizard
export TEXTDOMAINDIR="@LOCALEDIR@"

# We need some sub-routines from dvdwizard_common.
# This file must be found at PATH.
#
. dvdwizard_common || {
    echo $"FATAL ERROR: could not execute common function file \`dvdwizard_common'!
You have to install \`dvdwizard_common' somewhere at PATH." >&2
    exit 1
}

# ------------------------------
# Function specification
#
usagetext=$"
Usage:	${thisscript} [options] mpeg-file(s)
	${thisscript} -h|--help
	${thisscript} -v|--version

general processing:
-------------------
-C  | --config-file	filename of dvdwizard-configuration file.
			[~/.config/dvdwizard/dvdwizard.conf]
-o  | --output		Path where the 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 ~/.config/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 audio track of this titleset. [en];
			Each language may be followed by an optional \`+vi' to
			indicate a audio track for visually impaired, i.e.,
			\`-a de,de+vi' declares first audio track to be german
			and second audio track to be german for visually 
			impaired. Each language my be followed by an optional
                        \`+1' or \`+m' to indicate a mono audio track or \`+2' or
                        \`+s' to indicate a stereo audio track.
-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
"

# ------------------------------
# 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
    #
    show_version
    IM_ADDINFO=''
    if [ "$IM_VERSION4" \> "6.6.5-8" ]; then
	IM_ADDINFO=$( printf $"(%s was NOT TESTED with ImageMagick > %s)" "${DW_NAME}" "6.6.5-8" )
    fi
    echo $"Using ImageMagick"" ${IM_VERSION4} ${IM_ADDINFO}"
    echo

    #
    # Open file Log
    #
    printf $"Logfile from %s run at %s.
Using ImageMagick %s.
DVDwizard invoked with %s.
Default processing options read from %s.
-----------------------------------------------------------------\n" "${DW_NAME} ${DW_VERSIONX} ${DW_DATE}" "`date +%Y-%m-%d\ %H:%M:%S`" "${IM_VERSION4} ${IM_ADDINFO}" "${thisscript} ${allargs}" "${confFile}">> "$LOGFILE"

    #
    # 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
	    error_help $"No input files specified for titleset %d." $i
	fi

	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
	    log_warn $"Unsupported codec for audio stream: %s.\n" "$audiotracks"
	fi
	acount=$(echo "$audiotracks" | wc -w)
	if [ "$acount" -eq 0 ]; then
	    log_warn $"Cannot determine audio tracks for title %d.\n" $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
	    log_warn $"Cannot determine video resolution for title %d.\n" $i
	fi
	vratio=$(echo "$vattribs" | cut -d' ' -f2)
	if [ -z "$vratio" ];then
	    log_warn "Cannot determine aspect ratio for title %d.
*** .......: Assuming %s for chapter thumbs.\n" $i "${THUMBRATIO}"
	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 [:lower:] [:upper:])" == "AUTO" ]; then
	    eval vtstitle=\"\$VTSM_${i}_FILE_1\"
	    tstring=`nice -n $NICE dvdtguess "$vtstitle"`
	fi
	eval vratio=\"\$VTSM_${i}_VRATIO\"
	printf $"Title #%d: \`%s' \t (%s)\n" ${i} "${tstring}" "${vratio}"
	eval VTSTITLE_${i}=\"\${tstring}\"
    done
    if [ -z "$VMGMTITLE" ]; then
	VMGMTITLE=$VTSTITLE_1
	printf $"DVD-Title: \`%s'\n" "${VMGMTITLE}"
    fi

    #
    # Check Playback-Mode
    #
    if ! is_integer "$LOOP"; then
	error_help $"Playback mode %s is not numeric.\n" "$LOOP (-L|--loop \$LOOP)"
    fi
    if [ $LOOP -lt -2 -o $LOOP -gt $vts ]; then
	error_help $"Playback mode %s invalid.\nMust be between -2 and number of titles on dvd (%d)" "$LOOP (-L|--loop \$LOOP)" $vts
    fi

    #
    # Check Pause length
    #
    if ! is_integer "$PAUSE"; then
	error_help $"Pause time %s is not numeric." "$PAUSE (-W|--pause \$PAUSE)"
    fi
    if [ $PAUSE -lt 0 -o $PAUSE -gt 120 ]; then
	error_help $"Pause time %s invalid.\n
Must be between 0 and 120 seconds"! "$PAUSE (-W|--pause \$PAUSE)"
    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
	log_warn "Defined TVSIZE %dx%d is to small, set to %dx%d." ${TVWidth} ${TVHeight} ${miniX} ${miniY}
	TVWidth=$miniX; TVHeight=$miniY
    fi
    let maxiX="${normX}-14"
    let maxiY="${normY}-10"
    if [ "${TVWidth}" \> "${maxiX}" -o "${TVHeight}" \> "${maxiY}" ]; then
	log_warn "Defined TVSIZE %dx%d is to large, set to %dx%d." ${TVWidth} ${TVHeight} ${miniX} ${miniY}
	TVWidth=$maxiX; TVHeight=$maxiY
    fi
    TVSIZE="${TVWidth}x${TVHeight}"

    return 0
}

# ------------------------------
# Create Chapter-Pics
#
call_dvdcpics()
{
    echo -n $"Capturing Chapter-Screenshots from temporary DVD..."
    echo $"+-------------------------------------+
| Calling dvdcpics                    |
| Capture Screenshots from Chapters   |
+-------------------------------------+" >> "$LOGFILE"
    for i in $(seq 1 $vts); do
	printf $"Capturing Chapters from Titleset %d\n" $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..."
    echo $"+-------------------------------------+
| Calling dvdcpics                    |
| Use existing Chapter-Screenshots    |
+-------------------------------------+" >> "${LOGFILE}"
    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..."
    echo $"+-------------------------------------+
| Calling mk_vmgm                     |
| Creating VMGM-Menu                  |
+-------------------------------------+" >> "${LOGFILE}"

    #
    # 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
	printf $"Creating Titleset #%s...\n" $title
	echo -e "\t<titleset>" >> "$XMLFILE"
	echo -e "\t\t<menus>" >> "$XMLFILE"

        #
        # Get audio characteristics of the title
        #
	print_log "\t"$"Assigning Languages to Audio-Tracks...\n"
	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 [:lower:] [:upper:])
	    alang="$(normalize_formatstring $alang)"
	    alangs="$alangs $alang"
	    audioparm="${audioparm}${alang}+${i},"
	    eval "language=\$"$alang
	    [ -z "$language" ] && language="unknown"
	    print_log "\t"$"%d. audio-track (%s) will be assigned to language %s\n" ${disind} "$i" "${alang} (${language})"
	    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)
	#
	printf "\t"$"Building VTSM-Menu(s)..."
	echo $"+-------------------------------------+
| Calling mk_vtsm                     |
| Creating VTSM-Menu(s)               |
+-------------------------------------+" >> "${LOGFILE}"
	#
	# 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
	#
	printf "\t"$"Writing 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
	    audiolang=$(echo $i | cut -d'+' -f1)
	    echo -e "\t\t\t<audio lang=\"$audiolang\" />" >> "$XMLFILE"
	done
	# Subtitle informations
	if [ ! -z "$subtracks" ]; then
	    for i in $(echo "$subtracks" | tr ',' ' '); do
		sublang=$(normalize_formatstring $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 $"done."
	printf $"Finished titleset #%d.\n" $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
	printf $"Authoring DVD into %s..." "${DESTDIR}"
	echo $"+-------------------------------------+
| Calling dvdauthor                   |
| Final authoring of DVD              |
+-------------------------------------+" >> "${LOGFILE}"
	[ -e "$DESTDIR" ] && rm -R "$DESTDIR"
	echo "VIDEO_FORMAT=\"$TVNORM\" nice -n $NICE dvdauthor -x \"$XMLFILE\"" >> "$CMDFILE"
	VIDEO_FORMAT="$TVNORM" \
	    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 $"Removing temporary DVD structure."
	    rm -R "$DESTDIR"
	else
	    echo $"Keeping temporary DVD structure."
	fi
	printf "You may find the dvdauthor XML in a file called %s\n" "${XMLFILE}"
    fi
    echo
    print_log $"DVDwizard finished successfully at %s.\n" "`date +%Y-%m-%d\ %H:%M:%S`"
    
    return 0
}

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

#
# Is help wanted or version?
#
test_versionhelp "$@"

#
# 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 [:lower:] [:upper:])
            if [ "$TVNORM" == "PAL" -o "$TVNORM" == "NTSC" ]; then
    	    	:
	    else
        	error_help $"Incorrect TV-Norm %s specified.\nOnly PAL and NTSC are supported." "$TVNORM (-N|--tvnorm $TVNORM)"
            fi
	    shift
  	    ;;
	-V|--tvsize)
	    shift
	    TVSIZE="$1"
	    shift
  	    ;;
	-M|--menu)
	    shift
	    defMenu=$MENU
	    MENU=$(echo "$1" | tr [:lower:] [:upper:])
	    eval testtxt=\"\$TXT_VMGM_PLAY_$MENU\"
	    if [ -z "$testtxt" ]; then
		error_help $"Text elements for menu language %s does not seem to be defined correctly." "$1 (-M|--menu $1)"
	    fi
   	    shift
	    ;;
	-WS)
	    shift
   	    DVD_WS=$(echo "$1" | tr [:lower:] [:upper:])
	    if [ "$DVD_WS" == "NOPANSCAN" -o "$DVD_WS" == "NOLETTERBOX" ]; then
		:
	    else
	    	error_help "Incorrect Widescreen-Option %s specified, only NOPANSCAN or NOLETTERBOX are supported." "$1 (-WS $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 [:lower:] [:upper:])
	    if [ "$VTSMWS" == "NOPANSCAN" -o "$VTSMWS" == "NOLETTERBOX" ]; then
	    	eval VTSMWS_$vts=\"\$VTSMWS\"
	    else
		error_help $"Incorrect Widescreen-Option %s specified.\nOnly NOPANSCAN or NOLETTERBOX are supported." "%1 (-ws $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
		error_help "Incorrect Aspect-Ratio-Option %s specified.\nOnly 16:9 or 4:3 are supported." "$1 (-ar $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"
	    	    ;;
    		*)
        	    printf $"Incorrect Restart-Parameter specified: %s" "$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..."
	echo $"+-------------------------------------+
| Calling mk_tmpdvd                   |
| Creating temporary DVD-structure    |
+-------------------------------------+" >> "$LOGFILE"

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