############################################################################
#
#	File:     psrsplit.icn
#
#	Subject:  Program to separate psrecord.icn output pages
#
#	Author:   Gregg M. Townsend
#
#	Date:     September 21, 1999
#
############################################################################
#
#   This file is in the public domain.
#
############################################################################
#
#  usage:  psrsplit file
#
#     If a file produced by the procedures in psrecord.icn contains multiple
#  pages, it cannot be easily incorporated into another document.  psrsplit
#  reads such a file and breaks it into individual pages.  The algorithm
#  is frugal of memory and file descriptors at the expense of reading the
#  input file multiple times.
#
#     For an input file is named xxxx or xxxx.yyy, the output files are
#  named xxxx.p01, xxxx.p02, etc. for as many pages as are available.
#  It is assumed that the input file was written by psrecord.icn; the
#  likelihood of correctly processing anything else is small.
#
############################################################################

procedure main(args)
   local ifile, ofile, iname, basename, oname, pageno, line, n

   iname := args[1]			| stop("usage: ", &progname, " file")
   ifile := open(iname)			| stop("can't open ", iname)
   basename := (iname ? tab(upto('.') | 0))

   every pageno := seq() do {		# read file once for each page
      if pageno < 10 then
         oname := basename || ".p0" || pageno
      else
         oname := basename || ".p" || pageno
      ofile := open(oname, "w")		| stop("can't open ", oname)

      seek(ifile, 1)			| stop("can't rewind ", iname)
      line := read(ifile)		| stop(iname, ": empty file")
      line ? ="%!"			| stop(iname, ": not a PostScript file")
      write(&errout, "   writing ", oname)
      write(ofile, "%!PS-Adobe-3.0 EPSF-3.0")

      n := 0
      while n < pageno do {		# copy to nth "copypage"
         line := read(ifile) | break break
         if line ? ="copypage" then
            n +:= 1
         else
            write(ofile, line)
         }
      write(ofile, "showpage")
      write(ofile, "%%EOF")
      close(ofile)
      }
end
