#!/bin/sh
#
# default values
# "numtests" is a misnomer - it really should be numiter
numtests=1000
advdir=""
constvar=""

case $# in
    0|1)
       echo "Usage: $0 <test name> <adverse dir> [<Const var> [<# iterations>]]"
       exit 1
       ;;
    2)
       test_set=$1
       advdir="-viAdvDir=$2"
       ;;
    3)
       test_set=$1
       advdir="-viAdvDir=$2"
       constvar="-viConstVar=$3"
       ;;
    4)
       test_set=$1
       advdir="-viAdvDir=$2"
       constvar="-viConstVar=$3"
       numtests=$4
       ;;
esac

# Include current directory in path to get CModelAvg.exe
PATH=$PATH:`pwd`

#
# Create a subdirectory for the test if it doesn't exit.
if test ! -d $test_set
then
    mkdir $test_set
    echo "Created subdirectory $test_set"
fi
cd $test_set


# Generate the avg test files from the csv
echo "Removing old input files and regenerating from csv file..."
rm -f $test_set*.avg
awk -v iNTests=$numtests $advdir $constvar -f ../csvtoavg.awk ../$test_set.csv

# Remove old results to avoid problems.
echo "Removing old output files..."
rm -f *.log
rm -f *.err
rm -f *.stdout

# Ensure that we have the program in our path
which CModelAvg.exe
if [ $? -ne 0 ]
then
    echo "Cannot find Model Averaging program CModelAvg.exe in path ($PATH). Exiting."
    exit 1
fi

# Run each test
j=1
for i in $test_set*.avg
do
  bname=`basename $i .avg`
  echo -n "Running test $i ... "
  CModelAvg.exe $i >$bname.stdout 2>$bname.err
  echo "Done"
#  if [ $j -eq $numtests ]
#      then
#      break
#  fi
  j=`expr $j + 1`
done

# Summarize the results.
echo -n "Summarizing results in ${test_set}_Summary.csv ..."
awk -f ../parse_result.awk -vDoHeader=1 -vTestName="$test_set"
#for i in $test_set*.log
for i in *.log
do
  awk -f ../parse_result.awk -vTestName="$test_set" $i
done
echo "Done"
mv "${test_set}_Summary.csv" ..

exit 0
