#!/bin/bash
EXAMPLES=`ls dist/build | grep hoed-examples`
ulimit -v 1000000 # limit memory usage to 10 GB

echo "Available examples:"
i=0
for e in $EXAMPLES; do
  echo -n "$i) "
  echo $e | sed 's/^hoed-examples-//' | sed 's/__.*/ (&)/' |sed 's/__//' |  sed 's/_/ /g'
  ((i++))
done

echo -n "Select program or -1 to cancel: "
read

# Find the appropriate example from the given input
j=0
for e in $EXAMPLES; do
  if ((j==$REPLY)); then 
    EXE=$e
    break
  fi
  ((j++))
done

# Or exit if the input was invalid (or -1)
if ((j>=i)); then
  echo "Bye"
  exit 1
fi

echo "Now executing $EXE."

rm -f tmp/wwwroot/debugTree.png tmp/debugTree.dot
cd tmp
# if echo $EXE | grep -q does_not_terminate; then
#   echo "You selected a non terminating program. Will kill after 1 second."
#   ../dist/build/$EXE/$EXE +RTS -p -h -L80 &
#   sleep 1s
#   kill -2 $! # send a "ctrl-C" signal to stop the hanging compiler...
#   wait
# else
# ../dist/build/$EXE/$EXE +RTS -p -h -L80
# fi

eval ../dist/build/$EXE/$EXE

# profile ....
#../dist/build/$EXE/$EXE +RTS -hd -L80