#!/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=$(echo $build | sed 's/swipl-devel.*/swipl-devel\/src/')
echo home=$home

function basesource
{ case $1 in
    pl-wam.c)
	echo $1 pl-vmi.c
	;;
    pl-prims.c|pl-rec.c|pl-trie.c|pl-termhash.c|pl-copyterm.c)
	echo $1 pl-termwalk.c
	;;
    pl-read.c)
	echo $1 pl-umap.c
	;;
    pl-dtoa.c)
	echo $1 dtoa.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$/.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.c.o | grep 'U pl_' | awk '{ print $2 }'`
  for f in $funcs; do
    grep -w $f $home/pl-ext.c | sed 's/.*"\(.*\)",[	 ]*\([0-9]*\).*/predicate('"'"'\1'"'"', \2, '$f')./'
  done
}

rm *.functions
rm *.tree
rm built-in-predicates


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

ext_builtins > built-in-predicates

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