#!/bin/sh

# this is a really trivial script intended to massage the simple .ckt
# files generated by netgen.  It prepends a header file, and then
# appends a tail file to the specified .ckt file.

if [ "$SPICEHEAD" = "" ]  # if environment variable is not set
then
  head=spice.top         # set it to the default
else
  head=$SPICEHEAD         # otherwise, use the environment variable       
fi

if [ "$SPICETAIL" = "" ]
then
  tail=spice.bot
else
  tail=$SPICETAIL
fi

nmodel=n2  # default n-transistor model name
pmodel=p2  # default p-transistor model name
nsub=NSUB  # default n-transistor substrate node
psub=PSUB  # default p-transistor substrate node

output=spice.ckt # default output file name


case $# in
  0) echo "Usage:  $0 [-head={header file}] [-tail={tail file}]"
     echo "       [-nmodel={nmodel name}] [-pmodel={pmodel name}]"
     echo "       [-nsub={n-tran substrate name}] [-psub={p-tran substrate name}]"
     echo "       [-output={output file name}] {.ckt file name}"
     echo " "
if [ "$SPICEHEAD" = "" ]
then
     echo "Defaults:  header = $head (or set environment variable SPICEHEAD)"
else
     echo "Defaults:  header = $head (set by environment variable SPICEHEAD)"
fi
if [ "$SPICETAIL" = "" ]
then
     echo "           tail file = $tail (or set environment variable SPICETAIL)"
else
     echo "           tail file = $tail (set by environment variable SPICETAIL)"
fi
     echo "           N model-name = $nmodel; P model-name = $pmodel"
     echo "           N substrate-name = $nsub; P substrate-name = $psub"
     echo "           Output file name = $output"
     exit 1 ;;
  *) ;;
esac


for arg do
  case $arg in
    -head=*)
	head=`echo $arg | sed s/-head=//` ;;
    -tail=*)
	tail=`echo $arg | sed s/-tail=//` ;;
    -nmodel=*)
	nmodel=`echo $arg | sed s/-nmodel=//` ;;
    -pmodel=*)
	pmodel=`echo $arg | sed s/-pmodel=//` ;;
    -nsub=*)
	nsub=`echo $arg | sed s/-nsub=//` ;;
    -psub=*)
	psub=`echo $arg | sed s/-psub=//` ;;
    -output=*)
	output=`echo $arg | sed s/-output=//` ;;
    *) file=$arg ;;
  esac
done

echo "SPICE deck translation filter."
echo "Input from: $file;  Header: $head; Trailer: $tail"

if [ -f $output ]
then
  rm $output
fi

echo "SPICE deck created from file $file" > $output

if [ -f $head ]
then
  cat $head >> $output
fi

if [ -f $file ]
then
  sed -e "s/NTRAN/$nmodel/g" < $file |  \
  sed -e "s/PTRAN/$pmodel/g" | sed -e "s/NSUB/$nsub/g" | \
  sed -e "s/PSUB/$psub/g" >> $output
fi

if [ -f $tail ]
then
  cat $tail >> $output
fi

echo "SPICE deck written in file: $output"
