#!/bin/sh -e
# ECI Text Corpus UNIX shell wrapper for sgmls.
# Includes appropriate system declaration file, search path.
#
# Usage: eci [-trace] [-dir dir] [-showpath] [switches for sgmls] [filename]
#
# Invoke tracing with -trace flag, to debug entity location failures
# pipe into "grep ENOENT"
#
# When piping in, use -dir to specify the origin directory
#
# Echos SGML_PATH to STDERR if -showpath is used
#
# Uses the environment variable ECI_ROOT, which should be the full
# pathname of the root of the ECI directory tree -- usually
# this will be the mount directory of an ECI CD.
#
# Uses the environment variable ECI_PATCH, which can be used in future to
# point to patch directories if we find it necessary to distribute patches.
# The value of this if defined should probably be a valid prefix
# to SGML_PATH with %T on each component, e.g. "/foo/%T:/baz/bar/%T:"
# NOTE THE TRAILING COLON!!!!
#
if [ ! "$ECI_ROOT" ]
 then
  echo "Must set ECI_ROOT before using!" 1>&2
  exit 10
fi
#
ECI_LIB=$ECI_ROOT/lib/tei
while case $1 in
        -trace) trace="trace";;
        -dir) shift; dir=$1;;
        -showpath) shp=yes;;
	-*) sw="$sw $1";;
	*) break;;
      esac
 do
  shift
done
if [ "$1" ]
 then
   ff=$1
   shift
fi
if [ -f "$ff" ]
  then
   path=`perl $ECI_ROOT/src/perl/ecipath.pl $ff`
   if [ ! "$path" ]; then exit 1; fi
 elif [ "$ff" = mci.sgm ]
  then
   dir=${dir:-$ECI_ROOT}
   path=`perl $ECI_ROOT/src/perl/ecipath.pl $dir/$ff`
   if [ ! "$path" ]; then exit 1; fi
   ff=$dir/$ff
 elif [ "$dir" ]
  then
   path="$dir%T"
 elif [ "$ff" ]
  then
   # try to provide a path
   line=`perl $ECI_ROOT/src/perl/unpackfn.pl $ff`
   read dir corp comp sub <<EOL
$line
EOL
   nd=`echo $ECI_ROOT/data/eci?/$corp`
   ff=$nd/$corp$comp$sub.sgm
   if [ -f "$ff" ]
    then
     echo "${dir:="./"}$corp$comp$sub.sgm not found, trying $ff instead" 1>&2
     path=`perl $ECI_ROOT/src/perl/ecipath.pl $ff`
     if [ ! "$path" ]; then exit 3; fi
    else
     echo "Can't find ${dir:="./"}$corp$comp$sub.sgm anywhere, giving up" 1>&2
     exit 3
   fi
 else
   path="%T"
fi

SGML_PATH=$ECI_PATCH$ECI_LIB/%T.dtd:$ECI_LIB/%T.ent:$path
if [ "$shp" ]
  then
   echo "SGML_PATH is $SGML_PATH" 1>&2
fi
export SGML_PATH
$trace sgmls $sw $ECI_LIB/tei.dcl ${ff:--}
