#!/bin/sh
# tocfix - move a DVI file table of contents to its proper position

# TeX puts the table of contents at the end of the DVI file.
# If you're printing multiple pages per sheet, you can't fix it
# on the printout.  This program moves the TOC to be right after
# the titlepage and copyright page.
# It's a safe no-op to run this program on a DVI file more than once.

# Some explanation: the TOC has negative page numbers, represented
# to dviselect by an underscore.  The titlepage and copyright page
# have TeX page numbers 1 and 2, but so do the first two pages of the
# first chapter.  So we have to use absolute, as opposed to TeX,
# page numbers to get them right, represented to dviselect by an
# equals sign.

# This program assumes that the DVI file has the standard Texinfo
# format -- a titlepage, a copyright page, then the real text.

# djm@cygnus.com (David MacKenzie)

trap 'rm -f new-*.dvi title.dvi toc.dvi body_plus_toc.dvi body.dvi; exit 1' 1 3 15

if [ $# -eq 0 ]; then
    echo "Usage; tocfix dvifile..." >&2; exit 1
fi

for dvi
do
    dviselect -i $dvi -o title.dvi =1:2
    dviselect -i $dvi -o toc.dvi :_1
    dviselect -i $dvi -o body_plus_toc.dvi =3:
    dviselect -i body_plus_toc.dvi -o body.dvi 1:
    dviconcat -o new-$dvi title.dvi toc.dvi body.dvi
    mv new-$dvi $dvi
    rm -f title.dvi toc.dvi body_plus_toc.dvi body.dvi
done
