#! /bin/bash

# verbose than -v: print temporary variables, too
set -x

# stop on error: test_equal may return an error code
# example: test 1 = 2 returns a non-zero error code
# which will be reported to the makefile in which a
# fail target is defined for runtime error reporting
set -e

test_equal() {
    HASH1=$( md5sum $1 | cut -d\  -f1 )
    HASH2=$( md5sum $2 | cut -d\  -f1 )
    test $HASH1 = $HASH2
}

gen_benchmark() {
    wget http://www.ipol.im/pub/art/2013/52/sple_20130711.tgz
    tar xfz sple_20130711.tgz
    rm sple_20130711.tgz
    cd sple_20130711
    # eliminate random influence
    sed -i "s:init_randmt_auto()::g" util.cpp
    # the initial implementation does not trim the trailing white spaces
    sed -i "s:[\t ]*$::g" DataProvider.cpp 
    make OMP=1
    # first test the denoising application
    ./denoiseSPLE ../test/lena.png 10 2 denoised.png
    mv denoised.png patchmap.png ../test
    # next test the imsampling application
    path=$(find ~/Downloads -type d -name "BSD500")
    ./getPaths.sh $path/grays
    ./imsample 10000 5 20 dataCXX.cpp > log
    mv dataCXX.cpp log ../test
    # mission accomplished
    cd ..
    rm -rf sple_20130711
}

run_local() {
    make OMP=1
    ./denoiseSPLE ./test/lena.png 10 2 denoised.png
    path=$(find ~/Downloads -type d -name "BSD500")
    ./getPaths.sh $path/grays
    ./imsample 10000 5 20 dataCXX.cpp 8 > log
}

gen_benchmark
run_local

test_equal log ./test/log
test_equal dataCXX.cpp ./test/dataCXX.cpp
test_equal patchmap.png ./test/patchmap.png
test_equal denoised.png ./test/denoised.png

# if the script does not abort
rm ./test/log ./test/dataCXX.cpp ./test/patchmap.png ./test/denoised.png
