#!/bin/sh
#
# texi2dvi filelist...
#
# This shell script runs TeX and texindex on one or more  Texinfo files
# to convert them to DVI files.  It does not run texindex or TeX u
# except as needed.
#
# Copyright (C) 1990 Free Software Foundation.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# A copy of the GNU General Public License can be obtained from this
# program's author (send electronic mail to roland@ai.mit.edu) or from
# the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
# 02139, USA.

if [ $# -eq 0 ]; then
  echo "Usage: `basename $0` FILE ..." >&2
  exit 1
fi

TEXINDEX=${TEXINDEX-texindex}
TEX=${TEX-tex}

for file in $*; do
  base="`echo $file | \
	 sed -e 's/\.texinfo$//' -e 's/\.texi$//' -e 's/\.tex$//'`"

  # Find all existing index files corresponding to FILE.
  idx_files="`echo ${base}.??`"
  if [ "$idx_files" = "${base}.??" ]; then
    idx_files=''
  else
    # Ignore files with two-letter extensions that don't look like index files.
    oidx_files="$idx_files"
    idx_files=''
    for idx_file in $oidx_files; do
      if [ "`sed -n '1s/^\(.\).*$/\1/' $idx_file`" = \\ ]; then
        # It starts with a backslash, so it's probably an index file.
	idx_files="$idx_files $idx_file"
      fi
    done
  fi

  for idx_file in $idx_files; do
    # Save a copy of the old index file.
    cp ${idx_file} ${idx_file}O
  done

  if [ "$idx_files" != "" ]; then
    # Run texindex on the index files.
    ${TEXINDEX} $idx_files
  fi

  # Run TeX on FILE.
  ${TEX} $file

  # Run through all the index files, comparing them to the old ones.
  changed=no
  for idx_file in $idx_files; do
    # Compare the old and new index files.
    cmp -s ${idx_file}O ${idx_file}
    status=$?

    # Remove the old index file.
    rm -f ${idx_file}O

    if [ $status -ne 0 ]; then
      # The index file has changed.
      changed=yes
    fi
  done	# for idx_file

  if [ "`echo ${base}.??`" != "$idx_files" ]; then
    # There are new index files.
    changed=yes
  fi

  if [ $changed = yes ]; then
    # Some index file changed.  Run texindex and TeX again.

    # Run texindex on the index files.
    ${TEXINDEX} ${base}.??

    # Run TeX on FILE.
    ${TEX} $file
  fi

done	   # for file
