#!/bin/sh
def_frames=150
def_ratio=2
def_signal=1
def_aspect=1

help(){
	cat <<END
Usage: $0 <filename.[png|jpg]>
Options:
	-n n      Number of fames per image             ($def_frames)
	-s n      n=1 keep aspect, n=2 stetch           ($def_aspect)
	-v n      Video Signal, n=1 ntsc n=2 pal        ($def_signal)
	-r n      Aspect Ratio, n=1 4:3 n=2 16:9        ($def_ratio)
END
	exit 1
}

frames=$def_frames
signal=$def_signal
ratio=$def_ratio
aspect=$def_aspect

while getopts n:v:r:s:h name "$@"
do
    case $name in
n)
    frames=$OPTARG ;;
s)
	aspect=$OPTARG ;;
r)
	ratio=$OPTARG ;;
v)
    signal=$OPTARG ;;
*)
    help ;;
    esac
done
let shiftind=$OPTIND-1
shift $shiftind

case $signal in
2)
	Vflag="25:1"
	Nflag="pal"
	fwidth="720"
	fheight="576"
	case $ratio in
2)
		let sw=16
		let sh=9
		Rflag="236:99" ;;
*)
		let sw=4
		let sh=3
		Rflag="59:54" ;;
	esac ;;
*)
	Vflag="30000:1001"
	Nflag="ntsc"
	fwidth="720"
	fheight="480"
	case $ratio in
2)
		let sw=16
		let sh=9
		Rflag="40:33" ;;
*)
		let sw=4
		let sh=3
		Rflag="10:11" ;;
	esac ;;
esac

if test "$#" != "1"
then
	help
fi
case $1 in
*.jpg)
    ifilter=jpegtopnm
    input="$1"
    base=`echo $input | sed "s/\.jpg$//"` ;;
*.png)
	ifilter=pngtopnm
	input="$1"
	base=`echo $input | sed "s/\.png$//"` ;;
*)
	help ;;
esac

iwxh=`$ifilter $input | head -2 | tail -1`
iheight=`echo $iwxh | sed "s/^[^ ]* *//g"` 
iwidth=`echo $iwxh | sed "s/ *[^ ]*$//g"`
let sheight=$iheight*$sw
let swidth=$iwidth*$sh
if test "$sheight" -gt "$swidth"
then
	let owidth=$sheight/$sh
	let owidth=\(\($owidth+3\)/4\)*4
	let oheight=$iheight
else
	let owidth=$iwidth
	let owidth=\(\($owidth+3\)/4\)*4
	let oheight=$owidth*$sh/$sw
fi
let dw=$owidth-$iwidth
let dh=$oheight-$iheight
let fl=$dw/2
let fr=$dw-$fl
let ft=$dh/2
let fb=$dh-$ft
echo "Transcoding $input to $base.qt..."
#echo "-l$fl -r$fl -t$ft -b$fb"

case $aspect in
1)
    padprog="pnmpad -black -l$fl -r$fl -t$ft -b$fb"
echo "($iwidth x $iheight) pad ($owidth x $oheight) scale ($fwidth x $fheight)"
	;;
*)
	padprog=cat
echo "($iwidth x $iheight) scale ($fwidth x $fheight)"
	;;
esac

sleep 1
$ifilter $input |
$padprog |
pnmscale -height=$fheight -width=$fwidth |
ppmtoy4m -A $Rflag -F $Vflag -n $frames -r -I p -S 420mpeg2 |
yuvscaler -ODVD -n$Nflag |
yuv2lav -I0 -fq -o "$base".qt
