#!/bin/sh
# Convert WEB programs not needing special treatment to C.
# $1 is the Pascal file to be converted.
#
# author: Ken Nakano (ken-na@ascii.co.jp)
#
web2cdir=../web2c
target=$1

usage () {
	echo ""
	echo "Usage: $0 <basefile>"
	echo "  <basefile> = ptex|ppltotf|ptftopl|pdvitype|pbibtex"
	echo ""
}

convert_ptex () {
	cat $web2cdir/common.defines $web2cdir/texmf.defines \
                ../synctexdir/synctex.defines \
		./ptex.defines ./$target.p \
	| $web2cdir/web2c -htexmfmp.h -t -cptexcoerce \
	| $web2cdir/fixwrites -t ptex \
	| $web2cdir/splitup -i -l 65000 ptex
	sleep 2
	cat ptexcoerce.h $web2cdir/coerce.h > xptexcoerce.h
	echo '#include "kanji.h"' >> xptexcoerce.h
	mv xptexcoerce.h ptexcoerce.h
	touch ptexd.h
}

convert_tool () {
	cat $web2cdir/common.defines ./ptex.defines ./$target.p \
	| $web2cdir/web2c -hkanji.h -c$target \
	| $web2cdir/fixwrites $target > $target.c
}

convert_pbibtex() {
	cat $web2cdir/common.defines ./ptex.defines ./$target.p \
	| $web2cdir/web2c -hptexdir/kanji.h -c$target \
	| sed -f $web2cdir/cvtbib.sed \
	| $web2cdir/fixwrites $target > $target.c
	sed -e 's/(buftype)//g' -e 's/(pdstype)//g' < $target.h >x$target.h
	mv x$target.h $target.h
}

case $target in 
	ptex) convert_ptex
		cfile=ptex0.c # last output file, or thereabouts
		output_files="ptex[0-9]*.c ptexini.c ptexd.h ptexcoerce.h"
		;;
	ppltotf|ptftopl|pdvitype) convert_tool
		cfile=$target.c
		output_files="$target.c $target.h"
		;;
	pbibtex) convert_pbibtex
		cfile=$target.c
		output_files="$target.c $target.h"
		;;
	*) usage;
esac

if test ! -s $cfile || grep @error@ $output_files >nul; then
  : ${TMPDIR=./failure}
  # Don't just delete it, since it may be useful for debugging.
  echo "$0: conversion of $pascalfile failed, moving dregs:" >&2
  cmd="cp $output_files $TMPDIR"
  if test ! -d $TMPDIR ; then
     mkdir $TMPDIR
  fi
  (cd $TMPDIR && rm -f $output_files)
  echo "$0:   $cmd" >&2
  $cmd
  rm -f $output_files
  exit 1
fi

exit 0
