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

NumLoops=$1
OpToTest=$2
ExecutableFile="./TimingGeneralMatrixOp2D-g"
TimingResultsFile="./GeneralMatrixOp2D-$OpToTest.dat"
ExecutableDumpFile="./TimingGeneralMatrixOp2D-$OpToTest.dat"
MinTimeFile="./MinTime2D-$OpToTest.dat"

MaxNumModesp1=16;

types[1]="Quad"
types[3]="Tri"
opts[0]="Elemental Sum-Fac"
opts[1]="Elemental matrix"
opts[2]="Elemental block-matrix"
opts[3]="Global matrix"
opts[4]="Optimal"

# Clear results file and enter headings
echo "%     Type  nElements     nModes     nCalls       Time  Time/Call         L2Error L2Error(hi-res)      LinfError LinfErr(hi-res)  nLocCoef  nGlobCoef  nLocBCoef nGlobBCoef  nLocDCoef nGlobDCoef       nnz   optlevel" > $TimingResultsFile

# Loop over the element type
for Type in 1 3; do
    # Loop over the optimisation level
    for OptimisationLevel in 0 2 3; do
        # Loop over the mesh-size
        for MeshSize in 1 2 3 4 5 6 7 8 9 10; 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
                    $ExecutableFile $Type $MeshSize $NumModes \
                                    $OptimisationLevel $OpToTest \
                                    2>/dev/null > "$ExecutableDumpFile"

                    echo Nektar++ $ExecutableFile $Type $MeshSize $NumModes \
                        $OptimisationLevel $OpToTest \(${types[$Type]} / \
                        ${opts[$OptimisationLevel]} / Mesh \= $MeshSize / \
                        Modes \= $NumModes / Run \= $a\)

                    read TypeOut NumElementsOut NumModesOut NumCallsOut \
                         ElapsedTimeOut TimepCallOut L2Out L2OutBis LinfOut \
                         LinfOutBis nLocCoefOut  nGlobCoefOut nLocBCoefOut \
                         nGlobBCoefOut  nLocDCoefOut nGlobDCoefOut nnzOut \
                         optLevelOut< "$ExecutableDumpFile"

                    if [ $ElapsedTimeOut -lt $MinTime ]; then
                        MinTime=$ElapsedTimeOut
                        cp $ExecutableDumpFile $MinTimeFile
                    fi
                done
                cat $MinTimeFile >> $TimingResultsFile
            done
        done
    done
done

rm -f $MinTimeFile
rm -f $ExecutableDumpFile
