#!/bin/bash
#nathan jahnke <njahnke@gmail.com>

if [ -z $1 ] ; then echo "Usage: $0 videofile (without .avi extension) framecount" ; exit 1 ; fi

video="$1.avi"
frames=$2
framesperfile=1000
windowsize=200
outdir="$1"

rm -f "${outdir}.avs" ; rm -rf "${outdir}" ; mkdir "${outdir}"

i=1
while [ $i -le ${frames} ] ; do
	
	tempnum=`expr ${i} + 9`
	tempfilename=`expr ${tempnum} / ${framesperfile}`
	echo -n '' > "${outdir}/${tempfilename}.avs"
	
	if [ ${tempfilename} -ne 0 ] ; then
		echo '++\' >> "${outdir}.avs"
	fi
	echo -n 'avisource("'"${outdir}/${tempfilename}"'.avi")' >> "${outdir}.avs"
	
	j=1
	while [ $j -le ${framesperfile} ] ; do
	
		if [ ${i} -le ${frames} ] ; then
		
			echo 'directshowsource("../'${video}'")
converttoyuy2
trim('`expr ${i} - 1`','`expr ${i} + ${windowsize}`'-2)
autocrop(mode=0,wMultOf=2,hMultOf=2,threshold=100,samples=10)
lanczos4resize(508,386)
' >> "${outdir}/${tempfilename}.avs"
			
			if [ ! ${j} -eq 1 ] ; then #first window for this file doesn't need tempvid set
				echo 'tempvid++last' >> "${outdir}/${tempfilename}.avs"
			fi
			
			if [ ! ${j} -eq `expr ${framesperfile} - ${windowsize} + 1` ] ; then #not last frame for this file yet
				if [ `expr ${i} + ${windowsize}` -le ${frames} ] ; then #at least one more frame to go
					echo 'tempvid=last' >> "${outdir}/${tempfilename}.avs"
				fi
			fi
		
		fi
		
		i=$[ $i + ${windowsize} ]
		j=$[ $j + ${windowsize} ]
	done
done

echo '
thevideo=last

oldaudio=thevideo.killvideo.normalize
newaudio=wavsource("'"$1"'.wav").normalize.delayaudio(-2)

audiodub(thevideo,monotostereo(oldaudio,newaudio.converttomono))
#audiodub(thevideo,newaudio)' >> "${outdir}.avs"

exit 0
