#!/bin/bash

# --------------
# Configuration:
# --------------

# Test image
TEST_IMAGE=lena-orig.png

# Tool locations
SSIM=tools/ssim.exe
X264=tools/x264.exe
FFMPEG=tools/ffmpeg.exe
CWEBP=tools/cwebp.exe
DWEBP=tools/dwebp.exe
PSUTIL=tools/photoshop.vbs
IMAGICK=/c/Progra~2/ImageMagick/convert.exe

# Our location
WINPWD=C:\\Users\\Mason\\Documents\\DEV\\ssim

# -----------------
# Helper functions:
# -----------------

function header {
	echo "# "   >> results.dat
	echo "# ======================================" >> results.dat
	echo "#" $1 >> results.dat
	echo "# ======================================" >> results.dat
	echo "# "   >> results.dat
}

# ---------------
# Test functions:
# ---------------

function test_x264 {
	echo "Testing x264 at crf $1"
	$X264 $2 --frames 1 --crf $1 test.avs -o test.264
	SIZE=$(stat -c%s test.264)
	$FFMPEG -i test.264 test.png
	QUAL=$($SSIM $TEST_IMAGE test.png)
	echo $SIZE,$QUAL >> results.dat
	rm test.png
	rm test.264
}

function test_webp {
	echo "Testing WebP at q $1"
	$CWEBP -q $1 $TEST_IMAGE -o test.webp
	SIZE=$(stat -c%s test.webp)
	$DWEBP test.webp -o test.png
	QUAL=$($SSIM $TEST_IMAGE test.png)
	echo $SIZE,$QUAL >> results.dat
	rm test.png
	rm test.webp
}

function test_imagick {
	RATE=$(echo "scale=3; $1 / 1000" | bc)
	echo "Testing ImageMagick at rate $RATE"
	
	$IMAGICK $TEST_IMAGE -define jp2:rate=$RATE test.jp2
	SIZE=$(stat -c%s test.jp2)
	$IMAGICK test.jp2 test.png
	QUAL=$($SSIM $TEST_IMAGE test.png)
	echo $SIZE,$QUAL >> results.dat
	rm test.png
	rm test.jp2
}

# ------------
# Test script:
# ------------

# Clear results

echo "" > results.dat

# Test Photoshop

header "Photoshop"
mkdir pstemp
cscript $PSUTIL $WINPWD\\$TEST_IMAGE $WINPWD\\pstemp\\ 
echo "Checking SSIM..."
for i in {1..100};
do
	SIZE=$(stat -c%s pstemp/$i.jpg)
	$IMAGICK pstemp/$i.jpg test.png
	QUAL=$($SSIM $TEST_IMAGE test.png)
	echo $SIZE,$QUAL >> results.dat
	rm test.png
	rm pstemp/$i.jpg;
done
rmdir pstemp

# Test x264, trial A

header "x264 (placebo)"
echo "ImageSource(\"$TEST_IMAGE\")" > test.avs
for i in {1..50};
do
	test_x264 $i "--preset placebo";
done
rm test.avs

# Test x264, trial B

header "x264 (placebo, ssim)"
echo "ImageSource(\"$TEST_IMAGE\")" > test.avs
for i in {1..50};
do
	test_x264 $i "--preset placebo --tune ssim";
done
rm test.avs

# Test WebP

header "WebP -preset default"
for i in {1..100};
do
	test_webp $i;
done

# Test JP2k

header "ImageMagick JPEG2000"
for i in {1..20};
do
	test_imagick $i;
done
for i in $(seq 30 10 500);
do
	test_imagick $i;
done

# Tidy up

echo "All tests completed."