#!/bin/bash
set -e

out=${1:-output}

echo "" > $out

echo "Below is the feedback and provisional mark for your submission" >> $out
echo "for CW 8, Part 2.  Please note all marks are provisional until" >> $out
echo "ratified by the assessment board -- this is not an official" >> $out
echo "results transcript." >> $out
echo "" >> $out

function scala_vars {
   (egrep '\bvar\b|\breturn\b|ListBuffer|mutable' "$1" 2> /dev/null 1> /dev/null)
}


# compilation tests

function scala_compile {
  (scala "$1" 2> /dev/null 1> /dev/null) 
}


# functional tests

function scala_assert {
  (scala -i "$1" "$2" -e "" 2> /dev/null 1> /dev/null)
}


# marks for CW
marks=$(( 0 ))


# var, return, ListBuffer test
#
echo "re2.scala does not contain vars, returns etc?" | tee -a $out

if (scala_vars re2.scala)
then
  echo "  --> fail" | tee -a $out
  tsts0=$(( 1 ))
else
  echo "  --> yes" | tee -a $out
  tsts0=$(( 0 )) 
fi


# compilation test
if  [ $tsts0 -eq 0 ]
then    
  echo "re2.scala runs?" | tee -a $out

  if (scala_compile re2.scala)
  then
    echo "  --> yes" | tee -a $out
    tsts1=$(( 0 ))
  else
    echo "  --> scala re2.scala did not run successfully" | tee -a $out
    tsts1=$(( 1 )) 
  fi
else
  tsts1=$(( 1 ))     
fi

if [ $tsts1 -eq 0 ]
then
  echo " iterT(200000, (x: Int) => x + 1, 0) == 200000" | tee -a $out
  echo " iterT(100, (x: BigInt) => x * 2, BigInt(2)) == BigInt(\"2535301200456458802993406410752\")" | tee -a $out
  echo " iterT(10, (x: String) => x ++ \"a\", \"a\") == \"aaaaaaaaaaa\"" | tee -a $out
  
  if (scala_assert "re2.scala" "../../../marking/re2a_test.scala")
  then
    echo "  --> success" | tee -a $out
    marks=$(( marks + 2 ))
  else
    echo "  --> test failed" | tee -a $out
  fi
fi

if [ $tsts1 -eq 0 ]
then
  echo " size(iterT(20, (r: Rexp) => der('a', r), EVIL)) == 7340068" | tee -a $out
  echo " size(iterT(20, (r: Rexp) => simp(der('a', r)), EVIL)) == 8" | tee -a $out
  
  if (scala_assert "re2.scala" "../../../marking/re2b_test.scala")
  then
    echo "  --> success" | tee -a $out
    marks=$(( marks + 1 ))
  else
    echo "  --> test failed" | tee -a $out
  fi
fi

if [ $tsts1 -eq 0 ]
then
  echo " fixpT((x:Int) => if (200000 < x) x else x + 1, 0) == 200001" | tee -a $out
  echo " fixpT((x:Long) => if (20 < x) x else x + 1, 0L) == 21L" | tee -a $out
  
  if (scala_assert "re2.scala" "../../../marking/re2c_test.scala")
  then
    echo "  --> success" | tee -a $out
    marks=$(( marks + 1 ))
  else
    echo "  --> test failed" | tee -a $out
  fi
fi

## final marks
echo "Overall mark for CW 8, Part 2" | tee -a $out
echo "$marks" | tee -a $out
