#!/bin/sh
#
# "untex"	K. J. Turner	07/04/93
#
# This shell script attempts to remove all (La)TeX commands, but is
# not foolproof. In particular, it can fail to work correctly for
# constructs that span more than one line. The public domain utility
# "detex" would perhaps be a better alternative to "untex".
#
# Source files without a ".tex" extension are automatically given
# one.

prog="`basename $0`"
exttex=".tex"

if [ $# -eq 0 ]
  then
    sed '
      /^\\documentstyle/,/^\\begin{document}/d
      /^\\end{document}$/,$d
      /^\\begin{.*$/d
      /^\\end{.*$/d
      /^\\item$/d
      /^\\label{\(.*\)}$/s//*** \1 ***/
      s/{\\[a-zA-Z][a-zA-Z]* \([^}]*\)/\1/g
      s/{\\[a-zA-Z][a-zA-Z]*$//g
      s/\\[a-zA-Z][a-zA-Z]*{\([^}]*\)}/ \1 /g
      s/\\[a-zA-Z][a-zA-Z]*\[\([^\]]*\)\]/ \1 /g
      s/\\[a-zA-Z][a-zA-Z]*//
      s/{/ /g
      s/}/ /g
      s/\\_/_/g
      s/\$//g
      s/\\\[//g
      s/\\\]//g
      s/\\[, ]/ /g
      s/\\@//g
      s/\\\\//g
      s/~/ /g
      s/%.*$//
    '
    exit 0
fi

while [ "$1" != "" ]; do
  name="`expr Z$1 : Z'\(.*\)\'$exttex`"
  if [ "$name" = "" ]
    then name=$1; filename="$name$exttex"
    else filename=$1
  fi
  if [ -f $filename ]
    then untex < $filename
    else echo "$prog: $filename does not exist"
  fi
  shift
done

exit 0
