#!/bin/bash

# This script uses the meshtool program
# to write each of the reference elements
# to a tecplot file.

# Relative location of meshtool
meshtool=../bin/meshtool

# Relative location of reference elements
ref_element_dir=../reference_elements

# Relative location of gold standard
gold=./gold

# Relative location of meshtool
meshtooldir=../bin

# Program paths
diff=`which diff`
make=`which make`

# Regression test log file
log=./write_reference_elements.log

# Separating line
sep="=================================================="

# Define file extensions
ext=(plt dat gmv xda xdr ugrid)

# Make sure the meshtool is built
if ! test -x $meshtool; then
    # Try to build it...
    echo "Try to build meshtool..."
    $make -C ../ bin/meshtool
fi

# Generic testing function
# $1 is the filename
# $2 is the dimension
function do_test()
{
    base=`basename $1 | cut -d"." -f1`

    elt_type=`echo $base | cut -d"_" -f2`
    
    echo "$elt_type"
    
    for j in ${ext[*]}; do
	testfile=$base.$j
	$meshtool -d$2 -i $1 -o $testfile -v 2>> $log 1>/dev/null
	echo $diff $meshtooldir/$testfile $gold/$testfile
	diffs=`$diff $meshtooldir/$testfile $gold/$testfile`
	if test "x$diffs" != "x"; then

	    # Is it really different? If the word Id
	    # is found in the diffs, and there is only
	    # only line of diffs, then it's probably
	    # not a real change.
	    id_changed=`echo $diffs | grep -c "Id"`
	    n_diffs=`echo $diffs | wc -l`

	    if test $id_changed -eq 0 && $n_diffs -ge 1; then
	    
		echo "Differences found writing $testfile!";
		echo "See $log for details...";
		
	        # Write information to log file
		echo "Errors found in: $testfile" >> $log
		echo $diffs >> $log

		echo -e "\n\n$sep" >> $log
		echo "| Generated file" >> $log
		echo $sep >> $log
		cat $testfile >> $log
		echo $sep >> $log
		
		echo -e "\n\n$sep" >> $log
		echo "| Gold Standard" >> $log
		echo $sep >> $log
		cat $gold/$testfile >> $log
		echo $sep >> $log
	    fi
	fi
	
	rm -f $testfile
    done 
}


echo "Testing reference element write routines:" > $log

# Test 2D elements 
for i in `ls $ref_element_dir/2D/*.xda`; do
    do_test $i 2
done

# Test 3D elements
for i in `ls $ref_element_dir/3D/*.xda`; do
    do_test $i 3
done

