#!/bin/csh -f

# Doesn't handle \documentstyle, because you should be able to replace
# that with \documentclass and \usepackage.

set debug = 0

set fullprogname = $0
set progname = $fullprogname:t

set searchpath = (`echo $TEXINPUTS | tr ':' ' '`)

set ext
if ($#argv > 1) then
  set ext = "$1"
  shift
endif

foreach file (`echo $* | tr ',' ' '`)

unset fullfile

foreach dir ($searchpath)
  if ("$ext" == "") then
    if (-e $dir/$file) then
      set fullfile = $dir/$file
      break
    endif
    if (-e $dir/$file.tex) then
      set fullfile = $dir/$file.tex
      break
    endif
  else
    if (-e $dir/$file.$ext) then
      set fullfile = $dir/$file.$ext
      break
    endif
  endif
end

if (! $?fullfile) then
  echo "${progname}: File $file not found in TEXINPUTS" > /dev/tty
  exit (1)
endif

if ($debug) echo "${progname}:  fullfile: $fullfile" > /dev/tty

set tempscript = /tmp/${progname}.$$

cat $fullfile | tr '\140\047\041' '' | awk '{print "echo " $0 ""}' \
  | sed '\
   s+^echo \(.*\)\\input{\([^{}]*\)}\(.*\)$+'\1\n${progname}' \2\n\3+\
   s+^echo \(.*\)\\inputnospell{\([^{}]*\)}\(.*\)$+'\1\n${progname}' \2\n\3+\
   s+^echo \(.*\)\\incite{\([^{}]*\)}\(.*\)$+'\1\n${progname}' \2\n\3+\
   s+^echo \(.*\)\\usepackage{\([^{}]*\)}\(.*\)$+'\1\n${progname}' sty \2\n\3+\
   s+^echo \(.*\)\\bibliography{[^{}]*}\(.*\)$+'\1\n${progname}' bbl '$file:r'+\
   s+^echo \(.*\)\\@starttoc{\([^{}]*\)}\(.*\)$+'\1\n${progname}' \2 '$file:r'\n\3+\
   ' | tr "" "'" >$tempscript
if ($debug > 1) then
  echo "${progname}: About to execute ${tempscript}:" > /dev/tty
  cat -v $tempscript > /dev/tty
  echo '' > /dev/tty
endif
chmod +x $tempscript
csh -f $tempscript | tr '' '\140\047\041'
rm -f $tempscript

end
