#!/bin/bash

#
# Script for run the test programs to check the hitmap library. 
#
# @version 1.0 (Jun 2010)
# @version 1.1 (Oct 2011)
# @date Oct 2011
# @author Javier Fresno Bausela

 #
 # This software is provided to enhance knowledge and encourage progress
 # in the scientific community and are to be used only for research and
 # educational purposes. Any reproduction or use for commercial purpose
 # is prohibited without the prior express written permission.
 # 
 # This software is provided "as is" and without any express or implied
 # warranties, including, without limitation, the implied warranties of
 # merchantability and fitness for a particular purpose.
 # 
 # Copyright (c) 2007-2011, Arturo Gonzalez Escribano
 #                          Javier Fresno Bausela
 #                          Carlos de Blas Carton
 #                          Yuri Torres de la Sierra
 # All Rights Reserved.
 #


function runtest1
{
	mpi="$1"
	nprocs="$2"

	# Names of the test and test solution
	testprogram="$3"
	testsolution="$3.out"

	if [ ! -f "$testprogram" ]
	then
		echo "Executable $testprogram don't exists"
		exit
	fi

	if [ ! -f "$testsolution" ]
	then
		echo "Solution $testsolution don't exists"
		exit
	fi


	# Create a temporal file
	output=$(tempfile) || exit


	if [ "$mpi" = "true" ] ; then
		mpiexec -n $nprocs $testprogram > $output 2>/dev/null
	else
		$testprogram > $output 2>/dev/null
	fi

	if [ ! "$?" = 0 ]; then
		echo -e "$testprogram:\tExecution Error"
		return
	fi


	result=$(diff -q  "$testsolution" "$output") 

	if [ "$result" ]
	then
		echo -e "$testprogram:\tError"
	else
		echo -e "$testprogram:\tOK"
	fi

	# Delete the temporal file
	rm -f "$outpput"
}


function createtest
{

	mpi="$1"
	nprocs="$2"

	# Names of the test and test solution
	testprogram="$3"
	testsolution="$3.out"

	if [ ! -f "$testprogram" ]
	then
		echo "Executable $testprogram don't exists"
		exit
	fi

	if [ "$mpi" = "true" ] ; then
		mpiexec -n $nprocs $testprogram > $testsolution 
	else
		$testprogram > $testsolution 
	fi

	echo -e "$testprogram:\tOK"

}

function show_help
{
	echo "$1 [-c] [-n NPROCS] [test]"
	echo " Without options: Execute all the tests"
	echo " -c: Create the test ouput"
	echo " -n<NUM>: Number of processor for mpi."
}


#flags
create=false
mpi=false
nprocs=0

# Read the script parameters
while getopts hcn: o
	do
	case "$o" in
		c)		create=true;;
		n)		nprocs="$OPTARG"; mpi=true;;
		h)		show_help $0; exit 1;;
		[?])	show_help $0; exit 1;;
	esac
	done
shift $((OPTIND-1))



if [ "$create" = "true" ]; then

	if [ "$1" = "" ]; then
	echo "Creating test output"

		# testSparse
		./runtest -c testSparseSelectExpand
		./runtest -c -n 2 testSparse
		./runtest -c -n 2 testBitmap

		exit
	else
		createtest $mpi $nprocs $1
	fi
	exit
fi




if [ "$1" = "" ]; then
	echo "Executing all tests"

	./runtest testSparseSelectExpand
	./runtest -n 2 testSparse
	./runtest -n 2 testBitmap

	exit
fi


runtest1 $mpi $nprocs $1





