#!/bin/sh
#
# makeinstcopy - make an instance gate copy of a native digital gate.
#
# This is a loged wrapper to generate an instance gate from an existing
# native digital gate.
#
# It is typically used within a Makefile to ensure that a native gate's
# template contains a true likeness of itself prior to generating a definition.
#
# The instance gate differs from the native gate in that the definition and
# label parts are replaced with the definition and labels below.
# All other parts of the native gate remain intact.
#

progname=$0
USAGE="usage: $progname mylib.gate mygate.def"  
prog="loged -p"
prefix=^
suffix=

case $# in
  2) gatelib=$1
     deffile=$2
     ;;
  *) echo $USAGE 
     exit 1
     ;;
esac

# check the gate library exists.
if [ ! -e $gatelib ]
then
  echo $progname: error: $gatelib not found 1>&2
  exit 1
fi

if [ ! -r $gatelib ]
then
  echo $progname: error: $gatelib is not readable. 1>&2
  exit 1
fi

if [ ! -w $gatelib ]
then
  echo $progname: error: $gatelib is not writeable. 1>&2
  exit 1
fi

# produce the gate name by cutting on the first period of the def file name. 
native=`echo $deffile |cut -d'.' -f1`

# produce the instcopy name by appending a suffix to the gate name. 
iname=$prefix$native$suffix

# check the length of instcopy name is between 2 and 8 chars.
lenok=0
case $iname in
    ( ?? | ??? | ???? | ????? | ?????? | ??????? | ???????? ) 
      lenok=1 ;;
    ?) echo $0: instcopy name \"$iname\" is too short.
      exit 1 ;;
    *) echo $0: instcopy name \"$iname\" is longer than 8 chars.
      exit 1 ;;
esac

#-----------------------------------------------------------------------------
# generate a definition file for iname.
#
# the "[is-generic] V No (fixed):Generic?" label must match
# what is expected in log/src/loghier.c isgenericinstgate(g).
# i.e. the variant attribute (is-generic) set to the default value (No).
#-----------------------------------------------------------------------------

trap 'rm -f $iname.def; exit 1' 1 2 15

cat <<End >$iname.def
# LOG digital hierarchy compiler version of Apr 21, 1989 5:23 pm by dave

UPDATEKIND
SIMTYPE 16

def "CALL LOGSIMH_LOG_16_INST"
label "non-generic digital instance gate"
label ""
label "[inst-of] C"$native":Instance of::"
label "[disp-inst-name] BY:Display name?"
label "[gate-name] C:Instance name::"
label "[is-generic] V No:Generic port assignment?"
label ""

End

#-----------------------------------------------------------------------------
# feed a here-document into loged's stdin.
#
# 1. select the current iname gate and delete it.
# 2. select native gate, and copy it to iname gate,
# 3. read iname definition.
# 4. save & quit.
#-----------------------------------------------------------------------------

$prog $gatelib <<End >/dev/null
gate $iname 
delete
gate $native
copy $iname 
read $iname.def
save $gatelib
quit
End

# clean-up & exit.
rm -f $iname.def
exit 0

