#!/bin/bash -e
#
# A FEEDS test which transforms an image, and does its own
# evaluation by comparing the result to a image
# benchmark using two different metrics.

outdir=$1
benchmarkdir=$3

# Apply the transform to the data
flirt -in ./input.nii.gz                                    \
      -ref $FSLDIR/data/standard/MNI152_T1_2mm_brain.nii.gz \
      -applyxfm                                             \
      -init ./xform.mat                                     \
      -out $outdir/data_xformed.nii.gz

benchmark=$benchmarkdir/data_xformed.nii.gz

# Calculate the difference between the
# transformed image and the benchmark image
fslmaths $outdir/data_xformed -sub $benchmark $outdir/diff.nii.gz

# Calculate the mean error (normalised) between
# the flirt output and the benchmark
norm=`fslstats $benchmark -a -m`
error1=`fslstats $outdir/diff -a -m`
error1=`echo $error1 / $norm | bc -l`
error2=`fslstats $outdir/diff -P 99`
error2=`echo $error2 / $norm | bc -l`

thresh1=0.001; thresh2=0.01;

# If normalised error is < thresh, we
# consider that the test is a pass
if [[ `echo "$thresh1 < $error1" | bc` -eq "1" ]]; then
    echo "Test failed: error1 = $error1"
    exit 1
fi
if [[ `echo "$thresh2 < $error2" | bc` -eq "1" ]]; then
    echo "Test failed: error2 = $error2"
    exit 1
fi
exit 0
