#!/bin/bash

#--- Functions ---------------------------------------------------------------

rmframes()
{
	rm 0*0.png 2> /dev/null
	rm 0*1.png 2> /dev/null
	rm 0*2.png 2> /dev/null
	rm 0*3.png 2> /dev/null
	rm 0*4.png 2> /dev/null
	rm 0*5.png 2> /dev/null
	rm 0*6.png 2> /dev/null
	rm 0*7.png 2> /dev/null
	rm 0*8.png 2> /dev/null
	rm 0*9.png 2> /dev/null
}

makestats()
{
	# This function uses ImageMagic to compare an encoded movie to its original.
	# It requires as a parameter a path name where the original movie frames can
	# be found in the form of PNG bitmaps.
	# The second required parameter is the name of the encoded movie file to
	# compare. The third parameter is a name given to the test, the movie file
	# name is otherwise used by default. This name must not contain spaces.
	
	if [ -n "${3}" ]; then
		TESTNAME=${3}
	else
		TESTNAME=${2%%.*}
	fi
	
	echo "Frame q s Y Cb Cr PSNR t" > ${2%%.*}-psnrlog.data
	sed -e 's/,/ /g' psnr-${2%%.*}.log >> ${2%%.*}-psnrlog.data
	rmframes
	mplayer ${2} -nosound -vo png:z=0 -frames 12252 -quiet
	echo "Test Frame MAE MSE PSE PSNR RMSE" > ${2%%.*}.data
	for img in 0*.png; do
		echo "$TESTNAME - ${img%%.*}"
		b=$(compare -metric MAE ${1}/$img $img NULL:)
		c="0 dB" #$(compare -metric MSE ${1}/$img $img NULL:)
		d="0 dB" #$(compare -metric PSE ${1}/$img $img NULL:)
		e="0 dB" #$(compare -metric PSNR ${1}/$img $img NULL:)
		f="0 dB" #$(compare -metric RMSE ${1}/$img $img NULL:)
		echo "$TESTNAME ${img%%.*} ${b%% *} ${c%% *} ${d%% *} ${e%% *} ${f%% *}" >> ${2%%.*}.data
	done
	rmframes
}

#--- Main code ---------------------------------------------------------------

if [ "${1}" == "all" ] || [ "${1}" == "ALL" ]; then
	for i in 01 02 03 04 05 06 07 08 09 09v 09c 09f 09p6 09p7 09x2 09x6 09xb 09m 09pre 09dia 10 11 12 13 13v 14 15 15p 15L0 15L1 15L3 15L4 15L4q 15m0 15m1; do
		[ -f a${i}.avi ] && makestats opng a${i}.avi ${i}a
		[ -f a${i}-800.avi ] && makestats opng a${i}-800.avi ${i}a
		[ -f a${i}-1400.avi ] && makestats opng a${i}-1400.avi ${i}b
		[ -f olda${i}.avi ] && makestats opng olda${i}.avi ${i}aold
		[ -f olda${i}-800.avi ] && makestats opng olda${i}-800.avi ${i}aold
		[ -f olda${i}-1400.avi ] && makestats opng olda${i}-1400.avi ${i}bold
	done
else
	makestats opng ${1} ${2}
fi