#!/bin/bash
#set -n		# read but do not execute commands (check on syntax errors)
#
# File: /usr/local/bin/makemcf
#
# Make a media control file (.mcf).
#
#    Copyright (c) 2016 Juergen Kaesmann (JK)
#
##############################################################################
# GPL NOTICE
#
#    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 2 of the License, or
#    (at your option) any later version.
#
#    This program 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, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#############################################################################
# FIND
##############################################################################
# XARGS
##############################################################################
# FILTER
##############################################################################
# AWK
##############################################################################
# SED
##############################################################################
# TREE
##############################################################################
# RSYNC
##############################################################################
# DIALOG
##############################################################################
# EXIT CODES

##############################################################################
# SOURCE FILES
#
. /usr/local/etc/main.conf				# config main
#. $LLIBDIR/libfuncerr-sh				# functions error
. $LLIBDIR/libfuncstd-sh				# functions standard
#. $LLIBDIR/libfuncmath-sh				# functions math
#. $LLIBDIR/libfuncip-sh				# functions IP
#. /usr/local/etc/multimedia.conf			# config multimedia
#
#if [ ! -e ~/.multimediarc ]; then			# install config user
#	cp /usr/local/share/ksm-multimedia/multimediarc ~/.multimediarc
#fi
#. ~/.multimediarc					# config user

##############################################################################
# DECLARATION OF STANDARD CONSTANTS AND VARIABLES
#
readonly package=CAMP					# package name
readonly package_file=ksm-camp				# package file name
readonly vinfopath="/usr/local/share/$package_file"	# path to package dir
readonly version=$(/bin/cat $vinfopath/VERSION)		# package version
readonly release=$(/bin/cat $vinfopath/RELEASE)		# package release
readonly scriptname=$(basename $0)			# name of script
#readonly tempfile=$TEMPDIR/$scriptname.$UID.tmp	# temporary file name
tempfile=$(mktemp -u $TEMPDIR/$scriptname.$UID.XXXXXX)	# temporary file name
readonly lockfile=$TEMPDIR/lock/$scriptname.$UID.lock	# lock file name
readonly debuglog="/usr/bin/logger -p user.debug -t $scriptname -- DEBUG:"	# log dbg msg
readonly errlog="/usr/bin/logger -p user.err -t $scriptname -- ERROR:"		# log err msg
readonly infolog="/usr/bin/logger -p user.info -t $scriptname -- INFO:"		# log inf msg
cmd=''							# sub command
debug=no						# debug=yes/no
verbose=''						# verbose=yes/''/no
err=0							# error code

##############################################################################
# USER FILL IN AT FIRST RUN
##############################################################################
# SYSTEM
##############################################################################
# USER-CONSTANTS
#
# STRINGS
#readonly const=string
videotipp='#CHAPTER[n]="FILENAME	<TAB>POS	<TAB>TEXT	<TAB>OPT..."'
audiotipp='#TRACK[n]="FILENAME"'

# NUMBERS
#readonly const=value
#
##############################################################################
# USER-VARIABLES
#
# STRINGS
args=''					# all args from cmdline
arg1=''					# 1. arg from cmdline
arg2=''					# 2. arg from cmdline
#opt_o=''				# option -o (yes)
					# option --output (yes)
#opt_i=''				# option -i (arg)
					# option --infile (arg)
#opt_o=''				# option -o (arg)
					# option --outfile (arg)
#opt_p=''				# option -p (arg)
					# option --pages (arg)
opt_s=''				# option -s (yes)
audio=''				# option --audio (yes)

# NUMBERS
#p_first=0				# first page
#p_last=0				# last page
maxCHAPTER=0

# ARRAYS
# Indexed arrays are always zero based string arrays.
# If index starts with 1 and all members are assigned then
# count of members of array = last index of array
#declare -a arr
#maxarr="${#arr[@]}"			# get number of elements in arr
#unset arr[@]				# remove the entire array
#
##############################################################################
# SIGNAL HANDLING

