#!/bin/csh

# shell script for generating classes from prototypes
#
# usage: genclass protodir cdir extension type {ref | val} [type {ref | val}] ...  proto 
#

set PROGRAM_NAME=$0
set USAGE="Usage: ${PROGRAM_NAME} '<Proto dir> <C dir> <C file extension> <type> {ref | val} [<type> {ref | val}] ...  <prototype>'";

# there are at least 6 parameters, plus the program name (total of seven)
if (($#argv < 6) || ($#argv % 2) > 0) then
  echo "${PROGRAM_NAME}: invalid parameter count";
  echo "${USAGE}";
  exit 1;
endif

set PWD=`pwd`/

# get the prototype directory, the C directory and the C file extension (.h or .cc)
# from the argument list
set PROTODIR = $1; 	shift;
set OUTDIR = $1; 	shift;
set EXTNSN = $1; 	shift;

if ($PROTODIR !~ */) then
  set PROTODIR = $PROTODIR/
endif
if ($OUTDIR !~ */) then
  set OUTDIR = $OUTDIR/
endif

set FILE_NAME=;
set CLASS_NAME=;
set TYPES=;
set VALS=;

# loop through the parameters, pulling <type> <reference type> pairs off the 
# argument list.

while ( $#argv > 2 )
  set TYPES = (${TYPES} $1)
  set VALS = (${VALS} $2)
  set FILE_NAME = "${FILE_NAME}$1."
  set CLASS_NAME = "${CLASS_NAME}$1"

  if (($2 != "ref") && ($2 != "val")) then
    echo "${PROGRAM_NAME}: invalid reference type" ; 
    echo ${USAGE} ; 
    exit 1;
    endif

  shift; 
  shift;
end

set CLASS = $1

set FILE_NAME = "${FILE_NAME}${CLASS}.${EXTNSN}"
set CLASS_NAME = "${CLASS_NAME}${CLASS}"
set HSRC      = "$CLASS.hP"
set SRC       = "$CLASS.${EXTNSN}P"
set OUT       = "$OUTDIR$FILE_NAME"

if ( (-f $PWD$SRC) && (-r $PWD$SRC) && (-f $PWD$HSRC) ) then
  set PSRC = $PWD$SRC
  set HSRC = $PWD$HSRC
else if ( (-f $PROTODIR$SRC) && (-r $PROTODIR$SRC) && (-f $PROTODIR$HSRC) ) then
  set PSRC = $PROTODIR$SRC
  set HSRC = $PROTODIR$HSRC
else 
  echo "${PROGRAM_NAME}: $SRC: no such file"; 
  exit 1;
endif

set SEARCH_STRING = (generic class $CLASS\\\[.\*\\\])

set SED_SCRIPT = /tmp/genclass.$$

# this is so we can handle unreformed files from the distribution
if (1) then
  set TYPE_LIST = T
  if ( $#TYPES == 2 ) set TYPE_LIST = (${TYPE_LIST} C)
else
  # get TYPE_LIST somehow... ???
  set TEMP = "`grep $SEARCH_STRING $HSRC`" 
  set TYPE_LIST=(`expr $TEMP : \[^\\\[\]\*\\\[\(.*\)\\\].\* | tr ',' ' '`);
  unset TEMP
  echo "s/$SEARCH_STRING/class $CLASS_NAME/g" >> SED_SCRIPT
endif

set DUMMY=0
while ( $DUMMY < $#TYPES )
  @ DUMMY++
  set PREAMBLE = 's/<';
  set MIDDLE = '>/';
  set POSTAMBLE = '/g';
  echo ${PREAMBLE}${TYPE_LIST[$DUMMY]}${MIDDLE}${TYPES[$DUMMY]}${POSTAMBLE} >>$SED_SCRIPT

  set MIDDLE = "&$MIDDLE"
  if ($VALS[$DUMMY] == "ref") set POSTAMBLE = "\&$POSTAMBLE";

  echo ${PREAMBLE}${TYPE_LIST[$DUMMY]}${MIDDLE}${TYPES[$DUMMY]}${POSTAMBLE} >>$SED_SCRIPT
end

sed -f $SED_SCRIPT < $PSRC > $OUT 

rm -f $SED_SCRIPT




