#!/bin/bash

if [ $# -lt 1 ]; 
then
echo "Usage: $0 <annotated_C_header_file> ..."
exit 1
fi

while [ $# -ge 1 ]; do

	ANN_FILE=$1
	#echo "Annotated input file=$ANN_FILE"

	if [ ! -e $ANN_FILE ]; then 
	echo "Could not find file $ANN_FILE."
	exit 1
	fi 

	MARSHALGEN_DIR=`dirname $0`
	TARGET_DIR=`dirname $ANN_FILE`

	# get the prefix of the input file
	NAME_PREFIX=`basename $ANN_FILE | sed "s/\..*//"`

	# and append ".msh" to it
	MSH_FILE="$TARGET_DIR/$NAME_PREFIX.msh" 


	########### Phase 2 ###############

	echo ""
	echo "Phase 1: Reading $ANN_FILE, generating temporary $MSH_FILE file ..."
	echo ""
	echo "$MARSHALGEN_DIR/Phase1/mgen.pl $ANN_FILE"
	$MARSHALGEN_DIR/Phase1/mgen.pl $ANN_FILE

	if [ $? -ne "0" ]; then
	echo ""
	echo "Phase 1 failed. Stopped."
	exit 1
	fi


	########### Phase 2 ###############

	OUTPUT_FILE="$TARGET_DIR/Marshaled$NAME_PREFIX.h"
	echo ""
	echo "Phase 2: Reading $MSH_FILE, generating marshaling code" \
	     " to $OUTPUT_FILE"
	echo ""

	if [ ! -e $MSH_FILE ]; then 
	echo "Could not find file $MSH_FILE."
	exit 1
	fi 

	echo "$MARSHALGEN_DIR/Phase2/marshal $MSH_FILE $OUTPUT_FILE"
	$MARSHALGEN_DIR/Phase2/marshal $MSH_FILE $OUTPUT_FILE

	if [ $? -ne "0" ]; then
	echo ""
	echo "Phase 2 failed. Stopped."
	exit 1
	else
	echo ""
	echo "Marshalgen executed successfully."
	fi

	shift
done
