#!/bin/bash
#
# chaptercheck - Check Chapter-List for dvdauthor xml-definitions
#
# Version   0.01a written by Wolfgang Wershofen (mailto: itconsult at wershofen.de)
#
usage()
{
 cat <<EOF
Usage:	`basename $0` [options] <chapterspec>
	`basename $0` -h|--help

currently supported options:
----------------------------
-C | --config-file	filename of dvdwizard-configuration file
			[~/.dvdwizard/dvdwizard.conf]
-N | --tvnorm		Choose tv-norm from PAL or NTSC [PAL]
-L | --maxlen		Length of mpeg file
-h | --help		print this lot out

chapterspec:	Definition of Chapters as <file>|<timecodes>|interval|0 [none]

EOF

exit 1
}
# ------------------------------
# Main Processing
#
#
# Is help wanted?
#
case "$1" in
  	-h|--help)
   	    usage
  	;;
esac

# 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

#
# Ok, first define some default values
#
set_defaults "$@"

#
# Check for 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
  	;;
  	  	-N|--tvnorm)
	    shift
   	    TVNORM="$1"
        if [ "$TVNORM" == "PAL" -o "$TVNORM" == "NTSC" ]; then
        	:
        else
        	echo "Incorrect TV-Norm $TVNORM specified, only PAL and NTSC are supported. Aborting"
	        echo "See $thisscript -h for more infos"
    	    exit 1   
		fi >&2
   	    shift
  	;;
  	-L|--maxlen)
  		shift
  		MAXSEC="$1"
  		shift
  	;;
  	*)
   	    cSpec="$1"
        shift
  	;;
    esac
done

#
# Is Chapter-Specification supplied?
#
if [ -z "$cSpec" ]; then
	echo "No chapter specification supplied. Aborting"
	echo "See $thisscript -h for more infos"
    exit 1
fi >&2

#
# Nothing needs to be done, when cSpec=0
#
if [ "$cSpec" == "0" ]; then
	echo "" >&1
	exit 0
fi		

#
# Input can be a file or a chapter-list or an interval
#
[ -z "$MAXSEC" ] && MAXSEC=14400
if [ -f "$cSpec" ]; then
	mode="file"
	[ $(grep chapters= "$cSpec") ] && chapterList=`grep chapters= "$cSpec" | awk -F"\"" '{print $2}'` || chapterList=`cat "$cSpec"`
else
	if [ ! $(echo "$cSpec" | grep ,) ]; then
		mode="auto"
  		interval="$cSpec"
		checkInt=$(echo "$interval+0" | bc 2>/dev/null)
		if [ ! "$checkInt" == "$cSpec" ]; then
			echo "Invalid interval specified, $cSpec is not numeric. Aborting"
	        echo "See $thisscript -h for more infos"
    	    exit 1
		fi >&2
   		chapterList=`seq -s, 0 $interval $MAXSEC`
  	else
   		mode="string"
   		chapterList="$cSpec"
   	fi
fi

#
# Go through all the chapters. If errors are found, report them
#
[ "$TVNORM" == "NTSC" ] && fps=$(echo "scale=2; 30000/1001" | bc) || fps=25
fracInt=$(echo "scale=0; 1000/$fps" | bc)
errors=0
i=1
chapter=`echo $chapterList | cut -d, -f$i`
while [ ! -z $chapter ]; do

#
# Extract fractions, if they are given
#
	hmmss=`echo $chapter | awk -F. '{print $1}'`
   frac=`echo $chapter | awk -F. '{print $2}'`

#
# Check specified fractions - must be less than 3 numeric digits and a multiple of
# $fracInt (PAL 25fps/40ms NTSC 29.97fps/33.37ms per frame)
#
   if [ ! -z $frac ]; then
      if [ ${#frac} -gt 3 ]; then
         echo $chapter: wrong length of fractions >&2
		let "errors+=1"
      fi
      
#
# Fill with trailing blanks, if length is less than 3 digits
#
		if [ ${#frac} -lt 3 ]; then
			tmpfrac="${frac}000"
			frac=${tmpfrac:0:3}
		fi

#
# get rid of leading zeroes
#
      while [ ${frac:0:1} == "0" ]; do
         frac=${frac:1}
			if [ -z $frac ]; then
				frac=0
				break
         fi
      done

      if [ ! -z $(echo $frac | tr '[0-9]' ' ') ]; then
         echo $chapter: fractions not numeric >&2
	    let "errors+=1"
      else
         let checkfrac="($frac/$fracInt)*$fracInt"

         if [ $checkfrac -ne $frac -a "$TVNORM" == "PAL" ]; then
		    echo $chapter: fractions not a multiple of $fracInt >&2
		    let "errors+=1"
         fi
      fi
   fi

#
# Now, go for the rest of the specification - read :-separated values one by one
#
   j=1
   [ $(echo $hmmss | grep :) ] && timespec=`echo $hmmss | cut -d: -f$j` || timespec=$hmmss
   while [ ! -z $timespec ]; do

#
# drop leading zeroes
#
      while [ ${timespec:0:1} == "0" ]; do
         timespec=${timespec:1}
	 		if [ -z $timespec ]; then
	  			timespec=0
	  			break
      	fi
      done

#
# Check if value is numeric
#
      if [ ! -z $(echo $timespec | tr '[0-9]' ' ') ]; then
         echo $chapter: hour, minute or second definition not numeric >&2
	 		let "errors+=1"
      fi

      let "j+=1"
      [ $(echo $hmmss | grep :) ] && timespec=`echo $hmmss | cut -d: -f$j` || timespec=""
   done

#
# More than 3 :-separated values are not allowed
#
   if [ $j -gt 4 ]; then
      echo $chapter: Too many \":\" in chapter definition >&2
      let "errors+=1"
   fi
   let "i+=1"
   chapter=`echo $chapterList | cut -s -d, -f$i`
done

#
# Print summary and set appropriate return code
#
let "i-=1"
echo $i chapters found - with $errors errors >&2

# Cleanup temporary directory if script was called directly
#
cleanup_tmpdir

if [ $errors -eq 0 ]; then
	echo $chapterList >&1
   exit 0
else
	echo Chapter definition not correct. See /dev/stderr >&1
   exit 1
fi