##############################################################################
# FUNCTIONS
##############################################################################
#
##############################################################################
# HELP
#
#=============================================================================
function helptext ()
{
# Output helptext
# Uses cat, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG helptext: $# $@" >&2
	$debuglog helptext: $# $@
fi

cat <<EOT
NAME
$scriptname - Make a media control file (.mcf).

SYNOPSIS
$scriptname [options] [mcf mf [c [c [...]]]]
$scriptname --audio [options] [mcf mfw]

DESCRIPTION
Create a media control file (.mcf) from a media file with at least 1
chapter of the media file. This media control file is created in the
given directory. The pathname of the media files therein is changed to
an absolute path name and points always to the media directory. Therefore
one can move it after creation to another directory.

The name of the mcf and the name of the media file is required. If no
chapter is specified then the media control file will contain only the
start chapter at pos 0 of the media file.

Each chapter is specified in one line. It contains the media file name,
the startpos in seconds and a text for the user which describes this
chapter. The chapter numbers in the mcf go continously over all files.
After finishing, the medias can be played with CAMP.

Chapters/tracks in an mcf are played up from the starting chapter/track
till the end of this media. Then follows playing of all following
medias in full length. This is done without interruption.

ADVANCED USERS
If you want to play directly some chapters of one ore multiple mf in an
video mcf which start at different times then you have to prepend these
chapters with a '-' . This will force creating a start-time for this
entry (standard is that only the start entry will get a start-time).
In the mentioned case you should specify a stop-time as option for all
those chapters (see template-video.mcf).

You can put options for a vlc Playlist.xspf at the end of that line.
Each option need to be separated with a TAB (have a look into the
template-video.mcf). These options are only true for that track.

GLOBOPT
In addition you can write global options into the variable GLOBOPT.
Separate them with a blank. These options are given to the player
directly before the playlist.

MDIR
The mcf can hold multiple files which belong together. But all of them
must reside in the same directory. Audio tracks must always be of the
same type (f.i. mp3 or wav).

DVD
If building an mcf for a DVD then specify the VIDEO_TS.IFO in the
VIDEO_TS directory: <path>/VIDEO_TS/VIDEO_TS.IFO

Defaults:  Create a media control file from media file <mf>.

OPTIONS
Gnu style options:

  -h|--help    = Output help, then exit.
  -V|--version = Output version info, then exit.
  -d|--debug   = Turn on DEBUG mode.
  -q|--quiet   = Be quiet.
  -v|--verbose = Be verbose.
  -A           = Create mcf and append all mp4 in actual directory.
                 Do not create mcf separately! Give only mcf.
                 Text is created from the file name (cut off .ext and
                 video coding info if any). Therefore avoid punctuation
                 in file names.
  -a [-s]      = Append chapters or tracks to an existing media control
                 file.

                 ATTENTION - it is not possible to auto insert chapters
                 or tracks elsewhere. They are always appended at the
                 end ot the list. Therefor create ALL chapters for a
                 media file before the next mf is used! Otherwise you
                 have to edit the mcf manually.

                 If you insert chapters/tracks manually or in multiple
                 runs of makemcf then you have to check/correct the
                 indices of the CHAPTER/TRACK array and reorder them so
                 that the index is in ascending order continously
                 numbered from 1.

  -u           = Update the path to the media directory. This is needed
                 if the media directory has changed. Give the pathname
                 of one of the new located media files as argument. We
                 create the new path from it and store this new path in
                 the mcf.
  --audio      = Use 'AUDIO' as Media Type (default = VIDEO). If this
                 option is set, then all mediafiles must be of the same
                 file type.
  -s           = Set start-time for each entry. So the entry can played
                 independent of the others. Don't forget to give the
                 'stop-time' option manually. This option is only for
                 video media files.
  --           = End of options.

ARGUMENTS
Give if needed:

  mcf = Media control file (with or without path).
  mf  = Media file pathname (no wildcards allowed).
  c   = Chapter (position in seconds). The 1. chapter (start chapter)
        of the 1. file should be '0'. Pay attention to the order of the
        chapter positions. They have to be in ascending order.
  mfw = Media file(s) pathname, can be a wildcard or multiple files.

EXAMPLES
For instance:

  Create mcf with 1. chapter from work/MyVideo-1.mp4 in the videos dir:
  $scriptname MyVideo.mcf /videos/MyVideo-1.mp4

  Define 3 chapters with startpos 60 120 180 seconds from start of file
  /work/MyVideo-1.mp4, mcf is /videos/MyVideo.mcf :
  $scriptname -a /videos/MyVideo.mcf /videos/MyVideo-1.mp4 60 120 180

  Apply new media /videos/MyVideo-2.mp4 to the mcf and define 3
  chapters with startpos 0 200 and 600 seconds from start of this
  media, mcf is /videos/MyVideo.mcf :
  $scriptname -a /videos/MyVideo.mcf /videos/MyVideo-2.mp4 0 200 600

  Apply new media /videos/MyVideo-2.mp4 to the mcf and define 3
  chapters with startpos 10 30 and 50 seconds from start of this
  media. This chapters should play an individual time. mcf is
  /videos/MyVideo.mcf. The mcf has to be edited later and the
  stop-time must given for all specified entries manually:
  $scriptname -a -s /videos/MyVideo.mcf /videos/MyVideo-2.mp4 10 30 50

  Create mcf with all MP3-tracks from /audio/ in the audio dir:
  $scriptname --audio /audio/MyAudio.mcf /audio/*.mp3

EXIT STATUS
On program exit:

  Code 0 = OK

  See output of 'showerrmsg'.

SEE ALSO
Related manpages:

  showerrmsg(1), camp(1).

AUTHORS
Juergen Kaesmann <juergen@kaesmann-online.de>
EOT
#  -o|--output  = Output to STDOUT.
#  -i f         = Input from file <f>.
#  --infile=f   = Input from file <f>.
#  -o f         = Output to file <f>.
#  --outfile=f  = Output to file <f>.
#  -p s,e       = Pages s=START e=END.
#  --pages=s,e  = Pages s=START e=END.

#FILES
#Used directories and files:
#
#  Config Global = /usr/local/etc/sample.conf
#  Config User   = ~/.samplerc

return
}

#=============================================================================
function get_absolute_path ()
{
# Get the absulute path of the given relative path.
# Values are transferred to and from this function via given variable names.
# Additional normal values can be supplied.
# Local variables should surrounded by _  ( ret --> _ret_ ).
# Call: get_absolute_path mytransfer
#
# We use 1 returned value in its transfer variable:
# par1 = name of transfer variable (content = rel path)
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG get_absolute_path: $# $@" >&2
	$debuglog get_absolute_path: $# $@
fi

#	n=name			v=value
local get_absolute_path_n1="$1" get_absolute_path_v1="${!1}"
local _fpath_=''
local _ret_=0

# do the stuff
cd ${get_absolute_path_v1}
_fpath_=$(pwd)
cd $OLDPWD
_ret_=$?

# return values
eval ${get_absolute_path_n1}="\"${_fpath_}\""

return ${_ret_}
}

#=============================================================================
function create_new_path ()
{
# Create a new path and store it in the mcf.
# par1 = media control file
# par2 = media file
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG create_new_path: $# $@" >&2
	$debuglog create_new_path: $# $@
fi

local mdir='' mcf="$1" mf="$2"
local ret=0

mdir=$(dirname $mf)					# media dir
get_absolute_path mdir
ret=$?

rm -f $tempfile
# copy mcf to tempfile and replace line MDIR with new path
while read; do
	if [ "${REPLY:0:4}" != MDIR ]; then
		echo "$REPLY" >> $tempfile
	else
		REPLY="MDIR=\"${mdir}\""
		echo "$REPLY" >> $tempfile
	fi
done<$mcf
ret=$?

cp $tempfile $mcf
rm -f $tempfile
ret=$?

return $ret
}

#=============================================================================
function append_items ()
{
# Append items to a media control file.
# par1 = media control file
# par2 = media file
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG append_items: $# $@" >&2
	$debuglog append_items: $# $@
fi

local mcf="$1" mf="$2" mfile='' s=''
local i=0 ret=0

mfile=$(basename $mf)					# media file name

source $mcf

if [ -n "$audio" ]; then
	maxTRACK="${#TRACK[@]}"
	i="$maxTRACK"
	let ++i
	echo "TRACK[${i}]=\"$mfile\"" >> $mcf		# write 1. mf
	for s in $args; do				# all remain. tracks
		let ++i
		s=$(basename $s)
		echo "TRACK[${i}]=\"$s\"" >> $mcf
	done
else
	maxCHAPTER="${#CHAPTER[@]}"
	i="$maxCHAPTER"
	test -z "$args" && args=0
	for s in $args; do				# all chp pos
		let ++i
		echo "CHAPTER[${i}]=\"$mfile	$s	C ${i}: ${mfile%%.*}\"" >> $mcf
	done
fi

ret=$?

return $ret
}

#=============================================================================
function append_start_items ()
{
# Append items to a media control file.
# par1 = media control file
# par2 = media file
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG append_start_items: $# $@" >&2
	$debuglog append_start_items: $# $@
fi

local mcf="$1" mf="$2" mfile='' s=''
local i=0 ret=0

mfile=$(basename $mf)					# media file name

source $mcf
if [ "$MTYPE" == AUDIO ]; then
	if [ -z "$opt_s" ]; then			# ok is audio
		maxTRACK="${#TRACK[@]}"
		i="$maxTRACK"
		let ++i
		echo "TRACK[${i}]=\"$mfile\"" >> $mcf	# write 1. mf
		for s in $args; do			# all remain. tracks
			let ++i
			s=$(basename $s)
			echo "TRACK[${i}]=\"$s\"" >> $mcf
		done
		ret=$?
	else						# not ok is not audio
		Show_Err 13 "-s"
		ret=13
	fi
else
	maxCHAPTER="${#CHAPTER[@]}"
	i="$maxCHAPTER"
	test -z "$args" && args=0
	for s in $args; do				# all chp pos
		let ++i
		echo "CHAPTER[${i}]=\"-${mfile}	$s	C ${i}: \"" >> $mcf
	done
	ret=$?
fi

return $ret
}

#=============================================================================
function append_mp4 ()
{
# Append a mp4 to a media control file.
# par1 = media control file
# par2 = media file
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG append_mp4: $# $@" >&2
	$debuglog append_mp4: $# $@
fi

local mcf="$1" mf="$2" mfile='' s='' ss='' tfile=''
local i=0 ret=0

mfile=$(basename $mf)					# media file name

source $mcf

if [ -n "$audio" ]; then
	echo "Error - is not an video"
	ret=1
else
	maxCHAPTER="${#CHAPTER[@]}"
	i="$maxCHAPTER"
	test -z "$args" && args=0
	for s in $args; do				# all chp pos
		let ++i
		tfile=${mfile%.*}
		echo "CHAPTER[${i}]=\"$mfile	$s	Video ${i}: ${tfile%.*}\"" >> $mcf
	done
	ret=$?
fi

return $ret
}

#=============================================================================
function append_all ()
{
# Append all mp4
# par1 = 
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG append_all: $# $@" >&2
	$debuglog append_all: $# $@
fi

local s=''
local i=0 ret=0

i=0
for s in *.mp4; do
	let ++i
	if [ "$i" -eq 1 ]; then
		mainproc $arg1 $s
	else
		append_mp4 $arg1 $s
	fi
done
ret=$?

return $ret
}

#=============================================================================
function mainproc ()
{
# Create a media control file in actual dir.
# par1 = media control file
# par2 = media file
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG mainproc: $# $@" >&2
	$debuglog mainproc: $# $@
fi

local mcf="$1" mf="$2" mdir='' mfile='' tfile='' mt='' s=''
local i=0 ret=0
#local -a arr
#maxarr="${#arr[@]}"			# get number of elements in arr
#unset arr[@]				# remove the entire array

mdir=$(dirname $mf)					# media dir
mfile=$(basename $mf)					# media file name

get_absolute_path mdir					# get absolute path
ret=$?

mt="${mcf##*/}"						# media title
mt="${mt%.*}"						# media title

