#! /bin/sh

# Notes:
#
# $1 = output file name/path (C prototypes generated by f2c)
# $2, $3, ... = input file names/paths (fortran code)
#
# This script will only be called by SLIRP if f2c has 
# been found in the environment at configure time.
#
# mnoble@space.mit.edu

if [ "$1" = "-g" ] ; then
   set -x
   shift
fi

output=$1
errs=${output}.err
subs=${output}.subs
shift
\rm -f $errs $subs

echo "#include \"f2c.h\"" > $output

# f2c accepts multiple files, but do them 1by1 to better avoid system limits
for file in $* ; do
   grep -i "^[^c]*subroutine" $file | awk '{print $2}' | cut -d"(" -f1 | \
							tr A-Z a-z >> $subs
   f2c -P -\!c \
   	< $file	\
	>> $output \
	2>> ${output}.err

   if [ $? -ne 0 ] ; then
	\rm -f $output
	exit 1
   fi
done


# Reprocess to:
#  - remove "int" return value from C wrappers for SUBROUTINES
#  - morph string args so that the builtin SLIRP #argmap(in) can be
#    transparently applied (and avoid the need to pass a length param)

if [ -s $subs ] ; then
   for sub in `cat $subs` ; do
	sedstr="$sedstr -e 's/extern int $sub/extern void $sub/'"
   done

   sedstr="$sedstr -e 's/char[ \t]*\*[a-zA-Z_]*[ \t]*,[ \t]*ftnlen[ \t]*[a-zA-z_]*/char *, unsigned long FORTRAN_STRING_LEN/'"

   command="tr -s '\011' ' ' < $output | sed $sedstr"
   eval $command > ${output}.tmp
   mv ${output}.tmp ${output}
fi

\rm -f $errs $subs 
if [ -f /tmp/f2c_*  ] ; then
   tmpfiles=`ls -l /tmp/f2c_* | grep $LOGNAME | awk '{print $NF}'`
   if [ -n "$tmpfiles" ] ; then
	\rm -f $tmpfiles
   fi
fi
exit 0
