#!/bin/sh

# Add document structuring comments (DSC) to PostScript files to
# make them easier to navigate.
#
# Note: This script only works with some kinds of PS files, e.g.
# those of the Pascal standards distributed on the web.
#
# Requires GNU awk.
#
# Copyright (C) 2001-2005 Free Software Foundation, Inc.
#
# Author: Frank Heckenbach <frank@pascal.gnu.de>
#
# This file is part of GNU Pascal.
#
# GNU Pascal 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 2, or (at your option)
# any later version.
#
# GNU Pascal 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.
#
# You should have received a copy of the GNU General Public License
# along with GNU Pascal; see the file COPYING. If not, write to the
# Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.

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

for f do
  gawk '
    FNR == 1 { $0 = "%!PS-Adobe-2.0\n%%Pages: AtEnd\n%%EndComments" }
    /^TeXDict begin$/ { $0 = "%%EndProlog\n%%BeginSetup\n" $0 "\n%%EndSetup\n%%Page: 1 1"; page = 1 }
    /eop end$/ { sub (" end$", "\n%%Trailer\n&") }
    { print }
    /eop$/ { page++; print "%%Page: " page " " page }
    END { print "%%Pages: " page "\n%%EOF" }
  ' "$f" > "$f.tmp" || exit 1
  mv "$f.tmp" "$f" || exit
done
