#!/bin/sh

if test x"$srcdir" != x""; then
    builddir="."	# running from make check, but it does not define that
else
    srcdir=`echo "$0" | sed 's,[^/]*$,,'`
    test "$srcdir" = "$0" && srcdir=.
    test -z "$srcdir" && srcdir=.
    builddir="$srcdir"	# running manually, have to assume
fi

srcdir=`cd $srcdir;pwd`
builddir=`cd $builddir;pwd`

testfile="$srcdir/tests"
if [ $# -ge 1 ]; then testfile="$1"; fi

dirs=`cut -d '#' -f 1 $testfile`

basedir=`head -n 1 $testfile | awk '{print $2}'`
cd $srcdir; if [ ! -d $basedir ]; then
    cd ..; if [ ! -d $basedir ]; then exit 77; fi	# for make distcheck
fi
basedir=`cd $basedir;pwd`

# choose between c_md5 and mmx_md5 (based on the idct you use)
md5=c.md5
accel="-c"
if [ $# -ge 2 -a x"$2" != x"c" ]; then md5="$2.md5"; accel=""; fi

cd $builddir
error=0

rm -fr data
mkdir data
cd data

mpeg2dec="../../src/mpeg2dec"; if [ ! -x $mpeg2dec ]; then
    if [ -x ../../vc++/Release/mpeg2dec.exe ]; then
	mpeg2dec="../../vc++/Release/mpeg2dec.exe"
	basedir=`echo "$basedir" | sed "s,/cygdrive/\(.\)/,\1:/,"`
    elif [ -x ../../vc++/Debug/mpeg2dec.exe ]; then
	mpeg2dec="../../vc++/Debug/mpeg2dec.exe"
	basedir=`echo "$basedir" | sed "s,/cygdrive/\(.\)/,\1:/,"`
    else
	echo "Can not find mpeg2dec executable"; exit 1
    fi
fi

for dir in $dirs; do
    if [ -f $basedir/$dir/stream ]; then
	echo $dir
	$mpeg2dec -vvvv $accel -o md5 $basedir/$dir/stream >dump 2>&1 >md5
	if [ ! -f $basedir/$dir/$md5 ]; then
	    echo MISSING FILE $dir/$md5
	elif [ ! -f $basedir/$dir/IGNORE-MD5 ]; then
	    diff -wu md5 $basedir/$dir/$md5 || error=1
	fi
	if [ ! -f $basedir/$dir/dump ]; then
	    echo MISSING FILE $dir/dump
	else
	    sed '1d' dump | diff -wu - $basedir/$dir/dump || error=1
	fi
	rm -f md5 dump core
    else
	echo missing file $dir/stream
    fi
done

cd ..
rmdir data

exit $error
