#!/bin/bash
if [ -z "$1" ]; then
echo usage: $0 number_of_loops
exit
fi

NumLoops=$1
TimingResultsFile="./TimingResultsHDGHelmSolve2D.dat"
ExecutableDumpFile="./TimingHDGHelmSolve2D.dat"
MinTimeFile="./MinTimeHDG2D.dat"

MaxNumModesp1=16;

echo "%     Solver  optlevel  Type  nElements     nModes    Time   nCalls   Time/Call    L2Error  ppL2Error L2Error(hi-res)   LinfError   ppLinfErr  LinfErr(hi-res)  nLocCoef  nGlobCoef  nLocBCoef nGlobBCoef  nLocDCoef nGlobDCoef   GlobRank  GlobBndwth   nnz   FullSolveTime  ppTime" > $TimingResultsFile

# Loop over the mesh-size
for MeshSize in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
do
	# Loop over the element type: 1 - RQuad, 2 - DQuad, 3 - RTri
	for Type in 1 3
	do
		# Loop over the LinSysSolver type: 0 - DirectStaticCond, 1 - DirectMultiLevelStaticCond, 2 - IterativeStaticCond, 3 - IterativeMultiLevelStaticCond
		for LinSysSolver in 0 1 2 3
		do
			# Loop over the optimisation level: 0 - ElSumFac, 2 - ElBlkMat, 3 - GlbMat 
			for OptimisationLevel in 0 2 3
			do
				# Loop over the number of modes
				for ((NumModes=2; NumModes<MaxNumModesp1; NumModes++))
				do                
					# Initialise the minimal time to a really big value 
					MinTime=10000000000000000;

					# Loop over the number of Loops you want to run it
					for ((a=0; a<NumLoops; a++))
					do
						TimingHDGHelmSolve2D $Type $MeshSize $NumModes $OptimisationLevel $LinSysSolver
						echo Nektar++ TimingHDGHelmSolve2D $Type $MeshSize $NumModes $OptimisationLevel $LinSysSolver

						read  LinSysSolverOut optLevelOut TypeOut NumElementsOut NumModesOut ElapsedTimeOut NumCallsOut TimepCallOut L2Out ppL2Out L2OutBis LinfOut ppLinfOut LinfOutBis nLocCoefOut  nGlobCoefOut nLocBCoefOut  nGlobBCoefOut  nLocDCoefOut nGlobDCoefOut GlobRankOut GlobBndwthOut nnzOut FullSolveTimeOut ppTimeOut< $ExecutableDumpFile
						comp=`echo "$ElapsedTimeOut < $MinTime" | bc -l`
						if [ $comp -eq 1 ]; 
						then
							MinTime=$ElapsedTimeOut
							cp $ExecutableDumpFile $MinTimeFile
						fi
					done

					cat $MinTimeFile >> $TimingResultsFile
				done
			done
		done
	done
done

rm -f $MinTimeFile
rm -f $ExecutableDumpFile
