#!/bin/bash

function print_usage {
    cat << EOF
Usage: cnc_t [options] <cnc_input> ...
where [options] includes:
	-h -help --help		print this message
	-d			dump parsed tokens
	-k			dump keywords
	-p			print the AST
    
EOF
    exit 1
}

CNC_INPUT=
CNC_PARSER=CnCParser.Main
CLASSPATH=
args=""

if [ -n "$JAVA_HOME" -a -e "$JAVA_HOME/bin/java" ]; then
    JAVA="$JAVA_HOME/bin/java"
elif [ -n "$JRE_HOME" -a -e "$JRE_HOME/bin/java" ]; then
    JAVA="$JRE_HOME/bin/java"
else
    echo "JAVA_HOME ($JAVA_HOME) is not pointing to a JRE or a JDK"
    exit 1
fi

if [ -z "${CNC_HOME}" ]; then
	echo ""
	echo "ERROR CNC_HOME environment variable must be defined and point to a CnC Distribution"
	echo ""
    exit 1
fi

parse=true
while [ -n "$1" ]; do
    if [ -z "$parse" ]; then
	args=$args $1
        shift
     P   continue
    fi
    case "$1" in
        -h|-help|--help) print_usage; break;;
        --) parse=;;
        *) args="$args $1";;
    esac
    shift
done

if [ -z "$args" ]; then
	print_usage;
fi 
    	
###############################################################################
# This check ensures only .cnc files will be submit to soot.
###############################################################################

cnc_src_pattern=*.cnc

case $args in 
  $cnc_src_pattern) echo "" ;;
  *) echo "ERROR: Source file $args must have a .cnc extension to be compiled"; exit 1;; 
esac

###############################################################################
# set classpath to CnCParser
###############################################################################

for file in `ls ${CNC_HOME}/lib`; do
	CLASSPATH=${CLASSPATH}:${CNC_HOME}/lib/$file
done

JAVA_OPTIONS="${JAVA_OPTIONS} -cp ${CLASSPATH}"

CNC_INPUT=$args

###############################################################################
# Building and executing the final command
###############################################################################

CMD="$JAVA ${JAVA_OPTIONS} $CNC_PARSER $CNC_INPUT"

[ -n "$verbose" ] && echo ${CMD}

eval ${CMD}
exit $?