echo "TITLE=\"${mt}\"" > $mcf
if [ -n "$audio" ]; then				# is audio
	echo "MTYPE=\"AUDIO\"" >> $mcf
else							# is video
	echo "MTYPE=\"VIDEO\"" >> $mcf
fi
echo "MDIR=\"$mdir\"" >> $mcf
echo "GLOBOPT=\"\"" >> $mcf

if [ -n "$audio" ]; then				# is audio
	echo "$audiotipp" >> $mcf			# write 1 line of help
	echo >> $mcf
	echo "TRACK[1]=\"$mfile\"" >> $mcf
	i=1
	for s in $args; do				# all tracks
		let ++i
		s=$(basename $s)
		echo "TRACK[${i}]=\"$s\"" >> $mcf
	done
else							# is video
	echo "$videotipp" >> $mcf			# write 1 line of help
	echo >> $mcf
	test -z "$args" && args=0
	i=0
	for s in $args; do				# all chp pos
		let ++i
		if [ $i -eq 1 ]; then			# pre fill in entry
			if [ "$cmd" == -A ]; then	# create for all mp4
				tfile=${mfile%.*}
				if [ -z "$opt_s" ]; then
					echo "CHAPTER[${i}]=\"$mfile	$s	Video ${i}: ${tfile%.*}\"" >> $mcf
				else
					echo "CHAPTER[${i}]=\"$mfile	$s	Video ${i}: ${tfile%.*}\"" >> $mcf
				fi
			else
				if [ -z "$opt_s" ]; then
					echo "CHAPTER[${i}]=\"$mfile	$s	Video ${i}: ${tfile%.*}\"" >> $mcf
				else
					echo "CHAPTER[${i}]=\"-${mfile}	$s	Video ${i}: ${tfile%.*}\"" >> $mcf
				fi
			fi
		else					# only pur entry
			if [ -z "$opt_s" ]; then
				echo "CHAPTER[${i}]=\"$mfile	$s	C ${i}: \"" >> $mcf
			else
				echo "CHAPTER[${i}]=\"-${mfile}	$s	C ${i}: \"" >> $mcf
			fi
		fi
	done
