#!/bin/sh

# $Id: incelim,v 1.1 2008-08-04 12:32:50 mike Exp $

if [ $# -eq 0 ]
then
  cat <<USAGE
incelim 1.0

usage:
	incelim [-nnn] [-processor] schema.rng ...
where
	-nnn is number of strip/clean passes (default is -1)
	-processor is XSLT processor to use, default is -saxon,
	 other options are xt, jd.xslt, xalan, 4xslt, xsltproc 

output for
	schema.rng
is in
	schema-compiled.rng
	
Environment variable INCELIM should point to the directory
containing XSLT scripts, default is /usr/local/lib/incelim.

Temporary files are created in a directory pointed to 
by environment variable TMPDIR, /tmp by default.
USAGE
exit 1
fi

INCELIM=${INCELIM:-/usr/local/lib/incelim}
TMPDIR=${TMPDIR:-/tmp}
rinses=1
proc=saxon

options=1
while [ $options -eq 1 ]
do
  case $1 in
     -[0-9]) rinses=`echo $1|sed s/^-//` ; shift ;;
     -xt|-saxon|-jd.xslt|-xalan|-xsltproc|-4xslt) proc=`echo $1|sed s/^-//` ; shift ;;
     -*) echo "unknown option $1" ; exit 1 ;;
     *) options=0 ;;
  esac
done

inc=${TMPDIR}/incelim.inc.$$
str=${TMPDIR}/incelim.str.$$

rmtmp() {
 rm -f $inc $str
}

intr() {
  echo "incelim: interrupted" >&2
  rmtmp
  exit 1
}

errs() {
  echo "incelim: exiting on errors" >&2
  rmtmp
  exit 1
}

xslt() {
  xml=$1
  xsl=${INCELIM}/$2
  res=$3
  case $proc in
    xt) java com.jclark.xsl.sax.Driver $xml $xsl $res ;;
    saxon) java com.icl.saxon.StyleSheet -o $res $xml $xsl ;;
    jd.xslt) java jd.xml.xslt.Stylesheet -out $res $xml $xsl ;;
    xalan) java org.apache.xalan.xslt.Process -IN $xml -XSL $xsl -OUT $res ;;
    4xslt) 4xslt -o $res $xml $xsl ;;
    xsltproc) xsltproc -o $res $xsl $xml ;;
  esac
  if [ $? -ne 0 ]; then errs; fi
}

trap intr HUP INT TERM

for src in $*
do
  tgt=`echo $src|sed 's/\.rng/\-compiled\.rng/'`
  xslt $src inc.xsl $inc
  xslt $inc elim.xsl $tgt
  i=$rinses
  while [ $i -ne 0 ]
  do
    xslt $tgt strip.xsl $str
    xslt $str clean.xsl $tgt
    i=$(($i-1))
  done
done

rmtmp
