#!/bin/bash
# Author: Jan Wielemaker
# Copying: this code is in the public domain

tooldir=`dirname $0`
if [ "x$tooldir" == x ]; then
    tooldir=.
fi

build=`pwd`
home=`dirname $build`/src

function basesource
{ case $1 in
    pl-wam.c)
	echo $1 pl-alloc.c pl-index.c pl-fli.c pl-vmi.c
	;;
    pl-prims.c|pl-rec.c)
	echo $1 pl-termwalk.c
	;;
    pl-read.c)
	echo $1 pl-umap.c
	;;
    *)
	echo $1
	;;
  esac
}


function source
{ base=`basename $1`
  dir=`dirname $1`

  for f in `basesource $base`; do
    echo $dir/$f
  done
}


update()
{ base=`echo $1 | sed 's/\.c.*/.c/'`
  tout="$base.tree"
  fout="$base.functions"
  src=`find $home -name $base`
  obj=`echo $base | sed 's/\.c$/.o/'`
  aobj=`find $build -name $obj`

  if [ ! -r $tout -o $1 -nt $tout ]; then
    if ! $tooldir/calltree.pl $1 $tout; then
      return 1
    fi
  fi
  if [ ! -r $fout -o $src -nt $fout ]; then
    sources="`source $src`"
    echo $tooldir/functions.pm $sources
    if ! $tooldir/functions.pm $sources > $fout; then
      return 1
    fi
    echo "" >> $fout
    for s in $sources; do
      echo "object('$obj', '$s')." >> $fout
    done
    echo "" >> $fout
    nm -l $aobj | grep -w t | sed 's/:[0-9]*//' | \
	awk '{ printf("static('"'%s', '%s'"').\n", $3, $4) }' >> $fout
  fi
}

ext_builtins()
{ funcs=`nm pl-ext.o | grep 'U pl_' | awk '{ print $2 }'`
  for f in $funcs; do
    grep -w $f pl-ext.c | sed 's/.*"\(.*\)",[	]*\([0-9]*\).*/predicate('"'"'\1'"'"', \2, '$f')./'
  done
}

if [ -z "$1" ]; then
   files="*.expand"
else
   files="$*"
fi

ext_builtins > buildin-predicates

for f in $files; do
   if ! update $f; then
      exit 1
   fi
done