fi
ret=$?

return $ret
}

##############################################################################
# GET OPTIONS
##############################################################################
# Give 2 strings and all cmdline_args to func GetOpt
# (POSIX_options Gnu_long_options cmdline_args):
# GetOpt 'hVdqvi:m:' 'help version debug quiet verbose infile= myval=' $@
#
# A ':' after a POSIX option means this option needs an arg.
# A '=' after a Gnu long option means this option needs an arg.
#
# All cmd/options have to be initialised to ''!
#
# POSIX options are classified in 2 categories:
#   a) cmds (mutually exclusive). All cmds are given to var 'cmd'.
#   b) options (as many as you like). Each option is given to it's own var.
# As a general rule: If cmds/options are given multiple then last given wins.
#
# Options can take 1 argument (no whitespace in arg). If you want to give more
# than 1 arg or want to use multiple strings as 1 arg then concatenate them
# together with a delimiter like ',' or ';' or '.'
# Use a delimiter which will not be part of the arg:
# sampleprog -m val1,val2
# sampleprog --myval=val1,val2
# It's at the programmers responsibility to do meaningfull things with the
# content of the options.
#
# If err != 0 then all args are processed, else continue to look for options.
# When GetOpt finishes then all options are removed from cmdline.
#
if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG Parse Commandline: $# $@" >&2
	$debuglog Parse Commandline: $# $@
