#!/bin/sh

LISTFILE=$HOME/.movifylist
LISTFILE2=$HOME/.movifylist2
PARAMFILE=$HOME/.movify.param

if [ $# != 1 ]; then
	echo "Usage:"
	echo "  $0 name"
	echo
	echo "  'name' should be the base name of the JPEG or PPM files to encode,"
	echo "  as well as the name of the movie to create.  For example,"
	echo "  '$0 foo' would take foo-1.jpg, foo-2.jpg, etc., and create foo.mpg"
	exit
fi

TYPE=PPM
EXT=ppm
ls $1-[0-9]*.ppm > $LISTFILE 2> /dev/null
if [ $? = 1 ]; then
	TYPE=JPEG
	EXT=jpg
	ls $1-[0-9]*.jpg > $LISTFILE 2> /dev/null
	if [ $? = 1 ]; then
		echo "No files matching $1-*.ppm or $1-*.jpg found"
		exit
	fi
fi

echo `wc -w < $LISTFILE` files found, of type $TYPE
sed -e "s/^$1-"'\([0-9]*\)\.'"$EXT"'$/\1/' < $LISTFILE | sort -n > $LISTFILE2
FIRST=`head -1 $LISTFILE2`
LAST=`tail -1 $LISTFILE2`
if [ `expr $LAST - $FIRST + 1` != `wc -l < $LISTFILE` ]; then
	echo "Files aren't contiguously numbered"
	exit
fi

if [ "$TYPE" = "JPEG" ]; then
	SIZELINE=`djpeg $1-$FIRST.$EXT | head -2 | tail -1`
else
	SIZELINE=`head -2 $1-$FIRST.$EXT | tail -1`
fi
SIZE=`echo $SIZELINE | sed -e 's/^\([0-9]*\) \([0-9]*\) [0-9]*$/\1x\2/'`
echo Image size is: $SIZE

cat > $PARAMFILE <<EOF
PATTERN ibbpbbpbbpbbpbb
OUTPUT `pwd`/$1.mpg
GOP_SIZE 30
SLICES_PER_FRAME 1
FRAME_RATE 24
BASE_FILE_FORMAT $TYPE
YUV_SIZE $SIZE
INPUT_CONVERT *
INPUT_DIR `pwd`
INPUT
$1-*.$EXT [$FIRST-$LAST]
END_INPUT
PIXEL HALF
RANGE 8
PSEARCH_ALG LOGARITHMIC
BSEARCH_ALG SIMPLE
IQSCALE 8
PQSCALE 10
BQSCALE 25
REFERENCE_FRAME ORIGINAL
EOF

mpeg_encode $PARAMFILE

rm -f $LISTFILE $LISTFILE2 $PARAMFILE
