#!/bin/bash
#
# dvdwizard - create a DVD image from mpeg stream(s)
#             with chapters and menus without further user interaction
#
# Version   0.41 written by Wolfgang Wershofen (mailto: itconsult at wershofen.de)
#           0.42 / Stefan Becker,
#                   - pass Subpicture Information to dvdauthor (-s)
#                   - pass Palette File to dvdauthor (-P)
#                   - Widescreen-Options (-WS)
#                   - Widescreen Options for every Title Set (-ws)
#		 		/ Wolfgang Wershofen
#                   - Zuordnung Sprache/Audiotracks geaendert
#		    		- Neue Option --audio-seq
#			0.50 Wolfgang Wershofen
#					- changed location of temporary files (make use of $TMPDIR)
#					- make --notitle the default, Title will only be printed
#					  on VMGM-Menu if -T is explicitly used. Thus, option
#					  --notitle is obsolete
#					- introduced system-wide config-file /etc/dvdwizard.conf
#					- config file mandatory now
#					- Options for Subtitle and Info-Menus
#
# See TOOLS in the dvdwizard tarball for info about needed tools and programs
#

# 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
# but this would require an installation procedure - maybe in some
# later version.
#
rcfile="`dirname $0`/dvdwizardrc"
if [ -e "$rcfile" -a -r "$rcfile" ]; then
	. "$rcfile"
else
	echo "dvdwizardrc not found or is not readable. Aborting" >&2
    exit 1
fi

# ------------------------------
# Function specification
#
usage()
{
 cat <<EOF
Usage:	`basename $0` [options] mpeg-file(s)
	`basename $0` -h|--help
	`basename $0` -v|--version

miscellaneous options:
----------------------
-h  | --help   		print this lot out
-v  | --version		print version and exit

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
--restart		Do not start from beginning but from step x
			x may be dvdcpics, mk_vmgm, mk_vtsm, author
--xmlonly		Do not author final DVD, only create menus and xml
			and remove temp. DVD structure.
--xmlkeep		Like --xmlonly, but keep temp. 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> [635x535]
-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> 
			[de,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
-M  | --menu		Language to use in menu items [en]
			Textelements are defined in config file
-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 through all titles afterwards
			>0 - 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.

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
-ws             	Widescreen-Option (nopanscan or noletterbox) for 
			this titleset
-a  | --audio		see -A, but only applies to this titleset
-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 and -a and mpeg-file(s) apply only to that titleset. To create a DVD with 2 titlesets, 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 the Log
#
echo "Creating DVD with $dvdwizard_ver"
cat <<EOF >> "$LOGFILE"
Logfile from $dvdwizard_ver run at `date +%d.%m.%Y\ -\ %H:%M:%S`
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
    acount=$(echo "$audiotracks" | wc -w)
    if [ "$acount" -eq 0 ];then echo "*** Warning: Cannot determine audio tracks for title $i.";fi
 	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
    echo "Title #$i: $tstring"
    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

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"
    [ -e "$confFile" ] && cmd="${cmd} -C \"$confFile\""
    eval echo "$cmd" >> "$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
}

# ------------------------------
# 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 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
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..."
	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 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"
    vtsparms="$parm"
    cmd="nice -n $NICE mk_vtsm ${parm}"
    eval ropt=\${VTSM_"$title"_VRATIO:+"-r "}
    eval rparm=\$VTSM_"$title"_VRATIO
    cmd="${cmd} $ropt $rparm \"$BASEDIR/cpics/VTS$title/\"chapter*.jpg"
    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\"
	[ ! -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 "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)
   	    usage
  	;;
 	-v|--version)
   	   	echo $dvdwizard_ver
        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
	  	;;
  		-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
	  	;;
	  	-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 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 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 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 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
	  	;;
  		-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 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 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 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 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_mk_vmgm
	    call_mk_vtsm
    	call_author
	;;
	mk_vtsm)
		call_mk_vtsm
	    call_author
	;;
	author)
    	call_author
	;;
#
# Start from the very beginning
# Save Commands generated from dvdwizard
#
	*)
		echo "`basename $0` $allargs" > "$CMDFILE"
		cat <<EOF > "$XMLFILE"
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- 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
