#!/usr/bin/env bash
#
#   chaptercheck 
#     - Check Chapter-List for dvdauthor xml-definitions
#
#   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
#   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'
#   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] chapterspec
	${thisscript} -h|--help
	${thisscript} -v|--version

supported options:
------------------
-C | --config-file	filename of dvdwizard-configuration file
			                          [~/.config/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
-v | --version		print version and exit.

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

<file> := name of a file with <timecodes>
<timecode> := <timecode>[,<timecode>...] | <interval>
<timecode> :=  <h>:<mm>:<ss>[.<frac>]
<h>  := hour (0..23)
<mm> := minute (0..59)
<ss> := second (0..59)
<frac> := 000..999
<interval> := time in seconds
"

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

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

#
# 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
        	error_help $"Incorrect TV-Norm %s specified.\nOnly PAL and NTSC are supported." "$TVNORM (-N|--tvnorm $TVNORM)"
	    fi
   	    shift
  	    ;;
  	-L|--maxlen)
  	    shift
  	    MAXSEC="$1"
  	    shift
  	    ;;
  	*)
   	    cSpec="$1"
            shift
  	    ;;
    esac
done

#
# Is Chapter-Specification supplied?
#
if [ -z "$cSpec" ]; then
    error_help $"No chapter specification supplied."
fi

#
# 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"
	if ! is_real "$interval"; then
	    error_help $"Invalid interval specified, \`%s' is not numeric." \
		"$cSpec"
	fi
   	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=${chapter%%.*} # we don't need awk to seperate
    frac=${chapter##*.}  # before and after '.'
    [ "${frac}" == "${chapter}" ] && frac=""

    #
    # 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
            printf $"%s: wrong length of fractions\n" "$chapter" >&2
	    let "errors+=1"
	fi
      
        #
        # Fill with trailing zeros, 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 ! is_integer "$frac"; then
            printf $"%s: fractions not numeric\n" "$chapter" >&2
	    let "errors+=1"
	else
            let checkfrac="($frac/$fracInt)*$fracInt"
	    
            if [ $checkfrac -ne $frac -a "$TVNORM" == "PAL" ]; then
		printf $"%s: fractions not a multiple of %s\n" \
		    "$chapter" "$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 ! is_integer "$timespec"; then
            printf $"%s: hour, minute or second definition not numeric.\n" \
		"$chapter" >&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
	printf $"%s: Too many \`:' in chapter definition.\n" \
	    "$chapter" >&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"
printf $"%d chapters found - with %d errors.\n" $i $errors >&2

# Cleanup temporary directory if script was called directly
#
cleanup_tmpdir

if [ $errors -eq 0 ]; then
    echo $chapterList
    exit 0
else
    echo $"Chapter definition not correct." >&2
    exit 1
fi
