#!/bin/ksh
#
# gen_tables create the headerfile table.h
# with all default tables from default_tables
#
set -e
DEFTABLES=@abs_top_srcdir@/tables/default_tables
OFILE=@abs_top_srcdir@/src/table.h
PTFILES=""
#
#########################################
#
rm -f "$OFILE"
exec 3<"$DEFTABLES" 4>"$OFILE"
#
item=0
while read -u3 PTFILE[item] ; do
#

if [ -z ${PTFILE[item]} ] ; then break ; fi
#
PTFILE[item]="@abs_srcdir@/${PTFILE[item]}"
#
let item=item+1
#
done
unset PTFILE[item]
#
#########################################
#
#
cat >&4 <<EOF
/* Automatically generated, do not edit! */
#ifndef _TABLE_H
#define _TABLE_H

EOF
#
for TFILE in "${PTFILE[@]}"; do
    echo "process: $TFILE"
    rm -f ptfile
    @abs_top_builddir@/app/createtable "$TFILE" - >&4
done
#
cat >&4 <<EOF

static
void tableDefault(void)
{
  int tableID, instID, modelID;

EOF
#
settabvar() {
  grep "$2" "$1" | cut -f 2 -d "="
}
#
item=0
for TFILE in "${PTFILE[@]}" ; do
TFBASENAME="${TFILE##*/}"
echo "process: $TFILE"
#
TABLE_ID=`settabvar ${TFILE}  "TABLE_ID"`
TABLE_NA=`settabvar ${TFILE}  "TABLE_NA"`
TABLE_MO=`settabvar ${TFILE}  "TABLE_MO"`
TABLE_IN=`settabvar ${TFILE}  "TABLE_IN"`
TABLE_CE=`settabvar ${TFILE}  "TABLE_CE"`
TABLE_SU=`settabvar ${TFILE}  "TABLE_SU"`
#
if [ -z $TABLE_ID ] ; then TABLE_ID=0; fi
if [ -z $TABLE_NA ] ; then TABLE_NA=$TFBASENAME; fi
#if [ -z $TABLE_MO ] ; then TABLE_MO=NULL; fi
if [ -z $TABLE_CE ] ; then TABLE_CE=0; fi
if [ -z $TABLE_SU ] ; then TABLE_SU=0; fi
#
echo "ID = $TABLE_ID name=$TABLE_NA model=$TABLE_MO inistitut=$TABLE_IN center=$TABLE_CE subcenter=$TABLE_SU"
TABLENAME=`echo ${TFBASENAME} | sed -e "s/\./_/g" `
#
cat >&4 <<EOF

  /*
   *  define table : ${TFBASENAME}
   */

  instID  = institutInq(${TABLE_CE}, ${TABLE_SU}, "${TABLE_IN}", NULL);
  if ( instID == -1 )
    instID  = institutDef(${TABLE_CE}, ${TABLE_SU}, "${TABLE_IN}", NULL);

  modelID = modelInq(instID, 0, "${TABLE_MO}");
  if ( modelID == -1 )
    modelID = modelDef(instID, 0, "${TABLE_MO}");

  tableID = tableDef(modelID, ${TABLE_ID}, "${TABLE_NA}");

  tableLink(tableID, ${TABLENAME}, sizeof(${TABLENAME}) / sizeof(PAR));
EOF
#
done
#
cat >&4 <<EOF
}

#endif  /* _TABLE_H */
EOF
#
rm -f ptfile
#
exit