fi
#
err=0
while [ "$err" -eq 0 ]; do
	GetOpt 'hVdqvAaus' 'help version debug quiet verbose audio' $@
	err=$?
	if [ $err -eq 0 ]; then
		case "$_OPTNAME_" in
		    h|help)	cmd="-h";;
		    V|version)	cmd="-V";;
		    A)		cmd="-${_OPTNAME_}";;
		    a)		cmd="-${_OPTNAME_}";;
		    u)		cmd="-${_OPTNAME_}";;
		    d|debug)	debug=yes;;
		    q|quiet)	verbose=no;;
		    v|verbose)	verbose=yes;;
		    audio)	audio=yes;;
		    s)		opt_s=yes;;
#		    o|output)	opt_o=yes;;
#		    i|infile)	opt_i="${_OPTVAL_}";;
#		    o|outfile)	opt_o="${_OPTVAL_}";;
#		    p|pages)	opt_p="${_OPTVAL_}";;
		    --)		break;;
		    :)	Show_Err ${_ERR_MISSING_ARG_FOR_OPT_} "-${_OPTVAL_}"
			exit ${_ERR_MISSING_ARG_FOR_OPT_};;
		    ?)	Show_Err ${_ERR_UNKNOWN_OPT_} "-${_OPTVAL_}"
			exit ${_ERR_UNKNOWN_OPT_};;
		    *)	Show_Err ${_ERR_UNKNOWN_ERR_} "_OPTNAME_=${_OPTNAME_} _OPTVAL_=${_OPTVAL_}"
			exit ${_ERR_UNKNOWN_ERR_};;
		esac
	fi
done
err=0
shift ${_OPTIDX_}				# rm all opts from cmdline
#
# Uncomment if giving a cmd is mandatory
#if [ -z "$cmd" ]; then					# error no cmd given
#	Show_Err 7 ""
#	exit 7
#fi

