# ---------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------

parseBin=$MASC/bin/parse
translateBook=$MASC/lisp/translate
acl2Bin=$ACL2/saved_acl2

# ---------------------------------------------------------------------
# options parsing
# ---------------------------------------------------------------------

usage() {
    cat <<USAGEEOF
Usage:

  masc srcfile [options]

masc parses the given srcfile, checks that it satisfies the MASC
subset restrictions, and optionally generates various outputs.

Options are:

  -a                 Generate lisp output for ACL2.
  --acl2

  -c                 Generate C++ output for Cadence CtoS.
  --ctos

  -m                 Extract only the MASC code.
  --masc

  -I dir             Look for include files in directory 'dir'

  -h                 Print this message.
  --help
USAGEEOF
}

srcfile=
acl2=
ctos=
masc=
incdirs=""

OPTS=`getopt -l help -l acl2 -l ctos -l masc hacmI: $@`
if [ $? != 0 ]
then
    usage;
    exit 1
fi

eval set -- "$OPTS"
while true; do
    case $1 in
    -a | --acl2)
        acl2=1;
        shift 1;
        ;;
    -c | --ctos)
        ctos=1;
        shift 1;
        ;;
    -m | --masc)
        masc=1;
        shift 1;
        ;;
    -I)
        incdirs="$incdirs -I $2";
        shift 2;
        ;;
    --)
        shift 1;
        break
        ;;
    esac
done

# Extract the source filename and
# make sure only one of ctos, acl2, masc is specified

if [[ -z "$1" ]]
then
    usage;
    exit 1
else
    srcfile=$1;
    shift 1;
    # extra input left over?
    if [[ -n "$1" ]]
    then
        usage;
        exit 1
    fi
fi

if [[ "$acl2" && "$ctos" || "$acl2" && "$masc" || "$ctos" && "$masc" ]]
then
    usage;
    exit 1
fi

# ---------------------------------------------------------------------
# Call the masc parser in the appropriate mode
# ---------------------------------------------------------------------

# Die immediately on any error
set -e

basename=${srcfile%.*}
cppopts="-D__MASC__ -C -std=c++11"

/usr/intel/pkgs/gcc/4.8.1/bin/cpp $cppopts $incdirs $basename.cpp $basename.i;
#/usr/intel/bin/cpp $cppopts $incdirs $basename.cpp $basename.i;

if [[ -z "$ctos" && -z "$acl2" && -z "$masc" ]]
then
    $parseBin $basename
fi

if [[ "$ctos" ]]
then
    $parseBin $basename -ctos
fi

if [[ "$masc" ]]
then
    $parseBin $basename -masc
fi

if [[ "$acl2" ]]
then

    $parseBin $basename -acl2 $basename.ast.lisp

    $acl2Bin > $basename.acl2.log <<EOF
      (include-book "$translateBook")
      (set-inhibit-output-lst '(prove event proof-tree))
      (translate-program "$basename.ast.lisp" "$basename.lisp" state)
      :u
      (include-book "rtl/rel11/lib/masc" :dir :system)
      (certify-book "$basename" 1)
EOF

fi
