#!/bin/sh

help(){
    cat <<END
Usage: $0 [options] <filename>.[mpg|m2t]
Options:
END
    exit 0
}

while getopts h name "$@"
do
    case $name in
*)
    help ;;
    esac
done
let shiftind=$OPTIND-1
shift $shiftind

if test "$#" != "1"
then
    help
fi
case $1 in
*.m2t)
    input="$1"
    base=`echo $input | sed "s/\.m2t$//"` ;;
*.mpg)
    input="$1"
    base=`echo $input | sed "s/\.mpg$//"` ;;
*)
    help ;;
esac

echo HDV $input to ${base}s.mpg video...

rm -f $base.p0 $base.p1 $base.p2
mknod $base.p0 p
mknod $base.p1 p
mknod $base.p2 p

ffmpeg -i $input -f s16le -y $base.raw
sox -V -s -w -c2 -r24000 $base.raw -r48000 ${base}s.wav
sox -V -s -w -c2 -r48000 $base.raw -r48000 ${base}.wav
mplayer -nosound -vo yuv4mpeg:file=$base.p0 \
    -vf tfields=1:0,boxblur=1:1 $input </dev/null &

yuvfps -s 30000:1001 -r 30000:1001 2>/dev/null < $base.p0 |
    yuvcorrect -T PROGRESSIVE 2>/dev/null |
    yuvscaler -nn -M BICUBIC -O SIZE_720x480 2>/dev/null |
    tee $base.p1 $base.p2 | 
    yuv2lav -I0 -q85 -w ${base}s.wav -o ${base}s.mov &
yuvfps -s 60000:1001 -r 60000:1001 2>/dev/null < $base.p1 |
    y4minterlace -it |
    yuv2lav -I0 -q90 -w ${base}.wav -o ${base}i.mov &
yuvfps -s 60000:1001 -r 30000:1001 2>/dev/null < $base.p2 |
    yuv2lav -I0 -q90 -w ${base}.wav -o ${base}p.mov
