#!/bin/bash
set -euo pipefail
scalafile=${1:-bfc.scala}
out=${2:-output}
echo -e "" > $out
echo -e "Below is the feedback for your submission of bfc.scala" >> $out
echo -e "" >> $out
# compilation tests
function scala_compile {
  (ulimit -t 30; JAVA_OPTS="-Xmx1g" scala -Xprint:parser "$1" 2> c$out 1> c$out)
}
# functional tests
function scala_assert {
  (ulimit -t 30; JAVA_OPTS="-Xmx1g" scala -i "$1" -- "$2" -e "" 2> /dev/null 1> /dev/null)
}
# purity test
function scala_vars {
    (sed 's/immutable/ok/g' c$out > cb$out;
     egrep '\bvar\b|\breturn\b|\.par\.|\.par |ListBuffer|AtomicInteger|mutable|util.control|new Array' cb$out 2> /dev/null 1> /dev/null)
}
# compilation test
echo -e "bfc.scala runs?" >> $out
if (scala_compile $scalafile)
then
    echo -e "  --> passed" >> $out
    tsts1=$(( 0 ))
else
    echo -e "  --> SCALA DID NOT RUN BFC.SCALA\n" >> $out
    tsts1=$(( 1 )) 
fi
# var, return, ListBuffer test
#
if [ $tsts1 -eq 0 ]
then
    echo -e "bfc.scala does not contain vars, returns etc?" >> $out
    if (scala_vars $scalafile)
    then
	echo -e "   --> FAIL (make triple-sure your program conforms to the required format)" >> $out  
	tsts1=$(( 1 ))
    else
	echo -e "  --> passed" >> $out
	tsts1=$(( 0 )) 
    fi
fi
### bfc tests
if [ $tsts1 -eq 0 ]
then
  echo -e " jtable(\"\"\"+++++[->++++++++++<]>--<+++[->>++++++++++<<]>>++<<----------[+>.>.<+<]\"\"\") ==" >> $out
  echo -e "     Map(69 -> 61, 5 -> 20, 60 -> 70, 27 -> 44, 43 -> 28, 19 -> 6)" >> $out  
  
  if (scala_assert $scalafile "bf_test5.scala")
  then
    echo -e "  --> success" >> $out
  else
    echo -e "  --> \n ONE TEST FAILED\n" >> $out
  fi
fi
if [ $tsts1 -eq 0 ]
then
    echo -e " optimise(load_bff(\"benchmark.bf\")).length == 181" >> $out
    echo -e " optimise(load_bff(\"mandelbrot.bf\")).length == 11205" >> $out  
  if (scala_assert $scalafile "bf_test6.scala")
  then
    echo -e "  --> success" >> $out
  else
    echo -e "  --> \n ONE TEST FAILED\n" >> $out
  fi
fi
if [ $tsts1 -eq 0 ]
then
    echo -e " combine(optimise(load_bff(\"benchmark.bf\"))).length == 134" >> $out
    echo -e " combine(optimise(load_bff(\"mandelbrot.bf\"))).length == 6511" >> $out
  
  if (scala_assert $scalafile "bf_test7.scala")
  then
    echo -e "  --> success" >> $out
  else
    echo -e "  --> \n ONE TEST FAILED\n" >> $out   
  fi
fi