#!/bin/sh
PATH=/opt/gnu/bin:/usr/bin:/bin
#
# Postscript page counter by Ivan Popov, Feb 1997, heavily based on:
#
# # $Id: pspages,v 1.1 1993/08/25 20:20:41 grover Exp $
# #
# # count the number of pages output by a PostScript file
# # Requires GhostScript 1.5 or greater
# #
# # Syntax:  pspages [psfile [...]]
# #
# # - Kevin O. Grover, grover@isri.unlv.edu
# # Cre: Wed 08-Aug-1993
# #
# # pspages is an sh script to count the number of pages in a postscript
# # file.  It counts all instances of an output page (included copypage
# # and/or showpage).  It also works on files that redefine copypage
# # and/or showpage.  It requires ghostscript to run.  It works by
# # redefining the copypage and showpage commands to keep track of the
# # number of pages output, and then, at the end of the ps file, it
# # outputs the number of pages.
#
# Returns: number of pages or word "BAD" on stdout if there were problems
# with postscript.
#
# Exit code is 0 or 1, respectively.
#

COOKIE="PS PaGE CoUnTer"

result=`(
cat <<_END_PROLOG
/showpage {
  erasepage initgraphics
  (${COOKIE}\n) print
} bind def
/copypage {
  erasepage initgraphics
  (${COOKIE}\n) print
} bind def
_END_PROLOG
cat $*
) | gs -q -dNODISPLAY -r1 -dNOPAUSE -dSAFER - |
awk '
BEGIN { pages = 0 }
/^'"$COOKIE"'$/ { pages += 1; next }
{ print "BAD"; exit }
END { print pages }
'`

case x"$result" in
x[1-9]*) echo $result; exit 0 ;;
esac

echo BAD
exit 1