##############################################################################
# CHECK LINK NAMES
##############################################################################
# CHECK OPTIONS
#
#-----------------------------------------------------------------------------
# check not allowed option for sub commands
#case "$cmd" in
#    -l|-p)						# for these cmds
#	if [ -n "$opt_z" ]; then			# option -z not allowed
#		Show_Err ${_ERR_OPT_NOT_ALLOWED_} "-z"
#		exit ${_ERR_OPT_NOT_ALLOWED_}
#	fi
#	;;
#    *)							# for all other cmds
#	:
#	;;
#esac
#
#-----------------------------------------------------------------------------
# check allowed option for sub commands
#if [ -n "$opt_z" ]; then
#	case "$cmd" in
#	    -l|-p)					# for these cmds
#		:					# option -z allowed
#		;;
#	    *)						# for all other cmds
#		Show_Err ${_ERR_OPT_NOT_ALLOWED_} "-z"
#		exit ${_ERR_OPT_NOT_ALLOWED_}
#		;;
#	esac
#fi
#
#-----------------------------------------------------------------------------
# check needed option for sub commands
#case "$cmd" in
#    -l|-p)						# for these cmds
#	if [ -z "$opt_z" ]; then			# option -z needed
#		Show_Err ${_ERR_MISSING_ARG_FOR_OPT_} "-z"
#		exit ${_ERR_MISSING_ARG_FOR_OPT_}
#	fi
#	;;
#    *)							# for all other cmds
#	:
#	;;
#esac
#
#-----------------------------------------------------------------------------
# check options which are mutually exclusive
if [ -n "$audio" ] && [ -n "$opt_s" ]; then		# don't give both opts
		Show_Err ${_ERR_OPT_NOT_ALLOWED_} "${audio} and ${opt_s} given"
		exit ${_ERR_OPT_NOT_ALLOWED_}
fi
#
#-----------------------------------------------------------------------------
# check option which needs another option
#if [ -n "$opt_x" ]; then			# opt_x given
#	if [ -z "$opt_y" ]; then		# error - opt_x needs opt_y
#		Show_Err ${_ERR_GENERAL_} "-x needs -y"
#		exit ${_ERR_GENERAL_}
#	fi
#fi
#
#-----------------------------------------------------------------------------
# check options which needs to give at least one of them
#case "$cmd" in
#    '')
#	if [ -z "$opt_x" ] && [ -z "$opt_y" ]; then	# no option given
#		Show_Err ${_ERR_GENERAL_} "give -x and/or -y"
#		exit ${_ERR_GENERAL_}
#	fi
#esac
#
#-----------------------------------------------------------------------------
# get values from arg of option -p to vars p_first p_last
#if [ -n "$opt_p" ]; then
#	p_first="${opt_p%,*}"
#	p_last="${opt_p#*,}"
#fi
#
##############################################################################
# CHECK VERSION
##############################################################################
# CHECK ARGUMENTS
#
case "$cmd" in
    ''|-a|-u)
	if [ "$#" -ge 2 ]; then				# parameter count ok
		arg1="$1"
		arg2="$2"
		shift 2
		args="$@"
		shift $#
	else						# error in param count
		Show_Err 2 ""
		exit 2
	fi
	;;
    -A)
	if [ "$#" -eq 1 ]; then				# parameter count ok
		arg1="$1"
		shift
	else						# error in param count
		Show_Err 2 ""
		exit 2
	fi
	;;
    *)
	if [ "$#" -ne 0 ]; then				# error in param count
		Show_Err 2 ""
		exit 2
	fi
	;;
esac
#
##############################################################################
# LOCK

##############################################################################
# MAINPROGRAM
##############################################################################
#
if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG Main: $# $@" >&2
	$debuglog Main: $# $@
fi

if [ "$cmd" != "-h" ] && [ "$cmd" != "-V" ]; then
	if [ "${arg1##*.}" != mcf ];then
		Show_Err 1 "File $arg1 is not an mcf"
		exit 1
	fi

	if [ "$cmd" != -A ] && [ "${arg2:0:1}" == "-" ];then
		Show_Err 1 "Media files should not start with '-'"
		exit 1
	fi
fi

# Check what to do (sub commands, options and args are removed from cmdline)
case "$cmd" in
    '')
	mainproc $arg1 $arg2
	err=$?
	;;
    -h)
	helptext
	exit 0
	;;
    -V)
	echo "${scriptname}: (${package}) $package_file ${version}-${release}"
	exit 0
	;;
    -A)
	append_all
	err=$?
	;;
    -a)
	if [ -z "$opt_s" ]; then
		append_items $arg1 $arg2
		err=$?
	else
		append_start_items $arg1 $arg2
		err=$?
	fi
	;;
    -u)
	create_new_path $arg1 $arg2
	err=$?
	;;
    *)							# other cmds = error
	Show_Err 6 ""
	err=6
	;;
esac

#rm -f $lockfile

exit $err
