Index: pkpgcounter/tags/2.18/BUGS
===================================================================
--- pkpgcounter/tags/2.18/BUGS (revision 443)
+++ pkpgcounter/tags/2.18/BUGS (revision 443)
@@ -0,0 +1,27 @@
+# $Id$
+
+pkpgcounter : a generic Page Description Language parser
+
+(c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+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 2 of the License, 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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+=============================================================================
+
+pkpgcounter BUGS :
+   
+  - All parsers need more testing, especially those which allow the number
+    of copies to be specified as part of the data streams, as well as those
+    which allow N-up.
+
Index: pkpgcounter/tags/2.18/debian/menu.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/menu.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/menu.ex (revision 458)
@@ -0,0 +1,2 @@
+?package(pkpgcounter):needs="X11|text|vc|wm" section="Apps/see-menu-manual"\
+  title="pkpgcounter" command="/usr/bin/pkpgcounter"
Index: pkpgcounter/tags/2.18/debian/control
===================================================================
--- pkpgcounter/tags/2.18/debian/control (revision 458)
+++ pkpgcounter/tags/2.18/debian/control (revision 458)
@@ -0,0 +1,47 @@
+Source: pkpgcounter
+Section: text
+Priority: optional
+Maintainer: Jerome Alet <alet@librelogiciel.com>
+Build-Depends: debhelper (>= 4.0.0), python, python-dev
+Standards-Version: 3.6.2
+
+Package: pkpgcounter
+Architecture: any
+Depends: python, python-imaging, gs | gs-esp
+Suggests: python-psyco, ghostpcl | gspcl
+Description: pkpgcounter is a command line tool and Python
+ library which can count the number of pages in files or
+ compute the percent of ink used for each color in a 
+ number of different colorspaces.
+ .
+ The supported file formats are :
+ .
+   * PostScript
+ .
+   * PCLXL (aka PCL6)
+ .
+   * PCL3/4/5
+ .
+   * PDF
+ .
+   * DVI
+ .
+   * Plain text
+ .
+   * TIFF
+ .
+   * ESC/P2
+ .
+   * OpenDocument (ISO/IEC DIS 26300)
+ .
+   * Zenographics ZjStream
+ .
+   * Samsung QPDL (aka SPL2)
+ .
+   * Samsung SPL1
+ .
+ The five latter formats, as well as some TIFF files, are
+ only supported in page counting mode.
+ .
+ pkpgcounter is often used in combination with print
+ accounting solutions like PyKota or JasMine.
Index: pkpgcounter/tags/2.18/debian/emacsen-remove.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/emacsen-remove.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/emacsen-remove.ex (revision 458)
@@ -0,0 +1,15 @@
+#!/bin/sh -e
+# /usr/lib/emacsen-common/packages/remove/pkpgcounter
+
+FLAVOR=$1
+PACKAGE=pkpgcounter
+
+if [ ${FLAVOR} != emacs ]; then
+    if test -x /usr/sbin/install-info-altdir; then
+        echo remove/${PACKAGE}: removing Info links for ${FLAVOR}
+        install-info-altdir --quiet --remove --dirname=${FLAVOR} /usr/info/pkpgcounter.info.gz
+    fi
+
+    echo remove/${PACKAGE}: purging byte-compiled files for ${FLAVOR}
+    rm -rf /usr/share/${FLAVOR}/site-lisp/${PACKAGE}
+fi
Index: pkpgcounter/tags/2.18/debian/watch.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/watch.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/watch.ex (revision 458)
@@ -0,0 +1,22 @@
+# Example watch control file for uscan
+# Rename this file to "watch" and then you can run the "uscan" command
+# to check for upstream updates and more.
+# See uscan(1) for format
+
+# Compulsory line, this is a version 3 file
+version=3
+
+# Uncomment to examine a Webpage 
+# <Webpage URL> <string match>
+#http://www.example.com/downloads.php pkpgcounter-(.*)\.tar\.gz
+
+# Uncomment to examine a Webserver directory
+#http://www.example.com/pub/pkpgcounter-(.*)\.tar\.gz
+
+# Uncommment to examine a FTP server
+#ftp://ftp.example.com/pub/pkpgcounter-(.*)\.tar\.gz debian uupdate
+
+# Uncomment to find new files on sourceforge, for debscripts >= 2.9
+# http://sf.net/pkpgcounter/pkpgcounter-(.*)\.tar\.gz
+
+
Index: pkpgcounter/tags/2.18/debian/manpage.xml.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/manpage.xml.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/manpage.xml.ex (revision 458)
@@ -0,0 +1,148 @@
+<?xml version='1.0' encoding='ISO-8859-1'?>
+<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
+"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd" [
+
+<!--
+
+Process this file with an XSLT processor: `xsltproc \
+-''-nonet /usr/share/sgml/docbook/stylesheet/xsl/nwalsh/\
+manpages/docbook.xsl manpage.dbk'.  A manual page
+<package>.<section> will be generated.  You may view the
+manual page with: nroff -man <package>.<section> | less'.  A
+typical entry in a Makefile or Makefile.am is:
+
+DB2MAN=/usr/share/sgml/docbook/stylesheet/xsl/nwalsh/\
+manpages/docbook.xsl
+XP=xsltproc -''-nonet
+
+manpage.1: manpage.dbk
+        $(XP) $(DB2MAN) $<
+    
+The xsltproc binary is found in the xsltproc package.  The
+XSL files are in docbook-xsl.  Please remember that if you
+create the nroff version in one of the debian/rules file
+targets (such as build), you will need to include xsltproc
+and docbook-xsl in your Build-Depends control field.
+
+-->
+
+  <!-- Fill in your name for FIRSTNAME and SURNAME. -->
+  <!ENTITY dhfirstname "<firstname>FIRSTNAME</firstname>">
+  <!ENTITY dhsurname   "<surname>SURNAME</surname>">
+  <!-- Please adjust the date whenever revising the manpage. -->
+  <!ENTITY dhdate      "<date>juillet 25, 2007</date>">
+  <!-- SECTION should be 1-8, maybe w/ subsection other parameters are
+       allowed: see man(7), man(1). -->
+  <!ENTITY dhsection   "<manvolnum>SECTION</manvolnum>">
+  <!ENTITY dhemail     "<email>alet@librelogiciel.com</email>">
+  <!ENTITY dhusername  "Jerome Alet">
+  <!ENTITY dhucpackage "<refentrytitle>PKPGCOUNTER</refentrytitle>">
+  <!ENTITY dhpackage   "pkpgcounter">
+
+  <!ENTITY debian      "<productname>Debian</productname>">
+  <!ENTITY gnu         "<acronym>GNU</acronym>">
+  <!ENTITY gpl         "&gnu; <acronym>GPL</acronym>">
+]>
+
+<refentry>
+  <refentryinfo>
+    <address>
+      &dhemail;
+    </address>
+    <author>
+      &dhfirstname;
+      &dhsurname;
+    </author>
+    <copyright>
+      <year>2003</year>
+      <holder>&dhusername;</holder>
+    </copyright>
+    &dhdate;
+  </refentryinfo>
+  <refmeta>
+    &dhucpackage;
+
+    &dhsection;
+  </refmeta>
+  <refnamediv>
+    <refname>&dhpackage;</refname>
+
+    <refpurpose>program to do something</refpurpose>
+  </refnamediv>
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>&dhpackage;</command>
+
+      <arg><option>-e <replaceable>this</replaceable></option></arg>
+
+      <arg><option>--example <replaceable>that</replaceable></option></arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+  <refsect1>
+    <title>DESCRIPTION</title>
+
+    <para>This manual page documents briefly the
+      <command>&dhpackage;</command> and <command>bar</command>
+      commands.</para>
+
+    <para>This manual page was written for the &debian; distribution
+      because the original program does not have a manual page.
+      Instead, it has documentation in the &gnu;
+      <application>Info</application> format; see below.</para>
+
+    <para><command>&dhpackage;</command> is a program that...</para>
+
+  </refsect1>
+  <refsect1>
+    <title>OPTIONS</title>
+
+    <para>These programs follow the usual &gnu; command line syntax,
+      with long options starting with two dashes (`-').  A summary of
+      options is included below.  For a complete description, see the
+      <application>Info</application> files.</para>
+
+    <variablelist>
+      <varlistentry>
+        <term><option>-h</option>
+          <option>--help</option>
+        </term>
+        <listitem>
+          <para>Show summary of options.</para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term><option>-v</option>
+          <option>--version</option>
+        </term>
+        <listitem>
+          <para>Show version of program.</para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+  </refsect1>
+  <refsect1>
+    <title>SEE ALSO</title>
+
+    <para>bar (1), baz (1).</para>
+
+    <para>The programs are documented fully by <citetitle>The Rise and
+      Fall of a Fooish Bar</citetitle> available via the
+      <application>Info</application> system.</para>
+  </refsect1>
+  <refsect1>
+    <title>AUTHOR</title>
+
+    <para>This manual page was written by &dhusername; &dhemail; for
+      the &debian; system (but may be used by others).  Permission is
+      granted to copy, distribute and/or modify this document under
+      the terms of the &gnu; General Public License, Version 2 any 
+	  later version published by the Free Software Foundation.
+    </para>
+	<para>
+	  On Debian systems, the complete text of the GNU General Public
+	  License can be found in /usr/share/common-licenses/GPL.
+	</para>
+
+  </refsect1>
+</refentry>
+
Index: pkpgcounter/tags/2.18/debian/manpage.1.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/manpage.1.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/manpage.1.ex (revision 458)
@@ -0,0 +1,59 @@
+.\"                                      Hey, EMACS: -*- nroff -*-
+.\" First parameter, NAME, should be all caps
+.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
+.\" other parameters are allowed: see man(7), man(1)
+.TH PKPGCOUNTER SECTION "juillet 25, 2007"
+.\" Please adjust this date whenever revising the manpage.
+.\"
+.\" Some roff macros, for reference:
+.\" .nh        disable hyphenation
+.\" .hy        enable hyphenation
+.\" .ad l      left justify
+.\" .ad b      justify to both left and right margins
+.\" .nf        disable filling
+.\" .fi        enable filling
+.\" .br        insert line break
+.\" .sp <n>    insert n+1 empty lines
+.\" for manpage-specific macros, see man(7)
+.SH NAME
+pkpgcounter \- program to do something
+.SH SYNOPSIS
+.B pkpgcounter
+.RI [ options ] " files" ...
+.br
+.B bar
+.RI [ options ] " files" ...
+.SH DESCRIPTION
+This manual page documents briefly the
+.B pkpgcounter
+and
+.B bar
+commands.
+.PP
+.\" TeX users may be more comfortable with the \fB<whatever>\fP and
+.\" \fI<whatever>\fP escape sequences to invode bold face and italics, 
+.\" respectively.
+\fBpkpgcounter\fP is a program that...
+.SH OPTIONS
+These programs follow the usual GNU command line syntax, with long
+options starting with two dashes (`-').
+A summary of options is included below.
+For a complete description, see the Info files.
+.TP
+.B \-h, \-\-help
+Show summary of options.
+.TP
+.B \-v, \-\-version
+Show version of program.
+.SH SEE ALSO
+.BR bar (1),
+.BR baz (1).
+.br
+The programs are documented fully by
+.IR "The Rise and Fall of a Fooish Bar" ,
+available via the Info system.
+.SH AUTHOR
+pkpgcounter was written by <upstream author>.
+.PP
+This manual page was written by Jerome Alet <alet@librelogiciel.com>,
+for the Debian project (but may be used by others).
Index: pkpgcounter/tags/2.18/debian/conffiles.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/conffiles.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/conffiles.ex (revision 458)
@@ -0,0 +1,7 @@
+#
+# If you want to use this conffile, remove all comments and put files that
+# you want dpkg to process here using their absolute pathnames.
+# See the policy manual
+#
+# for example:
+# /etc/pkpgcounter/pkpgcounter.conf
Index: pkpgcounter/tags/2.18/debian/compat
===================================================================
--- pkpgcounter/tags/2.18/debian/compat (revision 458)
+++ pkpgcounter/tags/2.18/debian/compat (revision 458)
@@ -0,0 +1,1 @@
+4
Index: pkpgcounter/tags/2.18/debian/manpage.sgml.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/manpage.sgml.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/manpage.sgml.ex (revision 458)
@@ -0,0 +1,156 @@
+<!doctype refentry PUBLIC "-//OASIS//DTD DocBook V4.1//EN" [
+
+<!-- Process this file with docbook-to-man to generate an nroff manual
+     page: `docbook-to-man manpage.sgml > manpage.1'.  You may view
+     the manual page with: `docbook-to-man manpage.sgml | nroff -man |
+     less'.  A typical entry in a Makefile or Makefile.am is:
+
+manpage.1: manpage.sgml
+	docbook-to-man $< > $@
+
+    
+	The docbook-to-man binary is found in the docbook-to-man package.
+	Please remember that if you create the nroff version in one of the
+	debian/rules file targets (such as build), you will need to include
+	docbook-to-man in your Build-Depends control field.
+
+  -->
+
+  <!-- Fill in your name for FIRSTNAME and SURNAME. -->
+  <!ENTITY dhfirstname "<firstname>FIRSTNAME</firstname>">
+  <!ENTITY dhsurname   "<surname>SURNAME</surname>">
+  <!-- Please adjust the date whenever revising the manpage. -->
+  <!ENTITY dhdate      "<date>juillet 25, 2007</date>">
+  <!-- SECTION should be 1-8, maybe w/ subsection other parameters are
+       allowed: see man(7), man(1). -->
+  <!ENTITY dhsection   "<manvolnum>SECTION</manvolnum>">
+  <!ENTITY dhemail     "<email>alet@librelogiciel.com</email>">
+  <!ENTITY dhusername  "Jerome Alet">
+  <!ENTITY dhucpackage "<refentrytitle>PKPGCOUNTER</refentrytitle>">
+  <!ENTITY dhpackage   "pkpgcounter">
+
+  <!ENTITY debian      "<productname>Debian</productname>">
+  <!ENTITY gnu         "<acronym>GNU</acronym>">
+  <!ENTITY gpl         "&gnu; <acronym>GPL</acronym>">
+]>
+
+<refentry>
+  <refentryinfo>
+    <address>
+      &dhemail;
+    </address>
+    <author>
+      &dhfirstname;
+      &dhsurname;
+    </author>
+    <copyright>
+      <year>2003</year>
+      <holder>&dhusername;</holder>
+    </copyright>
+    &dhdate;
+  </refentryinfo>
+  <refmeta>
+    &dhucpackage;
+
+    &dhsection;
+  </refmeta>
+  <refnamediv>
+    <refname>&dhpackage;</refname>
+
+    <refpurpose>program to do something</refpurpose>
+  </refnamediv>
+  <refsynopsisdiv>
+    <cmdsynopsis>
+      <command>&dhpackage;</command>
+
+      <arg><option>-e <replaceable>this</replaceable></option></arg>
+
+      <arg><option>--example <replaceable>that</replaceable></option></arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+  <refsect1>
+    <title>DESCRIPTION</title>
+
+    <para>This manual page documents briefly the
+      <command>&dhpackage;</command> and <command>bar</command>
+      commands.</para>
+
+    <para>This manual page was written for the &debian; distribution
+      because the original program does not have a manual page.
+      Instead, it has documentation in the &gnu;
+      <application>Info</application> format; see below.</para>
+
+    <para><command>&dhpackage;</command> is a program that...</para>
+
+  </refsect1>
+  <refsect1>
+    <title>OPTIONS</title>
+
+    <para>These programs follow the usual &gnu; command line syntax,
+      with long options starting with two dashes (`-').  A summary of
+      options is included below.  For a complete description, see the
+      <application>Info</application> files.</para>
+
+    <variablelist>
+      <varlistentry>
+        <term><option>-h</option>
+          <option>--help</option>
+        </term>
+        <listitem>
+          <para>Show summary of options.</para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term><option>-v</option>
+          <option>--version</option>
+        </term>
+        <listitem>
+          <para>Show version of program.</para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+  </refsect1>
+  <refsect1>
+    <title>SEE ALSO</title>
+
+    <para>bar (1), baz (1).</para>
+
+    <para>The programs are documented fully by <citetitle>The Rise and
+      Fall of a Fooish Bar</citetitle> available via the
+      <application>Info</application> system.</para>
+  </refsect1>
+  <refsect1>
+    <title>AUTHOR</title>
+
+    <para>This manual page was written by &dhusername; &dhemail; for
+      the &debian; system (but may be used by others).  Permission is
+      granted to copy, distribute and/or modify this document under
+      the terms of the &gnu; General Public License, Version 2 any 
+	  later version published by the Free Software Foundation.
+    </para>
+	<para>
+	  On Debian systems, the complete text of the GNU General Public
+	  License can be found in /usr/share/common-licenses/GPL.
+	</para>
+
+  </refsect1>
+</refentry>
+
+<!-- Keep this comment at the end of the file
+Local variables:
+mode: sgml
+sgml-omittag:t
+sgml-shorttag:t
+sgml-minimize-attributes:nil
+sgml-always-quote-attributes:t
+sgml-indent-step:2
+sgml-indent-data:t
+sgml-parent-document:nil
+sgml-default-dtd-file:nil
+sgml-exposed-tags:nil
+sgml-local-catalogs:nil
+sgml-local-ecat-files:nil
+End:
+-->
+
+
Index: pkpgcounter/tags/2.18/debian/emacsen-startup.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/emacsen-startup.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/emacsen-startup.ex (revision 458)
@@ -0,0 +1,19 @@
+;; -*-emacs-lisp-*-
+;;
+;; Emacs startup file for the Debian pkpgcounter package
+;;
+;; Originally contributed by Nils Naumann <naumann@unileoben.ac.at>
+;; Modified by Dirk Eddelbuettel <edd@debian.org>
+;; Adapted for dh-make by Jim Van Zandt <jrv@vanzandt.mv.com>
+
+;; The pkpgcounter package follows the Debian/GNU Linux 'emacsen' policy and
+;; byte-compiles its elisp files for each 'emacs flavor' (emacs19,
+;; xemacs19, emacs20, xemacs20...).  The compiled code is then
+;; installed in a subdirectory of the respective site-lisp directory.
+;; We have to add this to the load-path:
+(let ((package-dir (concat "/usr/share/"
+                           (symbol-name flavor)
+                           "/site-lisp/pkpgcounter")))
+  (when (file-directory-p package-dir)
+        (setq load-path (cons package-dir load-path))))
+
Index: pkpgcounter/tags/2.18/debian/changelog
===================================================================
--- pkpgcounter/tags/2.18/debian/changelog (revision 458)
+++ pkpgcounter/tags/2.18/debian/changelog (revision 458)
@@ -0,0 +1,6 @@
+pkpgcounter (2.17-1) unstable; urgency=low
+
+  * Initial release
+
+ -- Jerome Alet <alet@librelogiciel.com>  Wed, 25 Jul 2007 11:09:28 +0200
+
Index: pkpgcounter/tags/2.18/debian/docs
===================================================================
--- pkpgcounter/tags/2.18/debian/docs (revision 458)
+++ pkpgcounter/tags/2.18/debian/docs (revision 458)
@@ -0,0 +1,3 @@
+BUGS
+NEWS
+README
Index: pkpgcounter/tags/2.18/debian/pkpgcounter.doc-base.EX
===================================================================
--- pkpgcounter/tags/2.18/debian/pkpgcounter.doc-base.EX (revision 458)
+++ pkpgcounter/tags/2.18/debian/pkpgcounter.doc-base.EX (revision 458)
@@ -0,0 +1,22 @@
+Document: pkpgcounter
+Title: Debian pkpgcounter Manual
+Author: <insert document author here>
+Abstract: This manual describes what pkpgcounter is
+ and how it can be used to
+ manage online manuals on Debian systems.
+Section: unknown
+
+Format: debiandoc-sgml
+Files: /usr/share/doc/pkpgcounter/pkpgcounter.sgml.gz
+
+Format: postscript
+Files: /usr/share/doc/pkpgcounter/pkpgcounter.ps.gz
+
+Format: text
+Files: /usr/share/doc/pkpgcounter/pkpgcounter.text.gz
+
+Format: HTML
+Index: /usr/share/doc/pkpgcounter/html/index.html
+Files: /usr/share/doc/pkpgcounter/html/*.html
+
+  
Index: pkpgcounter/tags/2.18/debian/emacsen-install.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/emacsen-install.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/emacsen-install.ex (revision 458)
@@ -0,0 +1,45 @@
+#! /bin/sh -e
+# /usr/lib/emacsen-common/packages/install/pkpgcounter
+
+# Written by Jim Van Zandt <jrv@vanzandt.mv.com>, borrowing heavily
+# from the install scripts for gettext by Santiago Vila
+# <sanvila@ctv.es> and octave by Dirk Eddelbuettel <edd@debian.org>.
+
+FLAVOR=$1
+PACKAGE=pkpgcounter
+
+if [ ${FLAVOR} = emacs ]; then exit 0; fi
+
+echo install/${PACKAGE}: Handling install for emacsen flavor ${FLAVOR}
+
+#FLAVORTEST=`echo $FLAVOR | cut -c-6`
+#if [ ${FLAVORTEST} = xemacs ] ; then
+#    SITEFLAG="-no-site-file"
+#else
+#    SITEFLAG="--no-site-file"
+#fi
+FLAGS="${SITEFLAG} -q -batch -l path.el -f batch-byte-compile"
+
+ELDIR=/usr/share/emacs/site-lisp/${PACKAGE}
+ELCDIR=/usr/share/${FLAVOR}/site-lisp/${PACKAGE}
+
+# Install-info-altdir does not actually exist. 
+# Maybe somebody will write it.
+if test -x /usr/sbin/install-info-altdir; then
+    echo install/${PACKAGE}: install Info links for ${FLAVOR}
+    install-info-altdir --quiet --section "" "" --dirname=${FLAVOR} /usr/info/${PACKAGE}.info.gz
+fi
+
+install -m 755 -d ${ELCDIR}
+cd ${ELDIR}
+FILES=`echo *.el`
+cp ${FILES} ${ELCDIR}
+cd ${ELCDIR}
+
+cat << EOF > path.el
+(setq load-path (cons "." load-path) byte-compile-warnings nil)
+EOF
+${FLAVOR} ${FLAGS} ${FILES}
+rm -f *.el path.el
+
+exit 0
Index: pkpgcounter/tags/2.18/debian/rules
===================================================================
--- pkpgcounter/tags/2.18/debian/rules (revision 458)
+++ pkpgcounter/tags/2.18/debian/rules (revision 458)
@@ -0,0 +1,102 @@
+#!/usr/bin/make -f
+# -*- makefile -*-
+# Sample debian/rules that uses debhelper.
+# This file was originally written by Joey Hess and Craig Small.
+# As a special exception, when this file is copied by dh-make into a
+# dh-make output file, you may use that output file without restriction.
+# This special exception was added by Craig Small in version 0.37 of dh-make.
+
+# Uncomment this to turn on verbose mode.
+#export DH_VERBOSE=1
+
+
+
+
+CFLAGS = -Wall -g
+
+ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
+	CFLAGS += -O0
+else
+	CFLAGS += -O2
+endif
+
+configure: configure-stamp
+configure-stamp:
+	dh_testdir
+	# Add here commands to configure the package.
+        
+	touch configure-stamp
+
+
+build: build-stamp
+
+build-stamp: configure-stamp 
+	dh_testdir
+
+	# Add here commands to compile the package.
+	#$(MAKE)
+	python setup.py build
+	#docbook-to-man debian/pkpgcounter.sgml > pkpgcounter.1
+
+	touch build-stamp
+
+clean:
+	dh_testdir
+	dh_testroot
+	rm -f build-stamp configure-stamp
+
+	# Add here commands to clean up after the build process.
+	#-$(MAKE) clean
+	python setup.py clean --all
+	rm -f pkpgpdls/version.pyc pkpgpdls/__init__.pyc
+
+	dh_clean 
+
+install: build
+	dh_testdir
+	dh_testroot
+	dh_clean -k 
+	dh_installdirs
+
+	# Add here commands to install the package into debian/pkpgcounter.
+	#$(MAKE) install DESTDIR=$(CURDIR)/debian/pkpgcounter
+	python setup.py install --prefix $(CURDIR)/debian/pkpgcounter/usr --no-compile
+
+
+# Build architecture-independent files here.
+binary-indep: build install
+# We have nothing to do by default.
+
+# Build architecture-dependent files here.
+binary-arch: build install
+	dh_testdir
+	dh_testroot
+	dh_installchangelogs 
+	dh_installdocs
+	dh_installexamples
+#	dh_install
+#	dh_installmenu
+	dh_installdebconf	
+#	dh_installlogrotate
+#	dh_installemacsen
+#	dh_installpam
+#	dh_installmime
+#	dh_installinit
+#	dh_installcron
+#	dh_installinfo
+	dh_installman
+	dh_link
+	dh_strip
+	dh_compress
+	dh_fixperms
+#	dh_perl
+	dh_pysupport
+#	dh_makeshlibs
+	dh_installdeb
+#	dh_shlibdeps
+	dh_gencontrol
+	dh_md5sums
+	dh_builddeb
+
+binary: binary-indep binary-arch
+.PHONY: build clean binary-indep binary-arch binary install configure
Index: pkpgcounter/tags/2.18/debian/cron.d.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/cron.d.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/cron.d.ex (revision 458)
@@ -0,0 +1,4 @@
+#
+# Regular cron jobs for the pkpgcounter package
+#
+0 4	* * *	root	pkpgcounter_maintenance
Index: pkpgcounter/tags/2.18/debian/pkpgcounter-default.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/pkpgcounter-default.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/pkpgcounter-default.ex (revision 458)
@@ -0,0 +1,10 @@
+# Defaults for pkpgcounter initscript
+# sourced by /etc/init.d/pkpgcounter
+# installed at /etc/default/pkpgcounter by the maintainer scripts
+
+#
+# This is a POSIX shell fragment
+#
+
+# Additional options that are passed to the Daemon.
+DAEMON_OPTS=""
Index: pkpgcounter/tags/2.18/debian/postinst.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/postinst.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/postinst.ex (revision 458)
@@ -0,0 +1,42 @@
+#! /bin/sh
+# postinst script for pkpgcounter
+#
+# see: dh_installdeb(1)
+
+set -e
+
+# summary of how this script can be called:
+#        * <postinst> `configure' <most-recently-configured-version>
+#        * <old-postinst> `abort-upgrade' <new version>
+#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
+#          <new-version>
+#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
+#          <failed-install-package> <version> `removing'
+#          <conflicting-package> <version>
+# for details, see http://www.debian.org/doc/debian-policy/ or
+# the debian-policy package
+#
+
+case "$1" in
+    configure)
+
+    ;;
+
+    abort-upgrade|abort-remove|abort-deconfigure)
+
+    ;;
+
+    *)
+        echo "postinst called with unknown argument \`$1'" >&2
+        exit 1
+    ;;
+esac
+
+# dh_installdeb will replace this with shell code automatically
+# generated by other debhelper scripts.
+
+#DEBHELPER#
+
+exit 0
+
+
Index: pkpgcounter/tags/2.18/debian/postrm.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/postrm.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/postrm.ex (revision 458)
@@ -0,0 +1,38 @@
+#! /bin/sh
+# postrm script for pkpgcounter
+#
+# see: dh_installdeb(1)
+
+set -e
+
+# summary of how this script can be called:
+#        * <postrm> `remove'
+#        * <postrm> `purge'
+#        * <old-postrm> `upgrade' <new-version>
+#        * <new-postrm> `failed-upgrade' <old-version>
+#        * <new-postrm> `abort-install'
+#        * <new-postrm> `abort-install' <old-version>
+#        * <new-postrm> `abort-upgrade' <old-version>
+#        * <disappearer's-postrm> `disappear' <r>overwrit>r> <new-version>
+# for details, see http://www.debian.org/doc/debian-policy/ or
+# the debian-policy package
+
+
+case "$1" in
+       purge|remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
+
+
+        ;;
+
+    *)
+        echo "postrm called with unknown argument \`$1'" >&2
+        exit 1
+
+esac
+
+# dh_installdeb will replace this with shell code automatically
+# generated by other debhelper scripts.
+
+#DEBHELPER#
+
+exit 0
Index: pkpgcounter/tags/2.18/debian/preinst.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/preinst.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/preinst.ex (revision 458)
@@ -0,0 +1,38 @@
+#! /bin/sh
+# preinst script for pkpgcounter
+#
+# see: dh_installdeb(1)
+
+set -e
+
+# summary of how this script can be called:
+#        * <new-preinst> `install'
+#        * <new-preinst> `install' <old-version>
+#        * <new-preinst> `upgrade' <old-version>
+#        * <old-preinst> `abort-upgrade' <new-version>
+#
+# for details, see http://www.debian.org/doc/debian-policy/ or
+# the debian-policy package
+
+
+case "$1" in
+    install|upgrade)
+    ;;
+
+    abort-upgrade)
+    ;;
+
+    *)
+        echo "preinst called with unknown argument \`$1'" >&2
+        exit 1
+    ;;
+esac
+
+# dh_installdeb will replace this with shell code automatically
+# generated by other debhelper scripts.
+
+#DEBHELPER#
+
+exit 0
+
+
Index: pkpgcounter/tags/2.18/debian/init.d.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/init.d.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/init.d.ex (revision 458)
@@ -0,0 +1,74 @@
+#! /bin/sh
+#
+# skeleton	example file to build /etc/init.d/ scripts.
+#		This file should be used to construct scripts for /etc/init.d.
+#
+#		Written by Miquel van Smoorenburg <miquels@cistron.nl>.
+#		Modified for Debian 
+#		by Ian Murdock <imurdock@gnu.ai.mit.edu>.
+#
+# Version:	@(#)skeleton  1.9  26-Feb-2001  miquels@cistron.nl
+#
+
+PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
+DAEMON=/usr/sbin/pkpgcounter
+NAME=pkpgcounter
+DESC=pkpgcounter
+
+test -x $DAEMON || exit 0
+
+# Include pkpgcounter defaults if available
+if [ -f /etc/default/pkpgcounter ] ; then
+	. /etc/default/pkpgcounter
+fi
+
+set -e
+
+case "$1" in
+  start)
+	echo -n "Starting $DESC: "
+	start-stop-daemon --start --quiet --pidfile /var/run/$NAME.pid \
+		--exec $DAEMON -- $DAEMON_OPTS
+	echo "$NAME."
+	;;
+  stop)
+	echo -n "Stopping $DESC: "
+	start-stop-daemon --stop --quiet --pidfile /var/run/$NAME.pid \
+		--exec $DAEMON
+	echo "$NAME."
+	;;
+  #reload)
+	#
+	#	If the daemon can reload its config files on the fly
+	#	for example by sending it SIGHUP, do it here.
+	#
+	#	If the daemon responds to changes in its config file
+	#	directly anyway, make this a do-nothing entry.
+	#
+	# echo "Reloading $DESC configuration files."
+	# start-stop-daemon --stop --signal 1 --quiet --pidfile \
+	#	/var/run/$NAME.pid --exec $DAEMON
+  #;;
+  restart|force-reload)
+	#
+	#	If the "reload" option is implemented, move the "force-reload"
+	#	option to the "reload" entry above. If not, "force-reload" is
+	#	just the same as "restart".
+	#
+	echo -n "Restarting $DESC: "
+	start-stop-daemon --stop --quiet --pidfile \
+		/var/run/$NAME.pid --exec $DAEMON
+	sleep 1
+	start-stop-daemon --start --quiet --pidfile \
+		/var/run/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS
+	echo "$NAME."
+	;;
+  *)
+	N=/etc/init.d/$NAME
+	# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
+	echo "Usage: $N {start|stop|restart|force-reload}" >&2
+	exit 1
+	;;
+esac
+
+exit 0
Index: pkpgcounter/tags/2.18/debian/prerm.ex
===================================================================
--- pkpgcounter/tags/2.18/debian/prerm.ex (revision 458)
+++ pkpgcounter/tags/2.18/debian/prerm.ex (revision 458)
@@ -0,0 +1,38 @@
+#! /bin/sh
+# prerm script for pkpgcounter
+#
+# see: dh_installdeb(1)
+
+set -e
+
+# summary of how this script can be called:
+#        * <prerm> `remove'
+#        * <old-prerm> `upgrade' <new-version>
+#        * <new-prerm> `failed-upgrade' <old-version>
+#        * <conflictor's-prerm> `remove' `in-favour' <package> <new-version>
+#        * <deconfigured's-prerm> `deconfigure' `in-favour'
+#          <package-being-installed> <version> `removing'
+#          <conflicting-package> <version>
+# for details, see http://www.debian.org/doc/debian-policy/ or
+# the debian-policy package
+
+
+case "$1" in
+    remove|upgrade|deconfigure)
+        ;;
+    failed-upgrade)
+        ;;
+    *)
+        echo "prerm called with unknown argument \`$1'" >&2
+        exit 1
+    ;;
+esac
+
+# dh_installdeb will replace this with shell code automatically
+# generated by other debhelper scripts.
+
+#DEBHELPER#
+
+exit 0
+
+
Index: pkpgcounter/tags/2.18/debian/dirs
===================================================================
--- pkpgcounter/tags/2.18/debian/dirs (revision 458)
+++ pkpgcounter/tags/2.18/debian/dirs (revision 458)
@@ -0,0 +1,4 @@
+usr/bin
+usr/lib/python2.4/site-packages/pkpgpdls
+usr/share/doc/pkpgcounter
+usr/share/man/man1
Index: pkpgcounter/tags/2.18/debian/manpage.1
===================================================================
--- pkpgcounter/tags/2.18/debian/manpage.1 (revision 459)
+++ pkpgcounter/tags/2.18/debian/manpage.1 (revision 459)
@@ -0,0 +1,88 @@
+.\" DO NOT MODIFY THIS FILE!  It was generated by help2man 1.36.
+.TH PKPGCOUNTER "1" "July 2007" "C@LL - Conseil Internet & Logiciels Libres" "User Commands"
+.SH NAME
+pkpgcounter \- manual page for pkpgcounter 2.18
+.SH DESCRIPTION
+pkpgcounter v2.18 (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet
+.PP
+pkpgcounter is a generic Page Description Language parser.
+.PP
+pkpgcounter parses any number of input files and/or its standard input
+and outputs the number of pages needed to print these documents.
+.PP
+pkpgcounter can also compute the percent of ink coverage in different
+colorspaces for several file formats.
+.PP
+pkpgcounter currently recognizes the following document formats :
+.IP
+* PostScript (both DSC compliant and binary)
+* PDF
+* PCLXL (aka PCL6)
+* PCL3/4/5 (mostly)
+* DVI
+* Plain text
+* TIFF
+* ESC/P2
+* OpenDocument (ISO/IEC DIS 26300)
+* Zenographics ZjStream
+* Samsung QPDL (aka SPL2)
+* Samsung SPL1
+.PP
+The five latter ones, as well as some TIFF documents, are currently
+only supported in page counting mode.
+.PP
+command line usage :
+.IP
+pkpgcounter [options] [files]
+.PP
+options :
+.TP
+\fB\-v\fR | \fB\-\-version\fR
+Prints pkpgcounter's version number then exits.
+.TP
+\fB\-h\fR | \fB\-\-help\fR
+Prints this message then exits.
+.TP
+\fB\-d\fR | \fB\-\-debug\fR
+Activate debug mode.
+.TP
+\fB\-cCOLORSPACE\fR, \fB\-\-colorspace\fR=\fICOLORSPACE\fR
+Activate the computation of ink usage, and defines the
+colorspace to use. Supported values are 'BW' (Black),
+\&'RGB', 'CMYK', 'CMY', and 'GC' (Grayscale vs Color).
+\&'GC' is useful if you only need to differentiate
+grayscale pages from coloured pages but don't care
+about ink usage per se.
+.TP
+\fB\-rRESOLUTION\fR, \fB\-\-resolution\fR=\fIRESOLUTION\fR
+The resolution in DPI to use when checking ink usage.
+Lower resolution is faster but less accurate. Default
+is 72 dpi.
+.PP
+examples :
+.IP
+\f(CW$ pkpgcounter file1.ps file2.escp2 file3.pclxl <file4.pcl345\fR
+.IP
+Will launch pkpgcounter and will output the total number of pages
+needed to print all the documents specified.
+.IP
+\f(CW$ pkpgcounter --colorspace bw --resolution 150 file1.ps\fR
+.IP
+Will output the percent of black ink needed on each page of
+the file1.ps file rendered at 150 dpi.
+.PP
+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 2 of the License, or
+(at your option) any later version.
+.PP
+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.
+.PP
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110\-1301, USA.
+.PP
+Please e\-mail bugs to: alet@librelogiciel.com
Index: pkpgcounter/tags/2.18/debian/copyright
===================================================================
--- pkpgcounter/tags/2.18/debian/copyright (revision 458)
+++ pkpgcounter/tags/2.18/debian/copyright (revision 458)
@@ -0,0 +1,26 @@
+This package was debianized by Jerome Alet <alet@librelogiciel.com> on
+Wed, 25 Jul 2007 11:09:28 +0200.
+
+It was downloaded from http://www.pykota.com/software/pkpgcounter/download/tarballs/pkpgcounter-2.17.tar.gz
+
+Copyright Holder: Jerome Alet - <alet@librelogiciel.com>
+
+License:
+
+   This package 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 of the License, or
+   (at your option) any later version.
+
+   This package 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 this package; if not, write to the Free Software
+   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+
+On Debian systems, the complete text of the GNU General
+Public License can be found in `/usr/share/common-licenses/GPL'.
+
Index: pkpgcounter/tags/2.18/tests/colors.pdf
===================================================================
--- pkpgcounter/tags/2.18/tests/colors.pdf (revision 405)
+++ pkpgcounter/tags/2.18/tests/colors.pdf (revision 405)
@@ -0,0 +1,441 @@
+%PDF-1.3
+%���� ReportLab Generated PDF document http://www.reportlab.com
+% 'BasicFonts': class PDFDictionary 
+1 0 obj
+% The standard fonts dictionary
+<< /F1 2 0 R
+ /F2 3 0 R
+ /F3 13 0 R >>
+endobj
+% 'F1': class PDFType1Font 
+2 0 obj
+% Font Helvetica
+<< /BaseFont /Helvetica
+ /Encoding /WinAnsiEncoding
+ /Name /F1
+ /Subtype /Type1
+ /Type /Font >>
+endobj
+% 'F2': class PDFType1Font 
+3 0 obj
+% Font Courier
+<< /BaseFont /Courier
+ /Encoding /WinAnsiEncoding
+ /Name /F2
+ /Subtype /Type1
+ /Type /Font >>
+endobj
+% 'Page1': class PDFPage 
+4 0 obj
+% Page dictionary
+<< /Contents 18 0 R
+ /MediaBox [ 0
+  0
+  595.2756
+  841.8898 ]
+ /Parent 17 0 R
+ /Resources << /Font 1 0 R
+  /ProcSet [ /PDF
+   /Text
+   /ImageB
+   /ImageC
+   /ImageI ] >>
+ /Rotate 0
+ /Trans <<  >>
+ /Type /Page >>
+endobj
+% 'Page2': class PDFPage 
+5 0 obj
+% Page dictionary
+<< /Contents 19 0 R
+ /MediaBox [ 0
+  0
+  595.2756
+  841.8898 ]
+ /Parent 17 0 R
+ /Resources << /Font 1 0 R
+  /ProcSet [ /PDF
+   /Text
+   /ImageB
+   /ImageC
+   /ImageI ] >>
+ /Rotate 0
+ /Trans <<  >>
+ /Type /Page >>
+endobj
+% 'Page3': class PDFPage 
+6 0 obj
+% Page dictionary
+<< /Contents 20 0 R
+ /MediaBox [ 0
+  0
+  595.2756
+  841.8898 ]
+ /Parent 17 0 R
+ /Resources << /Font 1 0 R
+  /ProcSet [ /PDF
+   /Text
+   /ImageB
+   /ImageC
+   /ImageI ] >>
+ /Rotate 0
+ /Trans <<  >>
+ /Type /Page >>
+endobj
+% 'Page4': class PDFPage 
+7 0 obj
+% Page dictionary
+<< /Contents 21 0 R
+ /MediaBox [ 0
+  0
+  595.2756
+  841.8898 ]
+ /Parent 17 0 R
+ /Resources << /Font 1 0 R
+  /ProcSet [ /PDF
+   /Text
+   /ImageB
+   /ImageC
+   /ImageI ] >>
+ /Rotate 0
+ /Trans <<  >>
+ /Type /Page >>
+endobj
+% 'Page5': class PDFPage 
+8 0 obj
+% Page dictionary
+<< /Contents 22 0 R
+ /MediaBox [ 0
+  0
+  595.2756
+  841.8898 ]
+ /Parent 17 0 R
+ /Resources << /Font 1 0 R
+  /ProcSet [ /PDF
+   /Text
+   /ImageB
+   /ImageC
+   /ImageI ] >>
+ /Rotate 0
+ /Trans <<  >>
+ /Type /Page >>
+endobj
+% 'Page6': class PDFPage 
+9 0 obj
+% Page dictionary
+<< /Contents 23 0 R
+ /MediaBox [ 0
+  0
+  595.2756
+  841.8898 ]
+ /Parent 17 0 R
+ /Resources << /Font 1 0 R
+  /ProcSet [ /PDF
+   /Text
+   /ImageB
+   /ImageC
+   /ImageI ] >>
+ /Rotate 0
+ /Trans <<  >>
+ /Type /Page >>
+endobj
+% 'Page7': class PDFPage 
+10 0 obj
+% Page dictionary
+<< /Contents 24 0 R
+ /MediaBox [ 0
+  0
+  595.2756
+  841.8898 ]
+ /Parent 17 0 R
+ /Resources << /Font 1 0 R
+  /ProcSet [ /PDF
+   /Text
+   /ImageB
+   /ImageC
+   /ImageI ] >>
+ /Rotate 0
+ /Trans <<  >>
+ /Type /Page >>
+endobj
+% 'Page8': class PDFPage 
+11 0 obj
+% Page dictionary
+<< /Contents 25 0 R
+ /MediaBox [ 0
+  0
+  595.2756
+  841.8898 ]
+ /Parent 17 0 R
+ /Resources << /Font 1 0 R
+  /ProcSet [ /PDF
+   /Text
+   /ImageB
+   /ImageC
+   /ImageI ] >>
+ /Rotate 0
+ /Trans <<  >>
+ /Type /Page >>
+endobj
+% 'Page9': class PDFPage 
+12 0 obj
+% Page dictionary
+<< /Contents 26 0 R
+ /MediaBox [ 0
+  0
+  595.2756
+  841.8898 ]
+ /Parent 17 0 R
+ /Resources << /Font 1 0 R
+  /ProcSet [ /PDF
+   /Text
+   /ImageB
+   /ImageC
+   /ImageI ] >>
+ /Rotate 0
+ /Trans <<  >>
+ /Type /Page >>
+endobj
+% 'F3': class PDFType1Font 
+13 0 obj
+% Font Helvetica-Bold
+<< /BaseFont /Helvetica-Bold
+ /Encoding /WinAnsiEncoding
+ /Name /F3
+ /Subtype /Type1
+ /Type /Font >>
+endobj
+% 'Page10': class PDFPage 
+14 0 obj
+% Page dictionary
+<< /Contents 27 0 R
+ /MediaBox [ 0
+  0
+  595.2756
+  841.8898 ]
+ /Parent 17 0 R
+ /Resources << /Font 1 0 R
+  /ProcSet [ /PDF
+   /Text
+   /ImageB
+   /ImageC
+   /ImageI ] >>
+ /Rotate 0
+ /Trans <<  >>
+ /Type /Page >>
+endobj
+% 'R15': class PDFCatalog 
+15 0 obj
+% Document Root
+<< /Outlines 28 0 R
+ /PageMode /UseNone
+ /Pages 17 0 R
+ /Type /Catalog >>
+endobj
+% 'R16': class PDFInfo 
+16 0 obj
+<< /Author (anonymous)
+ /CreationDate (20060911231409)
+ /Producer (ReportLab http://www.reportlab.com)
+ /Subject (unspecified)
+ /Title (untitled) >>
+endobj
+% 'R17': class PDFPages 
+17 0 obj
+% page tree
+<< /Count 10
+ /Kids [ 4 0 R
+  5 0 R
+  6 0 R
+  7 0 R
+  8 0 R
+  9 0 R
+  10 0 R
+  11 0 R
+  12 0 R
+  14 0 R ]
+ /Type /Pages >>
+endobj
+% 'R18': class PDFStream 
+18 0 obj
+% page stream
+<< /Filter [ /ASCII85Decode
+  /FlateDecode ]
+ /Length 923 >>
+stream
+Gat%"D,8n?&H7^.IlJSu_$$IWCK%TS!Y$sed_m=Q,egdKds-#qaDo;tmrq>*
+AF1kUWVYmBchX.o5?@n2I$!c]/`8+0M]2`9Kd6c[4$Fqan3&cokS@G$WETY!
+nR-q?*'reAYo=@4`dpM:0SX*=-V5p?8/80A]J.^Z$CKu*n.ZdLE\KM/SBDOE
+epW#.V:+Lt:/<&/%E[f#6,I:H6n*C/%(r*t`QK^W="5Jd8e)^+7WT'S<+[&K
+3Fl;F?t(GVit$1rboZ\j)>YjBVOUmr1em#o/g];6U\)c&7_IP%L[dXn*sS)^
+$l)27A-=3Ln`gNN_.9*o@YX/W+]Q8u.r,jdZ%ZSYe9B(+/hkYrE;^gjn-uEO
+1m^kVKTpE*-_o':CBT,006RZ@#hfPb9<'^VWUs=tk*/q@M^^DW\Q"R%`hC#*
+d\DBA5MHTdoa>)5Tkj-aiJtF-,oB/</8if)aAXTMN7ZH`O1rRS0<Fr!XQ07#
+IjJn-jumW'*q\sf-+-5j)[_<_quOQ@j4Y@JGXK0CB6`POCMkGS2?Y#7$UED#
+M@VWKN-kJ$/rWdrhd9FrcfnXIESu==c<=`-]W.g-X9[:"KAAWA+%=pX\b4he
+N5@ASe``,BVku7[VA<`[W"H$pJ$qf8`WLKT0h;!hf56raRW=cJTq%H*VWsoK
+L.:EQeK3MT[&rS=&_T<Q0CX_V!EdY#]\UJ'e[j`qZQ"S\m3/Z'U>ZYCL.n:&
+<@)5?IK`t>_;jnt>X(?[cTAX)okfq2*,j+;c>j(Yf<+GBa<tr>$?H?:<lXZZ
+-Io=KkND2a\`[7DCupmq[R5_pgTkHRe.;P4VX<H[b6i@cQri]hkQ-jqMSj0o
+""g`E[DKZfMtShuJ4a^n8MS2hV.P;c/fd%d[Kn/8d\^u.n/#sU91A~>endstream
+
+endobj
+% 'R19': class PDFStream 
+19 0 obj
+% page stream
+<< /Filter [ /ASCII85Decode
+  /FlateDecode ]
+ /Length 108 >>
+stream
+GapQh0E=F,0U\H3i"VoYmq/M+BVZ3&VI4)3B;,ssUYm'-b6:`Tj:5Z7V=S`h
+JQ\k9VKt_oVIg/N-AHg^(7#^C7B$Vh>.e)I]NbGJW"J\~>endstream
+
+endobj
+% 'R20': class PDFStream 
+20 0 obj
+% page stream
+<< /Filter [ /ASCII85Decode
+  /FlateDecode ]
+ /Length 109 >>
+stream
+GapQh0E=F,0U\H3i"VoYmq/M+BVZ3&VI4)3B;,ssUYm'-b6:`Vj:5Z7V=S`h
+JT[AaRd(cYS!kd.Ql,*k=BJ`T'W!9=C%63mn8\O0AY]q2~>endstream
+
+endobj
+% 'R21': class PDFStream 
+21 0 obj
+% page stream
+<< /Filter [ /ASCII85Decode
+  /FlateDecode ]
+ /Length 109 >>
+stream
+GapQh0E=F,0U\H3i"VoYmq/M+BVZ3&VI4)3B;,ssUYm'-b6:`Xj:5Z7V=S`h
+JT[AaRd(cYS!kd.Ql,*k=BJ`T'W!9=C%63mn8\O0AY9Y.~>endstream
+
+endobj
+% 'R22': class PDFStream 
+22 0 obj
+% page stream
+<< /Filter [ /ASCII85Decode
+  /FlateDecode ]
+ /Length 108 >>
+stream
+GapQh0E=F,0U\H3i"VoYmq/M+BVZ3&VI4)3B;,ssUYm'-b6:aOT\tf;B(L')
+JJk>NVKt_oVIg/N-AHg^(7#^C7B$Vh>.e)I]NbGZG7iL~>endstream
+
+endobj
+% 'R23': class PDFStream 
+23 0 obj
+% page stream
+<< /Filter [ /ASCII85Decode
+  /FlateDecode ]
+ /Length 106 >>
+stream
+GapQh0E=F,0U\H3i"VoYmq/M+BVZ3&VI4)3B;,ssUYm'-b6:i)NF6AiEohii
+VO"**7cpR[$5OtCH579^((*L0$;Od;>RJ,K!-N>pf`~>endstream
+
+endobj
+% 'R24': class PDFStream 
+24 0 obj
+% page stream
+<< /Filter [ /ASCII85Decode
+  /FlateDecode ]
+ /Length 107 >>
+stream
+GapQh0E=F,0U\H3i"VoYmq/M+BVZ3&VI4)3B;,ssUYm'-b6:i+NF6AiEohlF
+R9H'E)4?t_.9MrSl<.4k=st)].QD/4E[gKu!<@7\&_R~>endstream
+
+endobj
+% 'R25': class PDFStream 
+25 0 obj
+% page stream
+<< /Filter [ /ASCII85Decode
+  /FlateDecode ]
+ /Length 107 >>
+stream
+GapQh0E=F,0U\H3i"VoYmq/M+BVZ3&VI4)3B;,ssUYm'-b@LZRkD`k]o5`rD
+RAQ:IH:I%oAdT;#L3aUNQ50frW<uC(]NbfV>QAn^&_R~>endstream
+
+endobj
+% 'R26': class PDFStream 
+26 0 obj
+% page stream
+<< /Filter [ /ASCII85Decode
+  /FlateDecode ]
+ /Length 108 >>
+stream
+GapQh0E=F,0U\H3i"VoYmq/M+BVZ3&VI4)3B;,ssUYm'-b@R=HJ_gZE2D8,Q
+Qsj`DWb5j[C8PBI@]3pJ@;2E3PcEZ;`QP*nb67lg&eW^~>endstream
+
+endobj
+% 'R27': class PDFStream 
+27 0 obj
+% page stream
+<< /Filter [ /ASCII85Decode
+  /FlateDecode ]
+ /Length 894 >>
+stream
+Gau0C9lJc?%)!J@J)I0=2@Q$BIJ9,'m@h_"0JMSO-H_dnW<:m\p[dRX7H5dK
+,WVh+":h9K8+P'7_LT':epYlr0Zi7n%0M?H/V+3P+SuJsg%ed[^k&J&_%Q)d
+YW!Y[MGV8#BPRq+PX2a40A$4^DVhl,gq3EnBPP'T$J?NB^?thB0\Z=CngYAO
+(+fXEhAJmRkOk^R^ub/XR$U6EeXLsS^-hMUTR(*N[MuZiMnEq8PQ,gqZ762`
+XHlL\5n4F+#*r9"L6ornJQ3-iXsdY5(Y`@0!d?q@XoHpt;cZWleA0tSG]kt*
+Q0X7L-eAO,jfSWX.D`mdBjNnTg`jspB#bS?ga`!2q<GX9E!__85qJiom%f=8
++Q64=XtE%CAX%u#PVB/:2IW[V%kAKZX[glLX>D!L(t&J>A7;PN*gXjebl(^^
+"$nQeL9\t+'k9W^TkQocWE1V$MFP3.Lm>u`'uXUi?Rt&&;Q<\U?`@^d"&#=O
+B]/dB8J'*me[aR,Bf0U9<_?U^GMN`H-i:n+$T%Z24Ul]gi#,HD:5,$mn*kLV
+3fuj5)Sn1r91%eJXiBLd_P2"N/h&=q7fB*)iA'U>gLC<LfN_<(7Xas3,/RO/
+g"oZl)(5=$&.>ra5@q>_+&&*'kq!*@rHIW-Hh'&dl&]nNp."/,qCJ3HdiiR?
+C"fqVm'@ZkS.8DoZ62W@%-E`"c((6-\KnDP4]).lE^:A6ris&-MGaE+*^bco
+F%N>J2a5F^$)Pu-)/!Yr)+5'$AWY<#Vp&EPh4@#1:psHc?/"XR-:Y7:?hC=m
+ARoQJ6[U_u'IT8Gj/<,E_<;e-NA5;D3E`]9KAfq7D:`@ST'G9,(l(SNQ9$1)
+9i"KSn0bG1h;8Y(BE%uHN0WZ~>endstream
+
+endobj
+% 'R28': class PDFOutlines 
+28 0 obj
+<< /Count 0
+ /Type /Outlines >>
+endobj
+xref
+0 29
+0000000000 65535 f
+0000000113 00000 n
+0000000234 00000 n
+0000000399 00000 n
+0000000558 00000 n
+0000000849 00000 n
+0000001140 00000 n
+0000001431 00000 n
+0000001722 00000 n
+0000002013 00000 n
+0000002304 00000 n
+0000002596 00000 n
+0000002888 00000 n
+0000003182 00000 n
+0000003357 00000 n
+0000003650 00000 n
+0000003788 00000 n
+0000003986 00000 n
+0000004179 00000 n
+0000005247 00000 n
+0000005500 00000 n
+0000005754 00000 n
+0000006008 00000 n
+0000006261 00000 n
+0000006512 00000 n
+0000006764 00000 n
+0000007016 00000 n
+0000007269 00000 n
+0000008310 00000 n
+trailer
+<< /ID 
+  % ReportLab generated PDF document -- digest (http://www.reportlab.com) 
+  [(s\242'\002\325\364\351\177k"\2261\351\326\222G) (s\242'\002\325\364\351\177k"\2261\351\326\222G)] 
+ 
+ /Info 16 0 R
+ /Root 15 0 R
+ /Size 29 >>
+startxref
+8362
+%%EOF
Index: pkpgcounter/tags/2.18/tests/README
===================================================================
--- pkpgcounter/tags/2.18/tests/README (revision 443)
+++ pkpgcounter/tags/2.18/tests/README (revision 443)
@@ -0,0 +1,40 @@
+# $Id$
+
+pkpgcounter : a generic Page Description Language parser
+
+(c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+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 2 of the License, 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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+====================================================================
+
+This directory contains a gzipped PostScript file, master.ps.gz, 
+obtained by printing to a file a part of the SlashDot.org website 
+from the Galeon web browser on July 2nd 2004. 
+
+When uncompressed, this 16 pages file can be used to test the 
+accuracy of the generic Page Description Language analyzer included 
+in pkpgcounter for different conversion outputs of gs. 
+
+To see if it works, simply launch :
+
+        $ ./runtests.sh
+        
+It should report 16 pages for each document. If it doesn't then 
+there's a bug in the generic Page Description Language analyzer. 
+Please report this to : alet@librelogiciel.com
+
+This script will also launch the test for the computation of
+ink coverage. Look at the file colors.pdf to see what the 
+results should look like.
Index: pkpgcounter/tags/2.18/tests/runcolors.py
===================================================================
--- pkpgcounter/tags/2.18/tests/runcolors.py (revision 443)
+++ pkpgcounter/tags/2.18/tests/runcolors.py (revision 443)
@@ -0,0 +1,164 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+#
+
+"""This document was created with the help of the ReportLab
+ToolKit (tm) available as Free Software from :
+
+        http://www.reportlab.org
+
+It contains 10 pages, including this one.
+
+Each page after this one is entirely filled with 100%
+of a particular color, as described below :
+
+Page  1 ====> This notice
+Page  2 ====> Red
+Page  3 ====> Green
+Page  4 ====> Blue
+Page  5 ====> Cyan
+Page  6 ====> Magenta
+Page  7 ====> Yellow
+Page  8 ====> Black
+Page  9 ====> White
+Page 10 ====> The expected results.
+
+This document helps to ensure that the computation of
+ink coverage made by pkpgcounter works as expected.
+
+To check by yourself :
+
+  $ for cspace in BW RGB CMY CMYK ; do
+        echo "Colorspace : $cspace" ;
+        pkpgcounter --colorspace $cspace colors.pdf ;
+        echo ;
+    done    
+
+Please report any problem to : alet@librelogiciel.com
+"""
+
+lastpage = """For each colorspace, the results for the last page will differ a bit from what is below.
+The important values are the one for pages 2 to 9 included.
+
+Colorspace : BW
+B :   2.355336%
+B :  70.196078%
+B :  41.568627%
+B :  88.627451%
+B :  30.196078%
+B :  58.823529%
+B :  11.764706%
+B : 100.000000%
+B :   0.000000%
+B :   3.500669%
+
+Colorspace : RGB
+R :  97.644664%      G :  97.644664%      B :  97.644664%
+R : 100.000000%      G :   0.000000%      B :   0.000000%
+R :   0.000000%      G : 100.000000%      B :   0.000000%
+R :   0.000000%      G :   0.000000%      B : 100.000000%
+R :   0.000000%      G : 100.000000%      B : 100.000000%
+R : 100.000000%      G :   0.000000%      B : 100.000000%
+R : 100.000000%      G : 100.000000%      B :   0.000000%
+R :   0.000000%      G :   0.000000%      B :   0.000000%
+R : 100.000000%      G : 100.000000%      B : 100.000000%
+R :  96.499331%      G :  96.499331%      B :  96.499331%
+
+Colorspace : CMY
+C :   2.355336%      M :   2.355336%      Y :   2.355336%
+C :   0.000000%      M : 100.000000%      Y : 100.000000%
+C : 100.000000%      M :   0.000000%      Y : 100.000000%
+C : 100.000000%      M : 100.000000%      Y :   0.000000%
+C : 100.000000%      M :   0.000000%      Y :   0.000000%
+C :   0.000000%      M : 100.000000%      Y :   0.000000%
+C :   0.000000%      M :   0.000000%      Y : 100.000000%
+C : 100.000000%      M : 100.000000%      Y : 100.000000%
+C :   0.000000%      M :   0.000000%      Y :   0.000000%
+C :   3.500669%      M :   3.500669%      Y :   3.500669%
+
+Colorspace : CMYK
+C :   0.000000%      M :   0.000000%      Y :   0.000000%      K :   2.355336%
+C :   0.000000%      M : 100.000000%      Y : 100.000000%      K :   0.000000%
+C : 100.000000%      M :   0.000000%      Y : 100.000000%      K :   0.000000%
+C : 100.000000%      M : 100.000000%      Y :   0.000000%      K :   0.000000%
+C : 100.000000%      M :   0.000000%      Y :   0.000000%      K :   0.000000%
+C :   0.000000%      M : 100.000000%      Y :   0.000000%      K :   0.000000%
+C :   0.000000%      M :   0.000000%      Y : 100.000000%      K :   0.000000%
+C :   0.000000%      M :   0.000000%      Y :   0.000000%      K : 100.000000%
+C :   0.000000%      M :   0.000000%      Y :   0.000000%      K :   0.000000%
+C :   0.000000%      M :   0.000000%      Y :   0.000000%      K :   3.500669%
+"""
+
+import sys
+try :
+    from reportlab.lib import colors
+    from reportlab.lib import pagesizes
+    from reportlab.lib.units import cm
+    from reportlab.pdfgen import canvas
+except ImportError :    
+    sys.stderr.write("Please download and install ReportLab\n\tfrom http://www.reportlab.org\n")
+    sys.exit(-1)
+
+if __name__ == "__main__" :
+    canv = canvas.Canvas("colors.pdf", pagesize=pagesizes.A4)
+    (width, height) = pagesizes.A4
+    xbase = 2*cm
+    ybase = height - 2*cm
+    
+    # First we output the explanations on the first page.
+    canv.setFont("Courier", 14)
+    for line in __doc__.split("\n") :
+        canv.drawString(xbase, ybase, line)
+        ybase -= 18
+    canv.showPage()
+    
+    # Then we output each page
+    for color in (colors.Color(1, 0, 0),        # Red
+                  colors.Color(0, 1, 0),        # Green
+                  colors.Color(0, 0, 1)) :      # Blue
+        canv.setStrokeColorRGB(*color.rgb())          
+        canv.setFillColorRGB(*color.rgb())          
+        canv.rect(0, 0, width, height, fill=1)
+        canv.showPage()
+        
+    for color in (colors.CMYKColor(1, 0, 0, 0), # Cyan
+                  colors.CMYKColor(0, 1, 0, 0), # Magenta
+                  colors.CMYKColor(0, 0, 1, 0), # Yellow
+                  colors.CMYKColor(0, 0, 0, 1), # Black
+                  colors.CMYKColor(0, 0, 0, 0)) : # White
+        canv.setStrokeColorCMYK(*color.cmyk())          
+        canv.setFillColorCMYK(*color.cmyk())          
+        canv.rect(0, 0, width, height, fill=1)
+        canv.showPage()
+        
+    # Finally outputs the expected results.
+    canv.setFont("Helvetica-Bold", 16)
+    canv.drawCentredString(width/2.0, height-1.5*cm, "Expected Results :")
+    ybase = height - 3*cm
+    canv.setFont("Courier", 10)
+    for line in lastpage.split("\n") :
+        canv.drawString(xbase, ybase, line)
+        ybase -= 14
+    canv.showPage()
+        
+    canv.save()        
Index: pkpgcounter/tags/2.18/tests/runtest.sh
===================================================================
--- pkpgcounter/tags/2.18/tests/runtest.sh (revision 382)
+++ pkpgcounter/tags/2.18/tests/runtest.sh (revision 382)
@@ -0,0 +1,30 @@
+#! /bin/sh
+
+echo -n "Generating testsuite..."
+gunzip <master.ps.gz >master2.ps
+for device in cups lj250 lj4dithp ljet2p ljet4pjl ljetplus laserjet ljet3 ljet4 lj5gray lj5mono pxlmono pxlcolor pdfwrite pswrite psgray psmono psrgb epson epsonc eps9mid eps9high stcolor st800 escp escpc pcl3 cdeskjet cdj1600 cdj500 cdj550 cdj670 cdj850 cdj880 cdj890 cdj970 cdjcolor cdjmono dj505j djet500 djet500c hpdj1120c hpdj310 hpdj320 hpdj340 hpdj400 hpdj500 hpdj500c hpdj510 hpdj520 hpdj540 hpdj550c hpdj560c hpdj600 hpdj660c hpdj670c hpdj680c hpdj690c hpdj850c hpdj855c hpdj870c hpdj890c hpdjplus hpdjportable tiff12nc tiff24nc tiffcrle tiffg3 tiffg32d tiffg4 tifflzw tiffpack ; do
+    if ! [ -f "testsuite.$device" ]  ; then
+        gs -dQUIET -dBATCH -dNOPAUSE -sOutputFile="testsuite.$device" -sDEVICE="$device" master2.ps ; 
+    fi ;
+    done
+    
+if ! [ -f "colors.pdf" ]  ; then
+   python ./runcolors.py ; 
+fi ;
+echo 
+
+echo -n "File master.ps should be 16 pages long, result is : "
+python ../pkpgpdls/analyzer.py master2.ps
+
+echo "Analyzing testsuite..."
+for file in testsuite.* ; do
+    echo -n "$file ===> " && python ../pkpgpdls/analyzer.py "$file" ;
+done    
+echo
+
+echo "Analyzing colors..."
+for cspace in BW RGB CMY CMYK ; do
+    echo "Colorspace : $cspace" ;
+    python ../pkpgpdls/analyzer.py --colorspace $cspace colors.pdf ;
+    echo ;
+done    
Index: pkpgcounter/tags/2.18/pkpgpdls/tiff.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/tiff.py (revision 443)
+++ pkpgcounter/tags/2.18/pkpgpdls/tiff.py (revision 443)
@@ -0,0 +1,82 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a page counter for TIFF documents."""
+
+import sys
+import os
+import mmap
+from struct import unpack
+
+import pdlparser
+
+class Parser(pdlparser.PDLParser) :
+    """A parser for TIFF documents."""
+    totiffcommands = [ "cat >%(fname)s" ]
+    def isValid(self) :        
+        """Returns True if data is TIFF, else False."""
+        littleendian = (chr(0x49)*2) + chr(0x2a) + chr(0)
+        bigendian = (chr(0x4d)*2) + chr(0) + chr(0x2a)
+        if self.firstblock[:4] in (littleendian, bigendian) :
+            self.logdebug("DEBUG: Input file is in the TIFF format.")
+            return True
+        else :    
+            return False
+    
+    def getJobSize(self) :
+        """Counts pages in a TIFF document.
+        
+           Algorithm by Jerome Alet.
+           
+           The documentation used for this was :
+           
+           http://www.ee.cooper.edu/courses/course_pages/past_courses/EE458/TIFF/
+        """
+        infileno = self.infile.fileno()
+        minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
+        pagecount = 0
+        littleendian = (chr(0x49)*2) + chr(0x2a) + chr(0)
+        bigendian = (chr(0x4d)*2) + chr(0) + chr(0x2a)
+        if minfile[:4] == littleendian :
+            integerbyteorder = "<I"
+            shortbyteorder = "<H"
+        elif minfile[:4] == bigendian :
+            integerbyteorder = ">I"
+            shortbyteorder = ">H"
+        else :    
+            raise pdlparser.PDLParserError, "Unknown file endianness."
+        pos = 4    
+        try :    
+            nextifdoffset = unpack(integerbyteorder, minfile[pos : pos + 4])[0]
+            while nextifdoffset :
+                direntrycount = unpack(shortbyteorder, minfile[nextifdoffset : nextifdoffset + 2])[0]
+                pos = nextifdoffset + 2 + (direntrycount * 12)
+                nextifdoffset = unpack(integerbyteorder, minfile[pos : pos + 4])[0]
+                pagecount += 1
+        except IndexError :            
+            pass
+        minfile.close()
+        return pagecount
+        
+if __name__ == "__main__" :    
+    pdlparser.test(Parser)
Index: pkpgcounter/tags/2.18/pkpgpdls/pdlparser.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/pdlparser.py (revision 450)
+++ pkpgcounter/tags/2.18/pkpgpdls/pdlparser.py (revision 450)
@@ -0,0 +1,153 @@
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This module defines the base class for all Page Description Language parsers."""
+
+import sys
+import os
+import popen2
+
+KILOBYTE = 1024    
+MEGABYTE = 1024 * KILOBYTE    
+FIRSTBLOCKSIZE = 16 * KILOBYTE
+LASTBLOCKSIZE = int(KILOBYTE / 4)
+
+class PDLParserError(Exception):
+    """An exception for PDLParser related stuff."""
+    def __init__(self, message = ""):
+        self.message = message
+        Exception.__init__(self, message)
+    def __repr__(self):
+        return self.message
+    __str__ = __repr__
+        
+class PDLParser :
+    """Generic PDL parser."""
+    totiffcommands = None        # Default command to convert to TIFF
+    def __init__(self, infile, debug=0, firstblock=None, lastblock=None) :
+        """Initialize the generic parser."""
+        self.infile = infile
+        self.debug = debug
+        if firstblock is None :
+            self.infile.seek(0)
+            firstblock = self.infile.read(FIRSTBLOCKSIZE)
+            try :
+                self.infile.seek(-LASTBLOCKSIZE, 2)
+                lastblock = self.infile.read(LASTBLOCKSIZE)
+            except IOError :    
+                lastblock = ""
+            self.infile.seek(0)
+        self.firstblock = firstblock
+        self.lastblock = lastblock
+        if not self.isValid() :
+            raise PDLParserError, "Invalid file format !"
+        try :
+            import psyco 
+        except ImportError :    
+            pass # Psyco is not installed
+        else :    
+            # Psyco is installed, tell it to compile
+            # the CPU intensive methods : PCL and PCLXL
+            # parsing will greatly benefit from this.
+            psyco.bind(self.getJobSize)
+            
+    def logdebug(self, message) :       
+        """Logs a debug message if needed."""
+        if self.debug :
+            sys.stderr.write("%s\n" % message)
+            
+    def isValid(self) :    
+        """Returns True if data is in the expected format, else False."""
+        raise RuntimeError, "Not implemented !"
+        
+    def getJobSize(self) :    
+        """Counts pages in a document."""
+        raise RuntimeError, "Not implemented !"
+        
+    def convertToTiffMultiPage24NC(self, fname, dpi) :
+        """Converts the input file to TIFF format, X dpi, 24 bits per pixel, uncompressed.
+           Writes TIFF datas to the file named by fname.
+        """   
+        if self.totiffcommands :
+            for totiffcommand in self.totiffcommands :
+                self.infile.seek(0)
+                error = False
+                commandline = totiffcommand % locals()
+                child = popen2.Popen4(commandline)
+                try :
+                    try :
+                        data = self.infile.read(MEGABYTE)    
+                        while data :
+                            child.tochild.write(data)
+                            child.tochild.flush()
+                            data = self.infile.read(MEGABYTE)
+                    except (IOError, OSError) :    
+                        error = True
+                finally :    
+                    child.tochild.close()    
+                    dummy = child.fromchild.read()
+                    child.fromchild.close()
+                    
+                try :
+                    status = child.wait()
+                except OSError :    
+                    error = True
+                else :    
+                    if os.WIFEXITED(status) :
+                        if os.WEXITSTATUS(status) :
+                            error = True
+                    else :        
+                        error = True
+                    
+                if not os.path.exists(fname) :
+                    error = True
+                elif not os.stat(fname).st_size :
+                    error = True
+                else :        
+                    break       # Conversion worked fine it seems.
+                self.logdebug("Command failed : %s" % repr(commandline))
+            if error :
+                raise PDLParserError, "Problem during conversion to TIFF."
+        else :        
+            raise PDLParserError, "Impossible to compute ink coverage for this file format."
+            
+def test(parserclass) :        
+    """Test function."""
+    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
+        sys.argv.append("-")
+    totalsize = 0    
+    for arg in sys.argv[1:] :
+        if arg == "-" :
+            infile = sys.stdin
+            mustclose = 0
+        else :    
+            infile = open(arg, "rbU")
+            mustclose = 1
+        try :
+            parser = parserclass(infile, debug=1)
+            totalsize += parser.getJobSize()
+        except PDLParserError, msg :    
+            sys.stderr.write("ERROR: %s\n" % msg)
+            sys.stderr.flush()
+        if mustclose :    
+            infile.close()
+    print "%s" % totalsize
+    
Index: pkpgcounter/tags/2.18/pkpgpdls/ooo.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/ooo.py (revision 443)
+++ pkpgcounter/tags/2.18/pkpgpdls/ooo.py (revision 443)
@@ -0,0 +1,67 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a page counter for OpenDocument documents."""
+
+import sys
+import zipfile
+
+import pdlparser
+
+class Parser(pdlparser.PDLParser) :
+    """A parser for OpenOffice.org documents."""
+    def isValid(self) :        
+        """Returns True if data is OpenDocument, else False."""
+        if self.firstblock[:2] == "PK" :
+            try :
+                self.archive = zipfile.ZipFile(self.infile)
+                self.contentxml = self.archive.read("content.xml")
+                self.metaxml = self.archive.read("meta.xml")
+            except :    
+                return False
+            else :
+                self.logdebug("DEBUG: Input file is in the OpenDocument (ISO/IEC DIS 26300) format.")
+                return True
+        else :    
+            return False
+            
+    def getJobSize(self) :
+        """Counts pages in an OpenOffice.org document.
+        
+           Algorithm by Jerome Alet.
+        """
+        pagecount = 0
+        try :
+            # First try with Text documents
+            index = self.metaxml.index("meta:page-count=")
+            pagecount = int(self.metaxml[index:].split('"')[1])
+        except :
+            # Now try with Impress documents
+            pagecount = self.contentxml.count("<draw:page ")
+            if not pagecount :
+                # Probably a Spreadsheet document
+                raise pdlparser.PDLParserError, "OpenOffice.org's spreadsheet documents are not yet supported."
+        return pagecount
+        
+if __name__ == "__main__" :    
+    pdlparser.test(Parser)
Index: pkpgcounter/tags/2.18/pkpgpdls/inkcoverage.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/inkcoverage.py (revision 443)
+++ pkpgcounter/tags/2.18/pkpgpdls/inkcoverage.py (revision 443)
@@ -0,0 +1,130 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements the computation of ink coverage in different colorspaces."""
+
+import sys
+
+from PIL import Image
+
+import pdlparser
+
+def getPercent(img, nbpix) :
+    """Extracts the percents per color component from a picture.
+      
+       Faster without Psyco on my own machine.
+    """
+    result = {}     
+    bands = img.split()
+    for (i, bandname) in enumerate(img.getbands()) :
+        result[bandname] = 100.0 * (reduce(lambda current, next: current + (next[1] * next[0]), enumerate(bands[i].histogram()), 0) / 255.0) / nbpix
+    return result    
+    
+def getPercentCMYK(img, nbpix) :
+    """Extracts the percents of Cyan, Magenta, Yellow, and Black from a picture.
+     
+       PIL doesn't produce useable CMYK for our algorithm, so we use the algorithm from PrintBill.
+       Psyco speeds this function up by around 2.5 times on my computer.
+    """
+    if img.mode != "RGB" :
+        img = img.convert("RGB")
+    cyan = magenta = yellow = black = 0    
+    for (r, g, b) in img.getdata() :
+        if r == g == b :
+            black += 255 - r
+        else :    
+            cyan += 255 - r
+            magenta += 255 - g
+            yellow += 255 - b
+    return { "C" : 100.0 * (cyan / 255.0) / nbpix,
+             "M" : 100.0 * (magenta / 255.0) / nbpix,
+             "Y" : 100.0 * (yellow / 255.0) / nbpix,
+             "K" : 100.0 * (black / 255.0) / nbpix,
+           }
+        
+def getPercentGC(img, nbpix) :        
+    """Determines if a page is in grayscale or colour mode."""
+    if img.mode != "RGB" :
+        img = img.convert("RGB")
+    gray = 0
+    for (r, g, b) in img.getdata() :
+        if not (r == g == b) :
+            # optimize : if a single pixel is no gray the whole page is colored.
+            return { "G" : 0.0, "C" : 100.0 }
+    return { "G" : 100.0, "C" : 0.0 }
+    
+def getPercentBW(img, nbpix) :
+    """Extracts the percents of Black from a picture, once converted to gray levels."""
+    if img.mode != "L" :
+        img = img.convert("L")
+    return { "B" : 100.0 - getPercent(img, nbpix)["L"] }
+    
+def getPercentRGB(img, nbpix) :
+    """Extracts the percents of Red, Green, Blue from a picture, once converted to RGB."""
+    if img.mode != "RGB" :
+        img = img.convert("RGB")
+    return getPercent(img, nbpix)    
+    
+def getPercentCMY(img, nbpix) :
+    """Extracts the percents of Cyan, Magenta, and Yellow from a picture once converted to RGB."""
+    result = getPercentRGB(img, nbpix)
+    return { "C" : 100.0 - result["R"],
+             "M" : 100.0 - result["G"],
+             "Y" : 100.0 - result["B"],
+           }
+    
+def getInkCoverage(fname, colorspace) :
+    """Returns a list of dictionnaries containing for each page, 
+       for each color component, the percent of ink coverage on 
+       that particular page.
+    """
+    result = []
+    colorspace = colorspace.upper()
+    computation = globals()["getPercent%s" % colorspace]
+    if colorspace in ("CMYK", "GC") : # faster with psyco on my machine
+        try :
+            import psyco
+        except ImportError :    
+            pass
+        else :    
+            psyco.bind(getPercentCMYK)
+    
+    index = 0
+    try :
+        image = Image.open(fname)
+    except IOError, msg :   
+        raise pdlparser.PDLParserError, "%s (%s)" % (msg, fname)
+    else :    
+        try :
+            while 1 :
+                nbpixels = image.size[0] * image.size[1]
+                result.append(computation(image, nbpixels))
+                index += 1              
+                image.seek(index)
+        except EOFError :        
+            pass
+        return (colorspace, result)
+
+if __name__ == "__main__" :
+    # NB : length of result gives number of pages !
+    print getInkCoverage(sys.argv[1], "CMYK")
Index: pkpgcounter/tags/2.18/pkpgpdls/__init__.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/__init__.py (revision 443)
+++ pkpgcounter/tags/2.18/pkpgpdls/__init__.py (revision 443)
@@ -0,0 +1,20 @@
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
Index: pkpgcounter/tags/2.18/pkpgpdls/zjstream.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/zjstream.py (revision 443)
+++ pkpgcounter/tags/2.18/pkpgpdls/zjstream.py (revision 443)
@@ -0,0 +1,107 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a page counter for ZjStream documents."""
+
+import sys
+import os
+import mmap
+from struct import unpack
+
+import pdlparser
+
+class Parser(pdlparser.PDLParser) :
+    """A parser for ZjStream documents."""
+    def isValid(self) :    
+        """Returns True if data is ZjStream, else False."""
+        if self.firstblock[:4] == "ZJZJ" :
+            self.logdebug("DEBUG: Input file is in the Zenographics ZjStream (little endian) format.")
+            self.littleEndian()
+            return True
+        elif self.firstblock[:4] == "JZJZ" :    
+            self.logdebug("DEBUG: Input file is in the Zenographics ZjStream (big endian) format.")
+            self.bigEndian()
+            return True
+        else :    
+            return False
+        
+    def littleEndian(self) :
+        """Toggles to little endianness."""
+        self.unpackType = { 1 : "B", 2 : "<H", 4 : "<I" }
+        self.unpackShort = self.unpackType[2]
+        self.unpackLong = self.unpackType[4]
+        return 0
+        
+    def bigEndian(self) :
+        """Toggles to big endianness."""
+        self.unpackType = { 1 : "B", 2 : ">H", 4 : ">I" }
+        self.unpackShort = self.unpackType[2]
+        self.unpackLong = self.unpackType[4]
+        return 0
+        
+    def getJobSize(self) :
+        """Computes the number of pages in a ZjStream document."""
+        infileno = self.infile.fileno()
+        minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
+        pos = 4
+        startpagecount = endpagecount = 0
+        try :
+            try :
+                while 1 :
+                    header = minfile[pos:pos+16]
+                    if len(header) != 16 :
+                        break
+                    totalChunkSize = unpack(self.unpackLong, header[:4])[0]
+                    chunkType = unpack(self.unpackLong, header[4:8])[0]
+                    numberOfItems = unpack(self.unpackLong, header[8:12])[0]
+                    reserved = unpack(self.unpackShort, header[12:14])[0]
+                    signature = unpack(self.unpackShort, header[14:])[0]
+                    pos += totalChunkSize
+                    if chunkType == 0 :
+                        self.logdebug("startDoc")
+                    elif chunkType == 1 :    
+                        self.logdebug("endDoc")
+                    elif chunkType == 2 :    
+                        self.logdebug("startPage")
+                        startpagecount += 1
+                    elif chunkType == 3 :
+                        self.logdebug("endPage")
+                        endpagecount += 1
+                        
+                    #self.logdebug("Chunk size : %s" % totalChunkSize)
+                    #self.logdebug("Chunk type : 0x%08x" % chunkType)
+                    #self.logdebug("# items : %s" % numberOfItems)
+                    #self.logdebug("reserved : 0x%04x" % reserved)
+                    #self.logdebug("signature : 0x%04x" % signature)
+                    #self.logdebug("\n")
+            except IndexError : # EOF ?
+                pass 
+        finally :        
+            minfile.close()
+            
+        if startpagecount != endpagecount :    
+            sys.stderr.write("ERROR: Incorrect ZjStream datas.\n")
+        return max(startpagecount, endpagecount)
+        
+if __name__ == "__main__" :    
+    pdlparser.test(Parser)
Index: pkpgcounter/tags/2.18/pkpgpdls/qpdl.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/qpdl.py (revision 456)
+++ pkpgcounter/tags/2.18/pkpgpdls/qpdl.py (revision 456)
@@ -0,0 +1,297 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a page counter for QPDL (aka SPL2) documents."""
+
+import sys
+import os
+import mmap
+from struct import unpack
+
+import pdlparser
+import pjl
+
+class Parser(pdlparser.PDLParser) :
+    """A parser for QPDL (aka SPL2) documents."""
+    mediasizes = { 
+                    # The first values are identical to that of PCLXL
+                    0 : "Letter",
+                    1 : "Legal",
+                    2 : "A4",
+                    3 : "Executive",
+                    4 : "Ledger",
+                    5 : "A3",
+                    6 : "COM10Envelope",
+                    7 : "MonarchEnvelope",
+                    8 : "C5Envelope",
+                    9 : "DLEnvelope",
+                    10 : "JB4",
+                    11 : "JB5",
+                    12 : "B5Envelope",
+                    12 : "B5",
+                    14 : "JPostcard",
+                    15 : "JDoublePostcard",
+                    16 : "A5",
+                    17 : "A6",
+                    18 : "JB6",
+                    21 : "Custom",
+                    23 : "C6",
+                    24 : "Folio",
+                 }   
+                 
+    mediasources = {             
+                     # Again, values are identical to that of PCLXL
+                     0 : "Default",
+                     1 : "Auto",
+                     2 : "Manual",
+                     3 : "MultiPurpose",
+                     4 : "UpperCassette",
+                     5 : "LowerCassette",
+                     6 : "EnvelopeTray",
+                     7 : "ThirdCassette",
+                   }
+            
+    def isValid(self) :    
+        """Returns True if data is QPDL aka SPL2, else False."""
+        if ((self.firstblock[:128].find("\033%-12345X") != -1) and \
+             ((self.firstblock.find("LANGUAGE=QPDL") != -1) or \
+              (self.firstblock.find("LANGUAGE = QPDL") != -1))) :
+            self.logdebug("DEBUG: Input file is in the QPDL (aka SPL2) format.")
+            return True
+        else :    
+            return False
+            
+    def beginPage(self, nextpos) :
+        """Indicates the beginning of a new page, and extracts media information."""
+        self.pagecount += 1
+        
+        copies = unpack(self.unpackShort, self.minfile[nextpos+1:nextpos+3])[0]
+        mediasize = ord(self.minfile[nextpos+3])
+        mediasource = ord(self.minfile[nextpos+8])
+        duplexmode = unpack(self.unpackShort, self.minfile[nextpos+10:nextpos+12])[0]
+        
+        self.pages[self.pagecount] = { "copies" : copies, 
+                                       "mediasize" : self.mediasizes.get(mediasize, str(mediasize)),
+                                       "mediasource" : self.mediasources.get(mediasource, str(mediasource)),
+                                       "duplex" : duplexmode,
+                                     } 
+        return 16       # Length of a page header
+        
+    def endPage(self, nextpos) :    
+        """Indicates the end of a page."""
+        epcopies = unpack(self.unpackShort, self.minfile[nextpos:nextpos+2])[0]
+        bpcopies = self.pages[self.pagecount]["copies"]
+        if epcopies != bpcopies :
+            self.logdebug("ERROR: discrepancy between beginPage (%i) and endPage (%i) copies" % (bpcopies, epcopies))
+        return 2        # Length of a page footer
+        
+    def beginBand(self, nextpos) :
+        """Indicates the beginning of a new band."""
+        bandlength = unpack(self.unpackLong, self.minfile[nextpos+6:nextpos+10])[0]
+        return bandlength + 10 # Length of a band header - length of checksum
+        
+    def littleEndian(self) :
+        """Toggles to little endianness."""
+        self.unpackType = { 1 : "B", 2 : "<H", 4 : "<I" }
+        self.unpackShort = self.unpackType[2]
+        self.unpackLong = self.unpackType[4]
+        return 0
+        
+    def bigEndian(self) :
+        """Toggles to big endianness."""
+        self.unpackType = { 1 : "B", 2 : ">H", 4 : ">I" }
+        self.unpackShort = self.unpackType[2]
+        self.unpackLong = self.unpackType[4]
+        return 0
+    
+    def escape(self, nextpos) :    
+        """Handles the ESC code."""
+        pos = endpos = nextpos
+        minfile = self.minfile
+        if minfile[pos : pos+8] == r"%-12345X" :
+            endpos = pos + 9
+            endmark = chr(0x0c) + chr(0x00) + chr(0x1b)
+            asciilimit = chr(0x80)
+            quotes = 0
+            while (minfile[endpos] not in endmark) and \
+                   ((minfile[endpos] < asciilimit) or (quotes % 2)) :
+                if minfile[endpos] == '"' :
+                    quotes += 1
+                endpos += 1
+                
+            # Store this in a per page mapping.    
+            # NB : First time will be at page 0 (i.e. **before** page 1) !
+            stuff = self.escapedStuff.setdefault(self.pagecount, [])
+            stuff.append(minfile[pos : endpos])
+            self.logdebug("Escaped datas : [%s]" % repr(minfile[pos : endpos]))
+        return endpos - pos
+        
+    def maybeEOF(self, nextpos) :    
+        """Tries to detect the EOF marker."""
+        if self.minfile[nextpos:nextpos+9] == self.eofmarker :
+            return 9
+        else :    
+            return 0
+        
+    def getJobSize(self) :
+        """Counts pages in a QPDL (SPL2) document.
+        
+           Algorithm by Jerome Alet.
+           
+           The documentation used for this was :
+         
+           Sp�fication Technique (documentation non officielle)
+           Le Language SPL2
+           par Aur�en Croc
+           http://splix.ap2c.org
+        """
+        # Initialize table of tags
+        self.tags = [ lambda pos : 0 ] * 256    
+        self.tags[0x00] = self.beginPage
+        self.tags[0x01] = self.endPage
+        self.tags[0x09] = self.maybeEOF
+        self.tags[0x0c] = self.beginBand
+        self.tags[0x1b] = self.escape # The escape code
+        
+        self.eofmarker = "\033%-12345X"
+        
+        infileno = self.infile.fileno()
+        self.pages = { 0 : { "copies" : 1, 
+                             "orientation" : "Default", 
+                             "mediatype" : "Plain", 
+                             "mediasize" : "Default", 
+                             "mediasource" : "Default", 
+                             "duplex" : None,
+                           } 
+                     }      
+        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
+        self.pagecount = 0
+        self.escapedStuff = {}   # For escaped datas, mostly PJL commands
+        self.bigEndian()
+        pos = 0
+        tags = self.tags
+        try :
+            try :
+                while 1 :
+                    tag = ord(minfile[pos])
+                    pos += 1
+                    pos += tags[tag](pos)
+            except IndexError : # EOF ?            
+                pass
+        finally :
+            self.minfile.close()
+            
+        defaultduplexmode = "Simplex"
+        defaultpapersize = ""
+        defaultpjlcopies = 1    
+        oldpjlcopies = -1
+        oldduplexmode = ""
+        oldpapersize = ""
+        for pnum in range(1, self.pagecount + 1) :
+            # NB : is number of copies is 0, the page won't be output
+            # but the formula below is still correct : we want 
+            # to decrease the total number of pages in this case.
+            page = self.pages.get(pnum, self.pages.get(1, { "copies" : 1, "mediasize" : "Default", "duplex" : None }))
+            pjlstuff = self.escapedStuff.get(pnum, self.escapedStuff.get(0, []))
+            if pjlstuff :
+                pjlparser = pjl.PJLParser("".join(pjlstuff))
+                nbdefaultcopies = int(pjlparser.default_variables.get("COPIES", -1))
+                nbcopies = int(pjlparser.environment_variables.get("COPIES", -1))
+                nbdefaultqty = int(pjlparser.default_variables.get("QTY", -1))
+                nbqty = int(pjlparser.environment_variables.get("QTY", -1))
+                if nbdefaultcopies > -1 :
+                    defaultpjlcopies = nbdefaultcopies
+                if nbdefaultqty > -1 :
+                    defaultpjlcopies = nbdefaultqty
+                if nbcopies > -1 :
+                    pjlcopies = nbcopies
+                elif nbqty > -1 :
+                    pjlcopies = nbqty
+                else :
+                    if oldpjlcopies == -1 :    
+                        pjlcopies = defaultpjlcopies
+                    else :    
+                        pjlcopies = oldpjlcopies    
+                if page["duplex"] :        
+                    duplexmode = page["duplex"]
+                else :    
+                    defaultdm = pjlparser.default_variables.get("DUPLEX", "")
+                    if defaultdm :
+                        if defaultdm.upper() == "ON" :
+                            defaultduplexmode = "Duplex"
+                        else :    
+                            defaultduplexmode = "Simplex"
+                    envdm = pjlparser.environment_variables.get("DUPLEX", "")
+                    if envdm :
+                        if envdm.upper() == "ON" :
+                            duplexmode = "Duplex"
+                        else :    
+                            duplexmode = "Simplex"
+                    else :        
+                        if not oldduplexmode :
+                            duplexmode = defaultduplexmode
+                        else :    
+                            duplexmode = oldduplexmode
+                defaultps = pjlparser.default_variables.get("PAPER", "")
+                if defaultps :
+                    defaultpapersize = defaultps
+                envps = pjlparser.environment_variables.get("PAPER", "")
+                if envps :
+                    papersize = envps
+                else :    
+                    if not oldpapersize :
+                        papersize = defaultpapersize
+                    else :    
+                        papersize = oldpapersize
+            else :        
+                if oldpjlcopies == -1 :
+                    pjlcopies = defaultpjlcopies
+                else :    
+                    pjlcopies = oldpjlcopies
+                if not oldduplexmode :
+                    duplexmode = defaultduplexmode
+                else :    
+                    duplexmode = oldduplexmode
+                if not oldpapersize :    
+                    papersize = defaultpapersize
+                else :    
+                    papersize = oldpapersize
+                duplexmode = oldduplexmode
+                papersize = oldpapersize or page["mediasize"]
+            if page["mediasize"] != "Default" :
+                papersize = page["mediasize"]
+            if not duplexmode :    
+                duplexmode = oldduplexmode or defaultduplexmode
+            oldpjlcopies = pjlcopies    
+            oldduplexmode = duplexmode
+            oldpapersize = papersize
+            copies = max(pjlcopies, page["copies"]) # Was : pjlcopies * page["copies"]
+            self.pagecount += (copies - 1)
+            self.logdebug("%s*%s*%s*%s" % (copies, 
+                                           papersize, 
+                                           page["mediasource"], 
+                                           duplexmode))
+        return self.pagecount
+        
+if __name__ == "__main__" :    
+    pdlparser.test(Parser)
Index: pkpgcounter/tags/2.18/pkpgpdls/plain.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/plain.py (revision 443)
+++ pkpgcounter/tags/2.18/pkpgpdls/plain.py (revision 443)
@@ -0,0 +1,75 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a page counter for plain text documents."""
+
+import sys
+import os
+
+import pdlparser
+import version
+
+
+class Parser(pdlparser.PDLParser) :
+    """A parser for plain text documents."""
+    totiffcommands = [ 'enscript --quiet --portrait --no-header --columns 1 --output - | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -',
+                       'a2ps --borders 0 --quiet --portrait --no-header --columns 1 --output - | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -',
+                     ]  
+    def isValid(self) :    
+        """Returns True if data is plain text, else False.
+        
+           It's hard to detect a plain text file, so we just
+           read the first line, and if it doesn't end in CR or LF
+           we consider it's not plain text.
+        """   
+        line = self.infile.readline()
+        self.infile.seek(0)
+        if line.endswith("\n") or line.endswith("\r") :
+            self.logdebug("DEBUG: Input file seems to be in the plain text format.")
+            return True
+        else :    
+            return False
+            
+    def getJobSize(self) :
+        """Counts pages in a plain text document."""
+        pagesize = 66   # TODO : Does this vary wrt the default page size ?
+                        # TODO : /etc/papersize and /etc/paper.config
+        pagecount = 0
+        linecount = 0
+        for line in self.infile :
+            if line.endswith("\n") or line.endswith("\r") :
+                linecount += 1    
+                if (linecount > pagesize) :
+                    pagecount += 1
+                    linecount = 0
+                else :    
+                    cnt = line.count("\f")
+                    if cnt :
+                        pagecount += cnt
+                        linecount = 0
+            else :        
+                raise pdlparser.PDLParserError, "Unsupported file format. Please send the file to %s" % version.__authoremail__
+        return pagecount + 1    # NB : empty files are catched in isValid()
+        
+if __name__ == "__main__" :    
+    pdlparser.test(Parser)
Index: pkpgcounter/tags/2.18/pkpgpdls/pdf.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/pdf.py (revision 450)
+++ pkpgcounter/tags/2.18/pkpgpdls/pdf.py (revision 450)
@@ -0,0 +1,108 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a page counter for PDF documents."""
+
+import sys
+import re
+
+import pdlparser
+
+class PDFObject :
+    """A class for PDF objects."""
+    def __init__(self, major, minor, description) :
+        """Initialize the PDF object."""
+        self.major = major
+        self.minor = minor
+        self.description = description
+        self.comments = []
+        self.content = []
+        self.parent = None
+        self.kids = []
+        
+class Parser(pdlparser.PDLParser) :
+    """A parser for PDF documents."""
+    totiffcommands = [ 'gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -' ]
+    def isValid(self) :    
+        """Returns True if data is PDF, else False."""
+        if self.firstblock.startswith("%PDF-") or \
+           self.firstblock.startswith("\033%-12345X%PDF-") or \
+           ((self.firstblock[:128].find("\033%-12345X") != -1) and (self.firstblock.upper().find("LANGUAGE=PDF") != -1)) or \
+           (self.firstblock.find("%PDF-") != -1) :
+            self.logdebug("DEBUG: Input file is in the PDF format.")
+            return True
+        else :    
+            return False
+        
+    def getJobSize(self) :    
+        """Counts pages in a PDF document."""
+        # First we start with a generic PDF parser.
+        lastcomment = None
+        objects = {}
+        inobject = 0
+        objre = re.compile(r"\s?(\d+)\s+(\d+)\s+obj[<\s/]?")
+        for line in self.infile :
+            line = line.strip()
+            if line.startswith("% ") :    
+                if inobject :
+                    obj.comments.append(line)
+                else :
+                    lastcomment = line[2:]
+            else :
+                # New object begins here
+                result = objre.search(line)
+                if result is not None :
+                    (major, minor) = [int(num) for num in line[result.start():result.end()].split()[:2]]
+                    obj = PDFObject(major, minor, lastcomment)
+                    obj.content.append(line[result.end():])
+                    inobject = 1
+                elif line.startswith("endobj") \
+                  or line.startswith(">> endobj") \
+                  or line.startswith(">>endobj") :
+                    # Handle previous object, if any
+                    if inobject :
+                        # only overwrite older versions of this object
+                        # same minor seems to be possible, so the latest one
+                        # found in the file will be the one we keep.
+                        # if we want the first one, just use > instead of >=
+                        oldobject = objects.setdefault(major, obj)
+                        if minor >= oldobject.minor :
+                            objects[major] = obj
+                        inobject = 0        
+                else :    
+                    if inobject :
+                        obj.content.append(line)
+                        
+        # Now we check each PDF object we've just created.
+        # colorregexp = re.compile(r"(/ColorSpace) ?(/DeviceRGB|/DeviceCMYK)[/ \t\r\n]", re.I)
+        newpageregexp = re.compile(r"(/Type)\s?(/Page)[/>\s]", re.I)
+        pagecount = 0
+        for obj in objects.values() :
+            content = "".join(obj.content)
+            count = len(newpageregexp.findall(content))
+            if count and (content != r"<</Type /Page>>") : # Empty pages which are not rendered ?
+                pagecount += count
+        return pagecount    
+        
+if __name__ == "__main__" :    
+    pdlparser.test(Parser)
Index: pkpgcounter/tags/2.18/pkpgpdls/oldpcl345.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/oldpcl345.py (revision 443)
+++ pkpgcounter/tags/2.18/pkpgpdls/oldpcl345.py (revision 443)
@@ -0,0 +1,491 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a page counter for PCL3/4/5 documents."""
+
+import sys
+import os
+import mmap
+from struct import unpack
+
+import pdlparser
+import pjl
+
+class Parser(pdlparser.PDLParser) :
+    """A parser for PCL3, PCL4, PCL5 documents."""
+    totiffcommands = [ 'pcl6 -sDEVICE=pdfwrite -r%(dpi)i -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -sOutputFile=- - | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -', 
+                       'pcl6 -sDEVICE=pswrite -r%(dpi)i -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -sOutputFile=- - | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -',
+                     ]
+    mediasizes = {  # ESC&l####A
+                    0 : "Default",
+                    1 : "Executive",
+                    2 : "Letter",
+                    3 : "Legal",
+                    6 : "Ledger", 
+                    25 : "A5",
+                    26 : "A4",
+                    27 : "A3",
+                    45 : "JB5",
+                    46 : "JB4",
+                    71 : "HagakiPostcard",
+                    72 : "OufukuHagakiPostcard",
+                    80 : "MonarchEnvelope",
+                    81 : "COM10Envelope",
+                    90 : "DLEnvelope",
+                    91 : "C5Envelope",
+                    100 : "B5Envelope",
+                    101 : "Custom",
+                 }   
+                 
+    mediasources = { # ESC&l####H
+                     0 : "Default",
+                     1 : "Main",
+                     2 : "Manual",
+                     3 : "ManualEnvelope",
+                     4 : "Alternate",
+                     5 : "OptionalLarge",
+                     6 : "EnvelopeFeeder",
+                     7 : "Auto",
+                     8 : "Tray1",
+                   }
+                   
+    orientations = { # ESC&l####O
+                     0 : "Portrait",
+                     1 : "Landscape",
+                     2 : "ReversePortrait",
+                     3 : "ReverseLandscape",
+                   }
+                   
+    mediatypes = { # ESC&l####M
+                     0 : "Plain",
+                     1 : "Bond",
+                     2 : "Special",
+                     3 : "Glossy",
+                     4 : "Transparent",
+                   }
+        
+    def isValid(self) :    
+        """Returns True if data is PCL3/4/5, else False."""
+        if self.firstblock.startswith("\033E\033") or \
+           (self.firstblock.startswith("\033*rbC") and (not self.lastblock[-3:] == "\f\033@")) or \
+           self.firstblock.startswith("\033%8\033") or \
+           (self.firstblock.find("\033%-12345X") != -1) or \
+           (self.firstblock.find("@PJL ENTER LANGUAGE=PCL\012\015\033") != -1) or \
+           (self.firstblock.startswith(chr(0xcd)+chr(0xca)) and self.firstblock.find("\033E\033")) :
+            self.logdebug("DEBUG: Input file is in the PCL3/4/5 format.")
+            return True
+        else :    
+            return False
+        
+    def setPageDict(self, pages, number, attribute, value) :
+        """Initializes a page dictionnary."""
+        dic = pages.setdefault(number, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait", "escaped" : "", "duplex": 0})
+        dic[attribute] = value
+        
+    def getJobSize(self) :     
+        """Count pages in a PCL5 document.
+         
+           Should also work for PCL3 and PCL4 documents.
+           
+           Algorithm from pclcount
+           (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin 
+           published under the terms of the GNU General Public Licence v2.
+          
+           Backported from C to Python by Jerome Alet, then enhanced
+           with more PCL tags detected. I think all the necessary PCL tags
+           are recognized to correctly handle PCL5 files wrt their number
+           of pages. The documentation used for this was :
+         
+           HP PCL/PJL Reference Set
+           PCL5 Printer Language Technical Quick Reference Guide
+           http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf 
+        """
+        infileno = self.infile.fileno()
+        minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
+        tagsends = { "&n" : "W", 
+                     "&b" : "W", 
+                     "*i" : "W", 
+                     "*l" : "W", 
+                     "*m" : "W", 
+                     "*v" : "W", 
+                     "*c" : "W", 
+                     "(f" : "W", 
+                     "(s" : "W", 
+                     ")s" : "W", 
+                     "&p" : "X", 
+                     # "&l" : "XHAOM",  # treated specially
+                     "&a" : "G", # TODO : 0 means next side, 1 front side, 2 back side
+                     "*g" : "W",
+                     "*r" : "sbABC",
+                     "*t" : "R",
+                     # "*b" : "VW", # treated specially because it occurs very often
+                   }  
+        irmarker = chr(0xcd) + chr(0xca) # Marker for Canon ImageRunner printers
+        irmarker2 = chr(0x10) + chr(0x02)
+        wasirmarker = 0
+        hasirmarker = (minfile[:2] == (irmarker))
+        pagecount = resets = ejects = backsides = startgfx = endgfx = 0
+        starb = ampl = ispcl3 = escstart = 0
+        mediasourcecount = mediasizecount = orientationcount = mediatypecount = 0
+        tag = None
+        endmark = chr(0x1b) + chr(0x0c) + chr(0x00) 
+        asciilimit = chr(0x80)
+        pages = {}
+        pos = 0
+        try :
+            try :
+                while 1 :
+                    if hasirmarker and (minfile[pos:pos+2] == irmarker) :
+                        codop = minfile[pos+2:pos+4]
+                        # self.logdebug("Marker at 0x%08x     (%s)" % (pos, wasirmarker))
+                        length = unpack(">H", minfile[pos+8:pos+10])[0]
+                        pos += 20
+                        if codop != irmarker2 :
+                            pos += length
+                        wasirmarker = 1    
+                    else :        
+                        wasirmarker = 0
+                        char = minfile[pos] ; pos += 1
+                        if char == "\014" :    
+                            pagecount += 1
+                        elif char == "\033" :    
+                            starb = ampl = 0
+                            if minfile[pos : pos+8] == r"%-12345X" :
+                                endpos = pos + 9
+                                quotes = 0
+                                while (minfile[endpos] not in endmark) and \
+                                      ((minfile[endpos] < asciilimit) or (quotes % 2)) :
+                                    if minfile[endpos] == '"' :
+                                        quotes += 1
+                                    endpos += 1
+                                self.setPageDict(pages, pagecount, "escaped", minfile[pos : endpos])
+                                pos += (endpos - pos)
+                            else :
+                                #
+                                #     <ESC>*b###y#m###v###w... -> PCL3 raster graphics
+                                #     <ESC>*b###W -> Start of a raster data row/block
+                                #     <ESC>*b###V -> Start of a raster data plane
+                                #     <ESC>*c###W -> Start of a user defined pattern
+                                #     <ESC>*i###W -> Start of a viewing illuminant block
+                                #     <ESC>*l###W -> Start of a color lookup table
+                                #     <ESC>*m###W -> Start of a download dither matrix block
+                                #     <ESC>*v###W -> Start of a configure image data block
+                                #     <ESC>*r1A -> Start Gfx 
+                                #     <ESC>(s###W -> Start of a characters description block
+                                #     <ESC>)s###W -> Start of a fonts description block
+                                #     <ESC>(f###W -> Start of a symbol set block
+                                #     <ESC>&b###W -> Start of configuration data block
+                                #     <ESC>&l###X -> Number of copies for current page
+                                #     <ESC>&n###W -> Starts an alphanumeric string ID block
+                                #     <ESC>&p###X -> Start of a non printable characters block
+                                #     <ESC>&a2G -> Back side when duplex mode as generated by rastertohp
+                                #     <ESC>*g###W -> Needed for planes in PCL3 output
+                                #     <ESC>&l###H (or only 0 ?) -> Eject if NumPlanes > 1, as generated by rastertohp. Also defines mediasource
+                                #     <ESC>&l###A -> mediasize
+                                #     <ESC>&l###O -> orientation
+                                #     <ESC>&l###M -> mediatype
+                                #     <ESC>*t###R -> gfx resolution
+                                #
+                                tagstart = minfile[pos] ; pos += 1
+                                if tagstart in "E9=YZ" : # one byte PCL tag
+                                    if tagstart == "E" :
+                                        resets += 1
+                                    continue             # skip to next tag
+                                tag = tagstart + minfile[pos] ; pos += 1
+                                if tag == "*b" : 
+                                    starb = 1
+                                    tagend = "VW"
+                                elif tag == "&l" :    
+                                    ampl = 1
+                                    tagend = "XHAOM"
+                                else :    
+                                    try :
+                                        tagend = tagsends[tag]
+                                    except KeyError :    
+                                        continue # Unsupported PCL tag
+                                # Now read the numeric argument
+                                size = 0
+                                while 1 :
+                                    char = minfile[pos] ; pos += 1
+                                    if not char.isdigit() :
+                                        break
+                                    size = (size * 10) + int(char)    
+                                if char in tagend :    
+                                    if tag == "&l" :
+                                        if char == "X" : 
+                                            self.setPageDict(pages, pagecount, "copies", size)
+                                        elif char == "H" :
+                                            self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size)))
+                                            mediasourcecount += 1
+                                            ejects += 1 
+                                        elif char == "A" :
+                                            self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size)))
+                                            mediasizecount += 1
+                                        elif char == "O" :
+                                            self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size)))
+                                            orientationcount += 1
+                                        elif char == "M" :
+                                            self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size)))
+                                            mediatypecount += 1
+                                    elif tag == "*r" :
+                                        # Special tests for PCL3
+                                        if (char == "s") and size :
+                                            while 1 :
+                                                char = minfile[pos] ; pos += 1
+                                                if char == "A" :
+                                                    break
+                                        elif (char == "b") and (minfile[pos] == "C") and not size :
+                                            ispcl3 = 1 # Certainely a PCL3 file
+                                        startgfx += (char == "A") and (minfile[pos - 2] in ("0", "1", "2", "3")) # Start Gfx
+                                        endgfx += (not size) and (char in ("C", "B")) # End Gfx
+                                    elif tag == "*t" :    
+                                        escstart += 1
+                                    elif (tag == "&a") and (size == 2) :
+                                        # We are on the backside, so mark current page as duplex
+                                        self.setPageDict(pages, pagecount, "duplex", 1)
+                                        backsides += 1      # Back side in duplex mode
+                                    else :    
+                                        # we just ignore the block.
+                                        if tag == "&n" : 
+                                            # we have to take care of the operation id byte
+                                            # which is before the string itself
+                                            size += 1
+                                        pos += size    
+                        else :                            
+                            if starb :
+                                # special handling of PCL3 in which 
+                                # *b introduces combined ESCape sequences
+                                size = 0
+                                while 1 :
+                                    char = minfile[pos] ; pos += 1
+                                    if not char.isdigit() :
+                                        break
+                                    size = (size * 10) + int(char)    
+                                if char in ("w", "v") :    
+                                    ispcl3 = 1  # certainely a PCL3 document
+                                    pos += size - 1
+                                elif char in ("y", "m") :    
+                                    ispcl3 = 1  # certainely a PCL3 document
+                                    pos -= 1    # fix position : we were ahead
+                            elif ampl :        
+                                # special handling of PCL3 in which 
+                                # &l introduces combined ESCape sequences
+                                size = 0
+                                while 1 :
+                                    char = minfile[pos] ; pos += 1
+                                    if not char.isdigit() :
+                                        break
+                                    size = (size * 10) + int(char)    
+                                if char in ("a", "o", "h", "m") :    
+                                    ispcl3 = 1  # certainely a PCL3 document
+                                    pos -= 1    # fix position : we were ahead
+                                    if char == "h" :
+                                        self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size)))
+                                        mediasourcecount += 1
+                                    elif char == "a" :
+                                        self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size)))
+                                        mediasizecount += 1
+                                    elif char == "o" :
+                                        self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size)))
+                                        orientationcount += 1
+                                    elif char == "m" :
+                                        self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size)))
+                                        mediatypecount += 1
+            except IndexError : # EOF ?
+                pass
+        finally :
+            minfile.close()
+                            
+        # if pagecount is still 0, we will use the number
+        # of resets instead of the number of form feed characters.
+        # but the number of resets is always at least 2 with a valid
+        # pcl file : one at the very start and one at the very end
+        # of the job's data. So we substract 2 from the number of
+        # resets. And since on our test data we needed to substract
+        # 1 more, we finally substract 3, and will test several
+        # PCL files with this. If resets < 2, then the file is
+        # probably not a valid PCL file, so we use 0
+        
+        if self.debug :
+            sys.stderr.write("pagecount : %s\n" % pagecount)
+            sys.stderr.write("resets : %s\n" % resets)
+            sys.stderr.write("ejects : %s\n" % ejects)
+            sys.stderr.write("backsides : %s\n" % backsides)
+            sys.stderr.write("startgfx : %s\n" % startgfx)
+            sys.stderr.write("endgfx : %s\n" % endgfx)
+            sys.stderr.write("mediasourcecount : %s\n" % mediasourcecount)
+            sys.stderr.write("mediasizecount : %s\n" % mediasizecount)
+            sys.stderr.write("orientationcount : %s\n" % orientationcount)
+            sys.stderr.write("mediatypecount : %s\n" % mediatypecount)
+            sys.stderr.write("escstart : %s\n" % escstart)
+            sys.stderr.write("hasirmarker : %s\n" % hasirmarker)
+        
+        if hasirmarker :
+            self.logdebug("Rule #20 (probably a Canon ImageRunner)")
+            pagecount += 1
+        elif (orientationcount == (pagecount - 1)) and (resets == 1) :
+            if resets == ejects == startgfx == mediasourcecount == escstart == 1 :
+                self.logdebug("Rule #19")
+            else :    
+                self.logdebug("Rule #1")
+                pagecount -= 1
+        elif pagecount and (pagecount == orientationcount) :
+            self.logdebug("Rule #2")
+        elif resets == ejects == mediasourcecount == mediasizecount == escstart == 1 :
+            #if ((startgfx and endgfx) and (startgfx != endgfx)) or (startgfx == endgfx == 0) :
+            if (startgfx and endgfx) or (startgfx == endgfx == 0) :
+                self.logdebug("Rule #3")
+                pagecount = orientationcount
+            elif (endgfx and not startgfx) and (pagecount > orientationcount) :    
+                self.logdebug("Rule #4")
+                pagecount = orientationcount
+            else :     
+                self.logdebug("Rule #5")
+                pagecount += 1
+        elif (ejects == mediasourcecount == orientationcount) and (startgfx == endgfx) :     
+            if (resets == 2) and (orientationcount == (pagecount - 1)) and (orientationcount > 1) :
+                self.logdebug("Rule #6")
+                pagecount = orientationcount
+        elif pagecount == mediasourcecount == escstart : 
+            self.logdebug("Rule #7")
+        elif resets == startgfx == endgfx == mediasizecount == orientationcount == escstart == 1 :     
+            self.logdebug("Rule #8")
+        elif resets == startgfx == endgfx == (pagecount - 1) :    
+            self.logdebug("Rule #9")
+        elif (not startgfx) and (not endgfx) :
+            self.logdebug("Rule #10")
+        elif (resets == 2) and (startgfx == endgfx) and (mediasourcecount == 1) :
+            if orientationcount == (pagecount - 1) :
+                self.logdebug("Rule #11")
+                pagecount = orientationcount
+            elif not pagecount :    
+                self.logdebug("Rule #17")
+                pagecount = ejects
+        elif (resets == 1) and (startgfx == endgfx) and (mediasourcecount == 0) :
+            if (startgfx > 1) and (startgfx != (pagecount - 1)) :
+                self.logdebug("Rule #12")
+                pagecount -= 1
+            else :    
+                self.logdebug("Rule #18")
+        elif startgfx == endgfx :    
+            self.logdebug("Rule #13")
+            pagecount = startgfx
+        elif startgfx == (endgfx - 1) :    
+            self.logdebug("Rule #14")
+            pagecount = startgfx
+        elif (startgfx == 1) and not endgfx :    
+            self.logdebug("Rule #15")
+            pass
+        else :    
+            self.logdebug("Rule #16")
+            pagecount = abs(startgfx - endgfx)
+            
+        defaultpjlcopies = 1    
+        defaultduplexmode = "Simplex"
+        defaultpapersize = ""
+        oldpjlcopies = -1
+        oldduplexmode = ""
+        oldpapersize = ""
+        for pnum in range(pagecount) :
+            # if no number of copies defined, take the preceding one else the one set before any page else 1.
+            page = pages.get(pnum, pages.get(pnum - 1, pages.get(0, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait", "escaped" : "", "duplex": 0})))
+            pjlstuff = page["escaped"]
+            if pjlstuff :
+                pjlparser = pjl.PJLParser(pjlstuff)
+                nbdefaultcopies = int(pjlparser.default_variables.get("COPIES", -1))
+                nbcopies = int(pjlparser.environment_variables.get("COPIES", -1))
+                nbdefaultqty = int(pjlparser.default_variables.get("QTY", -1))
+                nbqty = int(pjlparser.environment_variables.get("QTY", -1))
+                if nbdefaultcopies > -1 :
+                    defaultpjlcopies = nbdefaultcopies
+                if nbdefaultqty > -1 :
+                    defaultpjlcopies = nbdefaultqty
+                if nbcopies > -1 :
+                    pjlcopies = nbcopies
+                elif nbqty > -1 :
+                    pjlcopies = nbqty
+                else :
+                    if oldpjlcopies == -1 :    
+                        pjlcopies = defaultpjlcopies
+                    else :    
+                        pjlcopies = oldpjlcopies    
+                if page["duplex"] :        
+                    duplexmode = "Duplex"
+                else :    
+                    defaultdm = pjlparser.default_variables.get("DUPLEX", "")
+                    if defaultdm :
+                        if defaultdm.upper() == "ON" :
+                            defaultduplexmode = "Duplex"
+                        else :    
+                            defaultduplexmode = "Simplex"
+                    envdm = pjlparser.environment_variables.get("DUPLEX", "")
+                    if envdm :
+                        if envdm.upper() == "ON" :
+                            duplexmode = "Duplex"
+                        else :    
+                            duplexmode = "Simplex"
+                    else :        
+                        duplexmode = oldduplexmode or defaultduplexmode
+                defaultps = pjlparser.default_variables.get("PAPER", "")
+                if defaultps :
+                    defaultpapersize = defaultps
+                envps = pjlparser.environment_variables.get("PAPER", "")
+                if envps :
+                    papersize = envps
+                else :    
+                    if not oldpapersize :
+                        papersize = defaultpapersize
+                    else :    
+                        papersize = oldpapersize
+            else :        
+                if oldpjlcopies == -1 :
+                    pjlcopies = defaultpjlcopies
+                else :    
+                    pjlcopies = oldpjlcopies
+                
+                duplexmode = (page["duplex"] and "Duplex") or oldduplexmode or defaultduplexmode
+                if not oldpapersize :    
+                    papersize = defaultpapersize
+                else :    
+                    papersize = oldpapersize
+                papersize = oldpapersize or page["mediasize"]
+            if page["mediasize"] != "Default" :
+                papersize = page["mediasize"]
+            if not duplexmode :    
+                duplexmode = oldduplexmode or defaultduplexmode
+            oldpjlcopies = pjlcopies    
+            oldduplexmode = duplexmode
+            oldpapersize = papersize
+            copies = pjlcopies * page["copies"]        
+            pagecount += (copies - 1)
+            self.logdebug("%s*%s*%s*%s*%s*%s*BW" % (copies, \
+                                              page["mediatype"], \
+                                              papersize, \
+                                              page["orientation"], \
+                                              page["mediasource"], \
+                                              duplexmode))
+                
+        return pagecount
+        
+if __name__ == "__main__" :    
+    pdlparser.test(Parser)
Index: pkpgcounter/tags/2.18/pkpgpdls/postscript.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/postscript.py (revision 450)
+++ pkpgcounter/tags/2.18/pkpgpdls/postscript.py (revision 450)
@@ -0,0 +1,212 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a page counter for PostScript documents."""
+
+import sys
+import os
+import tempfile
+import popen2
+
+import pdlparser
+import inkcoverage
+
+class Parser(pdlparser.PDLParser) :
+    """A parser for PostScript documents."""
+    totiffcommands = [ 'gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -' ]
+    def isValid(self) :    
+        """Returns True if data is PostScript, else False."""
+        if self.firstblock.startswith("%!") or \
+           self.firstblock.startswith("\004%!") or \
+           self.firstblock.startswith("\033%-12345X%!PS") or \
+           ((self.firstblock[:128].find("\033%-12345X") != -1) and \
+             ((self.firstblock.find("LANGUAGE=POSTSCRIPT") != -1) or \
+              (self.firstblock.find("LANGUAGE = POSTSCRIPT") != -1) or \
+              (self.firstblock.find("LANGUAGE = Postscript") != -1))) or \
+              (self.firstblock.find("%!PS-Adobe") != -1) :
+            self.logdebug("DEBUG: Input file is in the PostScript format.")
+            return True
+        else :    
+            return False
+        
+    def throughGhostScript(self) :
+        """Get the count through GhostScript, useful for non-DSC compliant PS files."""
+        self.logdebug("Internal parser sucks, using GhostScript instead...")
+        self.infile.seek(0)
+        command = 'gs -sDEVICE=bbox -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET - 2>&1 | grep -c "%%HiResBoundingBox:" 2>/dev/null'
+        child = popen2.Popen4(command)
+        try :
+            data = self.infile.read(pdlparser.MEGABYTE)    
+            while data :
+                child.tochild.write(data)
+                data = self.infile.read(pdlparser.MEGABYTE)
+            child.tochild.flush()
+            child.tochild.close()    
+        except (IOError, OSError), msg :    
+            raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
+            
+        pagecount = 0
+        try :
+            pagecount = int(child.fromchild.readline().strip())
+        except (IOError, OSError, AttributeError, ValueError), msg :
+            raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
+        child.fromchild.close()
+        
+        try :
+            child.wait()
+        except OSError, msg :    
+            raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
+        self.logdebug("GhostScript said : %s pages" % pagecount)    
+        return pagecount * self.copies
+        
+    def natively(self) :
+        """Count pages in a DSC compliant PostScript document."""
+        self.infile.seek(0)
+        pagecount = 0
+        self.pages = { 0 : { "copies" : 1 } }
+        oldpagenum = None
+        previousline = ""
+        notrust = 0
+        prescribe = 0 # Kyocera's Prescribe commands
+        acrobatmarker = 0
+        pagescomment = None
+        for line in self.infile : 
+            if (not prescribe) and line.startswith(r"%%BeginResource: procset pdf") \
+               and not acrobatmarker :
+                notrust = 1 # Let this stuff be managed by GhostScript, but we still extract number of copies
+            elif line.startswith(r"%ADOPrintSettings: L") :
+                acrobatmarker = 1
+            elif line.startswith("!R!") :
+                prescribe = 1
+            elif line.startswith(r"%%Pages: ") :
+                try :
+                    pagescomment = max(pagescomment or 0, int(line.split()[1]))
+                except ValueError :
+                    pass # strange, to say the least
+            elif line.startswith(r"%%Page: ") or line.startswith(r"(%%[Page: ") :
+                proceed = 1
+                try :
+                    # treats both "%%Page: x x" and "%%Page: (x-y) z" (probably N-up mode)
+                    newpagenum = int(line.split(']')[0].split()[-1])
+                except :    
+                    notinteger = 1 # It seems that sometimes it's not an integer but an EPS file name
+                else :    
+                    notinteger = 0
+                    if newpagenum == oldpagenum :
+                        proceed = 0
+                    else :
+                        oldpagenum = newpagenum
+                if proceed and not notinteger :        
+                    pagecount += 1
+                    self.pages[pagecount] = { "copies" : self.pages[pagecount-1]["copies"] }
+            elif line.startswith(r"%%Requirements: numcopies(") :    
+                try :
+                    number = int(line.strip().split('(')[1].split(')')[0])
+                except :     
+                    pass
+                else :    
+                    if number > self.pages[pagecount]["copies"] :
+                        self.pages[pagecount]["copies"] = number
+            elif line.startswith(r"%%BeginNonPPDFeature: NumCopies ") :
+                # handle # of copies set by some Windows printer driver
+                try :
+                    number = int(line.strip().split()[2])
+                except :     
+                    pass
+                else :    
+                    if number > self.pages[pagecount]["copies"] :
+                        self.pages[pagecount]["copies"] = number
+            elif line.startswith("1 dict dup /NumCopies ") :
+                # handle # of copies set by mozilla/kprinter
+                try :
+                    number = int(line.strip().split()[4])
+                except :     
+                    pass
+                else :    
+                    if number > self.pages[pagecount]["copies"] :
+                        self.pages[pagecount]["copies"] = number
+            elif line.startswith("{ pop 1 dict dup /NumCopies ") :
+                # handle # of copies set by firefox/kprinter/cups (alternate syntax)
+                try :
+                    number = int(line.strip().split()[6])
+                except :
+                    pass
+                else :
+                    if number > self.pages[pagecount]["copies"] :
+                        self.pages[pagecount]["copies"] = number
+            elif line.startswith("/languagelevel where{pop languagelevel}{1}ifelse 2 ge{1 dict dup/NumCopies") :
+                try :
+                    number = int(previousline.strip()[2:])
+                except :
+                    pass
+                else :
+                    if number > self.pages[pagecount]["copies"] :
+                        self.pages[pagecount]["copies"] = number
+            elif line.startswith("/#copies ") :
+                try :
+                    number = int(line.strip().split()[1])
+                except :     
+                    pass
+                else :    
+                    if number > self.pages[pagecount]["copies"] :
+                        self.pages[pagecount]["copies"] = number
+            elif line.startswith(r"%RBINumCopies: ") :   
+                try :
+                    number = int(line.strip().split()[1])
+                except :     
+                    pass
+                else :    
+                    if number > self.pages[pagecount]["copies"] :
+                        self.pages[pagecount]["copies"] = number
+            previousline = line
+            
+        # extract max number of copies to please the ghostscript parser, just    
+        # in case we will use it later
+        self.copies = max([ v["copies"] for (k, v) in self.pages.items() ])
+        
+        # now apply the number of copies to each page
+        if not pagecount and pagescomment :    
+            pagecount = pagescomment
+        for pnum in range(1, pagecount + 1) :
+            page = self.pages.get(pnum, self.pages.get(1, self.pages.get(0, { "copies" : 1 })))
+            copies = page["copies"]
+            pagecount += (copies - 1)
+            self.logdebug("%s * page #%s" % (copies, pnum))
+            
+        self.logdebug("Internal parser said : %s pages" % pagecount)
+        return (pagecount, notrust)
+        
+    def getJobSize(self) :    
+        """Count pages in PostScript document."""
+        self.copies = 1
+        (nbpages, notrust) = self.natively()
+        newnbpages = nbpages
+        if notrust or not nbpages :
+            try :
+                newnbpages = self.throughGhostScript()
+            except pdlparser.PDLParserError, msg :
+                self.logdebug(msg)
+        return max(nbpages, newnbpages)    
+        
+if __name__ == "__main__" :    
+    pdlparser.test(Parser)
Index: pkpgcounter/tags/2.18/pkpgpdls/pcl345.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/pcl345.py (revision 456)
+++ pkpgcounter/tags/2.18/pkpgpdls/pcl345.py (revision 456)
@@ -0,0 +1,576 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a page counter for PCL3/4/5 documents."""
+
+import sys
+import os
+import mmap
+from struct import unpack
+
+import pdlparser
+import pjl
+
+NUL = chr(0x00)
+LINEFEED = chr(0x0a)
+FORMFEED = chr(0x0c)
+ESCAPE = chr(0x1b)
+ASCIILIMIT = chr(0x80)
+
+class Parser(pdlparser.PDLParser) :
+    """A parser for PCL3, PCL4, PCL5 documents."""
+    totiffcommands = [ 'pcl6 -sDEVICE=pdfwrite -r%(dpi)i -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -sOutputFile=- - | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -', 
+                       'pcl6 -sDEVICE=pswrite -r%(dpi)i -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -sOutputFile=- - | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -',
+                     ]
+    mediasizes = {  # ESC&l####A
+                    0 : "Default",
+                    1 : "Executive",
+                    2 : "Letter",
+                    3 : "Legal",
+                    6 : "Ledger", 
+                    25 : "A5",
+                    26 : "A4",
+                    27 : "A3",
+                    45 : "JB5",
+                    46 : "JB4",
+                    71 : "HagakiPostcard",
+                    72 : "OufukuHagakiPostcard",
+                    80 : "MonarchEnvelope",
+                    81 : "COM10Envelope",
+                    90 : "DLEnvelope",
+                    91 : "C5Envelope",
+                    100 : "B5Envelope",
+                    101 : "Custom",
+                 }   
+                 
+    mediasources = { # ESC&l####H
+                     0 : "Default",
+                     1 : "Main",
+                     2 : "Manual",
+                     3 : "ManualEnvelope",
+                     4 : "Alternate",
+                     5 : "OptionalLarge",
+                     6 : "EnvelopeFeeder",
+                     7 : "Auto",
+                     8 : "Tray1",
+                   }
+                   
+    orientations = { # ESC&l####O
+                     0 : "Portrait",
+                     1 : "Landscape",
+                     2 : "ReversePortrait",
+                     3 : "ReverseLandscape",
+                   }
+                   
+    mediatypes = { # ESC&l####M
+                     0 : "Plain",
+                     1 : "Bond",
+                     2 : "Special",
+                     3 : "Glossy",
+                     4 : "Transparent",
+                   }
+        
+    def isValid(self) :    
+        """Returns True if data is PCL3/4/5, else False."""
+        if self.firstblock.startswith("\033E\033") or \
+           (self.firstblock.startswith("\033*rbC") and (not self.lastblock[-3:] == "\f\033@")) or \
+           self.firstblock.startswith("\033%8\033") or \
+           (self.firstblock.find("\033%-12345X") != -1) or \
+           (self.firstblock.find("@PJL ENTER LANGUAGE=PCL\012\015\033") != -1) or \
+           (self.firstblock.startswith(chr(0xcd)+chr(0xca)) and self.firstblock.find("\033E\033")) :
+            self.logdebug("DEBUG: Input file is in the PCL3/4/5 format.")
+            return True
+        else :    
+            return False
+        
+    def setPageDict(self, attribute, value) :
+        """Initializes a page dictionnary."""
+        dic = self.pages.setdefault(self.pagecount, { "linescount" : 1,
+                                                      "copies" : 1, 
+                                                      "mediasource" : "Main", 
+                                                      "mediasize" : "Default", 
+                                                      "mediatype" : "Plain", 
+                                                      "orientation" : "Portrait", 
+                                                      "escaped" : "", 
+                                                      "duplex": 0 })
+        dic[attribute] = value
+        
+    def readByte(self) :    
+        """Reads a byte from the input stream."""
+        tag = ord(self.minfile[self.pos])
+        self.pos += 1
+        return tag
+        
+    def endPage(self) :    
+        """Handle the FF marker."""
+        #self.logdebug("FORMFEED %i at %08x" % (self.pagecount, self.pos-1))
+        if not self.hpgl2 :
+            # Increments page count only if we are not inside an HPGL2 block
+            self.pagecount += 1
+        
+    def escPercent(self) :    
+        """Handles the ESC% sequence."""
+        if self.minfile[self.pos : self.pos+7] == r"-12345X" :
+            #self.logdebug("Generic ESCAPE sequence at %08x" % self.pos)
+            self.pos += 7
+            buffer = []
+            quotes = 0
+            char = chr(self.readByte())
+            while ((char < ASCIILIMIT) or (quotes % 2)) and (char not in (FORMFEED, ESCAPE, NUL)) :  
+                buffer.append(char)
+                if char == '"' :
+                    quotes += 1
+                char = chr(self.readByte())
+            self.setPageDict("escaped", "".join(buffer))
+            #self.logdebug("ESCAPED : %s" % "".join(buffer))
+            self.pos -= 1   # Adjust position
+        else :    
+            while 1 :
+                (value, end) = self.getInteger()
+                if end == 'B' :
+                    self.enterHPGL2()
+                    while self.minfile[self.pos] != ESCAPE :
+                        self.pos += 1
+                    self.pos -= 1    
+                    return 
+                elif end == 'A' :    
+                    self.exitHPGL2()
+                    return
+                elif end is None :    
+                    return
+        
+    def enterHPGL2(self) :    
+        """Enters HPGL2 mode."""
+        #self.logdebug("ENTERHPGL2 %08x" % self.pos)
+        self.hpgl2 = True
+        
+    def exitHPGL2(self) :    
+        """Exits HPGL2 mode."""
+        #self.logdebug("EXITHPGL2 %08x" % self.pos)
+        self.hpgl2 = False
+        
+    def handleTag(self, tagtable) :    
+        """Handles tags."""
+        tagtable[self.readByte()]()
+        
+    def escape(self) :    
+        """Handles the ESC character."""
+        #self.logdebug("ESCAPE")
+        self.handleTag(self.esctags)
+        
+    def escAmp(self) :    
+        """Handles the ESC& sequence."""
+        #self.logdebug("AMP")
+        self.handleTag(self.escamptags)
+        
+    def escStar(self) :    
+        """Handles the ESC* sequence."""
+        #self.logdebug("STAR")
+        self.handleTag(self.escstartags)
+        
+    def escLeftPar(self) :    
+        """Handles the ESC( sequence."""
+        #self.logdebug("LEFTPAR")
+        self.handleTag(self.escleftpartags)
+        
+    def escRightPar(self) :    
+        """Handles the ESC( sequence."""
+        #self.logdebug("RIGHTPAR")
+        self.handleTag(self.escrightpartags)
+        
+    def escE(self) :    
+        """Handles the ESCE sequence."""
+        #self.logdebug("RESET")
+        self.resets += 1
+        
+    def escAmpl(self) :    
+        """Handles the ESC&l sequence."""
+        while 1 :
+            (value, end) = self.getInteger()
+            if value is None :
+                return
+            if end in ('h', 'H') :
+                mediasource = self.mediasources.get(value, str(value))
+                self.mediasourcesvalues.append(mediasource)
+                self.setPageDict("mediasource", mediasource)
+                #self.logdebug("MEDIASOURCE %s" % mediasource)
+            elif end in ('a', 'A') :
+                mediasize = self.mediasizes.get(value, str(value))
+                self.mediasizesvalues.append(mediasize)
+                self.setPageDict("mediasize", mediasize)
+                #self.logdebug("MEDIASIZE %s" % mediasize)
+            elif end in ('o', 'O') :
+                orientation = self.orientations.get(value, str(value))
+                self.orientationsvalues.append(orientation)
+                self.setPageDict("orientation", orientation)
+                #self.logdebug("ORIENTATION %s" % orientation)
+            elif end in ('m', 'M') :
+                mediatype = self.mediatypes.get(value, str(value))
+                self.mediatypesvalues.append(mediatype)
+                self.setPageDict("mediatype", mediatype)
+                #self.logdebug("MEDIATYPE %s" % mediatype)
+            elif end == 'X' :
+                self.copies.append(value)
+                self.setPageDict("copies", value)
+                #self.logdebug("COPIES %i" % value)
+            elif end == 'F' :    
+                self.linesperpagevalues.append(value)
+                self.linesperpage = value
+                #self.logdebug("LINES PER PAGE : %i" % self.linesperpage)
+            #else :
+            #    self.logdebug("Unexpected end <%s> and value <%s>" % (end, value))
+                
+    def escAmpa(self) :    
+        """Handles the ESC&a sequence."""
+        while 1 :
+            (value, end) = self.getInteger()
+            if value is None :
+                return
+            if end == 'G' :    
+                #self.logdebug("BACKSIDES %i" % value)
+                self.backsides.append(value)
+                self.setPageDict("duplex", value)
+                
+    def escAmpp(self) :    
+        """Handles the ESC&p sequence."""
+        while 1 :
+            (value, end) = self.getInteger()
+            if value is None :
+                return
+            if end == 'X' :    
+                self.pos += value
+                #self.logdebug("SKIPTO %08x" % self.pos)
+                
+    def escStarb(self) :    
+        """Handles the ESC*b sequence."""
+        while 1 :
+            (value, end) = self.getInteger()
+            if (end is None) and (value is None) :
+                return
+            if end in ('V', 'W', 'v', 'w') :    
+                self.pos += (value or 0)
+                #self.logdebug("SKIPTO %08x" % self.pos)
+                
+    def escStarr(self) :    
+        """Handles the ESC*r sequence."""
+        while 1 :
+            (value, end) = self.getInteger()
+            if value is None :
+                if end is None :
+                    return
+                elif end in ('B', 'C') :        
+                    #self.logdebug("EndGFX")
+                    if self.startgfx :
+                        self.endgfx.append(1)
+                    else :    
+                        #self.logdebug("EndGFX found before StartGFX, ignored.")
+                        pass
+            if end == 'A' and (0 <= value <= 3) :
+                #self.logdebug("StartGFX %i" % value)
+                self.startgfx.append(value)
+                
+    def escStaroptAmpu(self) :    
+        """Handles the ESC*o ESC*p ESC*t and ESC&u sequences."""
+        while 1 :
+            (value, end) = self.getInteger()
+            if value is None :
+                return
+        
+    def escSkipSomethingW(self) :    
+        """Handles the ESC???###W sequences."""
+        while 1 :
+            (value, end) = self.getInteger()
+            if value is None :
+                return
+            if end == 'W' :    
+                self.pos += value
+                #self.logdebug("SKIPTO %08x" % self.pos)
+                
+    def newLine(self) :            
+        """Handles new lines markers."""
+        if not self.hpgl2 :
+            dic = self.pages.get(self.pagecount, None)
+            if dic is None :
+                self.setPageDict("linescount", 1)                              
+                dic = self.pages.get(self.pagecount)
+            nblines = dic["linescount"]    
+            self.setPageDict("linescount", nblines + 1)                              
+            if (self.linesperpage is not None) \
+               and (dic["linescount"] > self.linesperpage) :
+                self.pagecount += 1
+        
+    def getInteger(self) :    
+        """Returns an integer value and the end character."""
+        sign = 1
+        value = None
+        while 1 :
+            char = chr(self.readByte())
+            if char in (NUL, ESCAPE, FORMFEED, ASCIILIMIT) :
+                self.pos -= 1 # Adjust position
+                return (None, None)
+            if char == '-' :
+                sign = -1
+            elif not char.isdigit() :
+                if value is not None :
+                    return (sign*value, char)
+                else :
+                    return (value, char)
+            else :    
+                value = ((value or 0) * 10) + int(char)    
+        
+    def skipByte(self) :    
+        """Skips a byte."""
+        #self.logdebug("SKIPBYTE %08x ===> %02x" % (self.pos, ord(self.minfile[self.pos])))
+        self.pos += 1
+        
+    def handleImageRunner(self) :    
+        """Handles Canon ImageRunner tags."""
+        tag = self.readByte()
+        if tag == ord(self.imagerunnermarker1[-1]) :
+            oldpos = self.pos-2
+            codop = self.minfile[self.pos:self.pos+2]
+            length = unpack(">H", minfile[pos+6:pos+8])[0]
+            self.pos += 18
+            if codop != self.imagerunnermarker2 :
+                self.pos += length
+            self.logdebug("IMAGERUNNERTAG SKIP %i AT %08x" % (self.pos-oldpos, self.pos))
+        else :
+            self.pos -= 1 # Adjust position
+                
+    def getJobSize(self) :     
+        """Count pages in a PCL5 document.
+         
+           Should also work for PCL3 and PCL4 documents.
+           
+           Algorithm from pclcount
+           (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin 
+           published under the terms of the GNU General Public Licence v2.
+          
+           Backported from C to Python by Jerome Alet, then enhanced
+           with more PCL tags detected. I think all the necessary PCL tags
+           are recognized to correctly handle PCL5 files wrt their number
+           of pages. The documentation used for this was :
+         
+           HP PCL/PJL Reference Set
+           PCL5 Printer Language Technical Quick Reference Guide
+           http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf 
+        """
+        infileno = self.infile.fileno()
+        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
+        self.pages = {}
+        self.pagecount = 0
+        self.resets = 0
+        self.backsides = []
+        self.copies = []
+        self.mediasourcesvalues = []
+        self.mediasizesvalues = []
+        self.orientationsvalues = []
+        self.mediatypesvalues = []
+        self.linesperpagevalues = []
+        self.linesperpage = None
+        self.startgfx = []
+        self.endgfx = []
+        self.hpgl2 = False
+        self.imagerunnermarker1 = chr(0xcd) + chr(0xca) # Markers for Canon ImageRunner printers
+        self.imagerunnermarker2 = chr(0x10) + chr(0x02)
+        self.isimagerunner = (minfile[:2] == self.imagerunnermarker1)
+        
+        tags = [ lambda : None] * 256
+        tags[ord(LINEFEED)] = self.newLine
+        tags[ord(FORMFEED)] = self.endPage
+        tags[ord(ESCAPE)] = self.escape
+        tags[ord(ASCIILIMIT)] = self.skipByte
+        tags[ord(self.imagerunnermarker1[0])] = self.handleImageRunner
+        
+        self.esctags = [ lambda : None ] * 256
+        self.esctags[ord('%')] = self.escPercent
+        self.esctags[ord('*')] = self.escStar
+        self.esctags[ord('&')] = self.escAmp
+        self.esctags[ord('(')] = self.escLeftPar
+        self.esctags[ord(')')] = self.escRightPar
+        self.esctags[ord('E')] = self.escE
+        
+        self.escamptags = [lambda : None ] * 256
+        self.escamptags[ord('a')] = self.escAmpa
+        self.escamptags[ord('l')] = self.escAmpl
+        self.escamptags[ord('p')] = self.escAmpp
+        self.escamptags[ord('b')] = self.escSkipSomethingW
+        self.escamptags[ord('n')] = self.escSkipSomethingW
+        self.escamptags[ord('u')] = self.escStaroptAmpu
+        
+        self.escstartags = [ lambda : None ] * 256
+        self.escstartags[ord('b')] = self.escStarb
+        self.escstartags[ord('r')] = self.escStarr
+        self.escstartags[ord('o')] = self.escStaroptAmpu
+        self.escstartags[ord('p')] = self.escStaroptAmpu
+        self.escstartags[ord('t')] = self.escStaroptAmpu
+        self.escstartags[ord('c')] = self.escSkipSomethingW
+        self.escstartags[ord('g')] = self.escSkipSomethingW
+        self.escstartags[ord('i')] = self.escSkipSomethingW
+        self.escstartags[ord('l')] = self.escSkipSomethingW
+        self.escstartags[ord('m')] = self.escSkipSomethingW
+        self.escstartags[ord('v')] = self.escSkipSomethingW
+        
+        self.escleftpartags = [ lambda : None ] * 256
+        self.escleftpartags[ord('s')] = self.escSkipSomethingW
+        self.escleftpartags[ord('f')] = self.escSkipSomethingW
+        
+        self.escrightpartags = [ lambda : None ] * 256
+        self.escrightpartags[ord('s')] = self.escSkipSomethingW
+        
+        self.pos = 0
+        try :
+            try :
+                while 1 :
+                    tags[self.readByte()]()
+            except IndexError : # EOF ?            
+                pass
+        finally :
+            self.minfile.close()
+        
+        self.logdebug("Pagecount : \t\t\t%i" % self.pagecount)
+        self.logdebug("Resets : \t\t\t%i" % self.resets)
+        self.logdebug("Copies : \t\t\t%s" % self.copies)
+        self.logdebug("NbCopiesMarks : \t\t%i" % len(self.copies))
+        self.logdebug("MediaTypes : \t\t\t%s" % self.mediatypesvalues)
+        self.logdebug("NbMediaTypes : \t\t\t%i" % len(self.mediatypesvalues))
+        self.logdebug("MediaSizes : \t\t\t%s" % self.mediasizesvalues)
+        self.logdebug("NbMediaSizes : \t\t\t%i" % len(self.mediasizesvalues))
+        self.logdebug("MediaSources : \t\t\t%s" % self.mediasourcesvalues)
+        nbmediasourcesdefault = len([m for m in self.mediasourcesvalues if m == 'Default'])
+        self.logdebug("MediaSourcesDefault : \t\t%i" % nbmediasourcesdefault)
+        self.logdebug("MediaSourcesNOTDefault : \t%i" % (len(self.mediasourcesvalues) - nbmediasourcesdefault))
+        self.logdebug("Orientations : \t\t\t%s" % self.orientationsvalues)
+        nborientations = len(self.orientationsvalues)
+        self.logdebug("NbOrientations : \t\t\t%i" % nborientations)
+        self.logdebug("StartGfx : \t\t\t%s" % len(self.startgfx))
+        self.logdebug("EndGfx : \t\t\t%s" % len(self.endgfx))
+        self.logdebug("BackSides : \t\t\t%s" % self.backsides)
+        self.logdebug("NbBackSides : \t\t\t%i" % len(self.backsides))
+        self.logdebug("IsImageRunner : \t\t\t%s" % self.isimagerunner)
+        
+        if self.isimagerunner :
+            self.pagecount += 1      # ImageRunner adjustment
+        elif self.linesperpage is not None :    
+            self.pagecount += 1      # Adjusts for incomplete last page
+        elif len(self.startgfx) == len(self.endgfx) == 0 :
+            if self.resets % 2 :
+                if nborientations == self.pagecount + 1 :
+                    self.logdebug("Adjusting PageCount : +1")
+                    self.pagecount += 1
+                elif nborientations == self.pagecount - 1 :
+                    self.logdebug("Adjusting PageCount : -1")
+                    self.pagecount -= 1
+                    
+        self.pagecount = self.pagecount or nbmediasourcesdefault
+        
+        
+        defaultpjlcopies = 1    
+        defaultduplexmode = "Simplex"
+        defaultpapersize = ""
+        oldpjlcopies = -1
+        oldduplexmode = ""
+        oldpapersize = ""
+        for pnum in range(self.pagecount) :
+            # if no number of copies defined, take the preceding one else the one set before any page else 1.
+            page = self.pages.get(pnum, self.pages.get(pnum - 1, self.pages.get(0, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait", "escaped" : "", "duplex": 0})))
+            pjlstuff = page["escaped"]
+            if pjlstuff :
+                pjlparser = pjl.PJLParser(pjlstuff)
+                nbdefaultcopies = int(pjlparser.default_variables.get("COPIES", -1))
+                nbcopies = int(pjlparser.environment_variables.get("COPIES", -1))
+                nbdefaultqty = int(pjlparser.default_variables.get("QTY", -1))
+                nbqty = int(pjlparser.environment_variables.get("QTY", -1))
+                if nbdefaultcopies > -1 :
+                    defaultpjlcopies = nbdefaultcopies
+                if nbdefaultqty > -1 :
+                    defaultpjlcopies = nbdefaultqty
+                if nbcopies > -1 :
+                    pjlcopies = nbcopies
+                elif nbqty > -1 :
+                    pjlcopies = nbqty
+                else :
+                    if oldpjlcopies == -1 :    
+                        pjlcopies = defaultpjlcopies
+                    else :    
+                        pjlcopies = oldpjlcopies    
+                if page["duplex"] :        
+                    duplexmode = "Duplex"
+                else :    
+                    defaultdm = pjlparser.default_variables.get("DUPLEX", "")
+                    if defaultdm :
+                        if defaultdm.upper() == "ON" :
+                            defaultduplexmode = "Duplex"
+                        else :    
+                            defaultduplexmode = "Simplex"
+                    envdm = pjlparser.environment_variables.get("DUPLEX", "")
+                    if envdm :
+                        if envdm.upper() == "ON" :
+                            duplexmode = "Duplex"
+                        else :    
+                            duplexmode = "Simplex"
+                    else :        
+                        duplexmode = oldduplexmode or defaultduplexmode
+                defaultps = pjlparser.default_variables.get("PAPER", "")
+                if defaultps :
+                    defaultpapersize = defaultps
+                envps = pjlparser.environment_variables.get("PAPER", "")
+                if envps :
+                    papersize = envps
+                else :    
+                    if not oldpapersize :
+                        papersize = defaultpapersize
+                    else :    
+                        papersize = oldpapersize
+            else :        
+                if oldpjlcopies == -1 :
+                    pjlcopies = defaultpjlcopies
+                else :    
+                    pjlcopies = oldpjlcopies
+                
+                duplexmode = (page["duplex"] and "Duplex") or oldduplexmode or defaultduplexmode
+                if not oldpapersize :    
+                    papersize = defaultpapersize
+                else :    
+                    papersize = oldpapersize
+                papersize = oldpapersize or page["mediasize"]
+            if page["mediasize"] != "Default" :
+                papersize = page["mediasize"]
+            if not duplexmode :    
+                duplexmode = oldduplexmode or defaultduplexmode
+            oldpjlcopies = pjlcopies    
+            oldduplexmode = duplexmode
+            oldpapersize = papersize
+            copies = max(pjlcopies, page["copies"]) # Was : pjlcopies * page["copies"]
+            self.pagecount += (copies - 1)
+            self.logdebug("%s*%s*%s*%s*%s*%s*BW" % (copies, \
+                                              page["mediatype"], \
+                                              papersize, \
+                                              page["orientation"], \
+                                              page["mediasource"], \
+                                              duplexmode))
+        
+        return self.pagecount
+        
+if __name__ == "__main__" :    
+    pdlparser.test(Parser)
Index: pkpgcounter/tags/2.18/pkpgpdls/escp2.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/escp2.py (revision 443)
+++ pkpgcounter/tags/2.18/pkpgpdls/escp2.py (revision 443)
@@ -0,0 +1,79 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a page counter for ESC/P2 documents."""
+
+import sys
+
+import pdlparser
+
+class Parser(pdlparser.PDLParser) :
+    """A parser for ESC/P2 documents."""
+    def isValid(self) :        
+        """Returns True if data is ESC/P2, else False."""
+        if self.firstblock.startswith("\033@") or \
+           self.firstblock.startswith("\033*") or \
+           self.firstblock.startswith("\n\033@") or \
+           self.firstblock.startswith("\0\0\0\033\1@EJL") : # ESC/P Raster ??? Seen on Stylus Photo 1284
+            self.logdebug("DEBUG: Input file is in the ESC/P2 format.")
+            return True
+        else :    
+            return False
+            
+    def getJobSize(self) :    
+        """Counts pages in an ESC/P2 document."""
+        # with Gimpprint, at least, for each page there
+        # are two Reset Printer sequences (ESC + @)
+        marker1 = "\033@"
+        
+        # with other software or printer driver, we
+        # may prefer to search for "\r\n\fESCAPE"
+        # or "\r\fESCAPE"
+        marker2r = "\r\f\033"
+        marker2rn = "\r\n\f\033"
+        
+        # and ghostscript's stcolor for example seems to
+        # output ESC + @ + \f for each page plus one
+        marker3 = "\033@\f"
+        
+        # while ghostscript's escp driver outputs instead
+        # \f + ESC + @
+        marker4 = "\f\033@"
+        
+        data = self.infile.read()
+        pagecount1 = data.count(marker1)
+        pagecount2 = max(data.count(marker2r), data.count(marker2rn))
+        pagecount3 = data.count(marker3)
+        pagecount4 = data.count(marker4)
+            
+        if pagecount2 :    
+            return pagecount2
+        elif pagecount3 > 1 :     
+            return pagecount3 - 1
+        elif pagecount4 :    
+            return pagecount4
+        else :    
+            return int(pagecount1 / 2)       
+        
+if __name__ == "__main__" :    
+    pdlparser.test(Parser)
Index: pkpgcounter/tags/2.18/pkpgpdls/spl1.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/spl1.py (revision 456)
+++ pkpgcounter/tags/2.18/pkpgpdls/spl1.py (revision 456)
@@ -0,0 +1,130 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a page counter for SPL1 documents."""
+
+import sys
+import os
+import mmap
+from struct import unpack
+
+import pdlparser
+import version
+
+ESCAPECHARS = (chr(0x1b), chr(0x24))
+
+class Parser(pdlparser.PDLParser) :
+    """A parser for SPL1 documents."""
+    def isValid(self) :    
+        """Returns True if data is QPDL aka SPL2, else False."""
+        if ((self.firstblock[:128].find("\033%-12345X") != -1) and \
+            (self.firstblock.find("$PJL ") != -1) and \
+             ((self.firstblock.find("LANGUAGE=SMART") != -1) or \
+              (self.firstblock.find("LANGUAGE = SMART") != -1))) :
+            self.logdebug("DEBUG: Input file is in the SPL1 (aka SPL12) format.")
+            return True
+        else :    
+            return False
+            
+    def littleEndian(self) :
+        """Toggles to little endianness."""
+        self.unpackType = { 1 : "B", 2 : "<H", 4 : "<I" }
+        self.unpackShort = self.unpackType[2]
+        self.unpackLong = self.unpackType[4]
+        return 0
+        
+    def bigEndian(self) :
+        """Toggles to big endianness."""
+        self.unpackType = { 1 : "B", 2 : ">H", 4 : ">I" }
+        self.unpackShort = self.unpackType[2]
+        self.unpackLong = self.unpackType[4]
+        return 0
+    
+    def escape(self, nextpos) :    
+        """Handles the ESC code."""
+        self.isbitmap = False
+        pos = endpos = nextpos
+        minfile = self.minfile
+        if minfile[pos : pos+8] == r"%-12345X" :
+            endpos = pos + 9
+        elif minfile[pos-1] in ESCAPECHARS :    
+            endpos = pos
+        else :    
+            return 0
+        endmark = (chr(0x1b), chr(0x00))
+        asciilimit = chr(0x80)
+        quotes = 0
+        while (minfile[endpos] not in endmark) and \
+               ((minfile[endpos] < asciilimit) or (quotes % 2)) :
+            if minfile[endpos] == '"' :
+                quotes += 1
+            endpos += 1
+            
+        # Store this in a per page mapping.    
+        # NB : First time will be at page 0 (i.e. **before** page 1) !
+        stuff = self.escapedStuff.setdefault(self.pagecount, [])
+        datas = minfile[pos-1 : endpos]
+        stuff.append(datas)
+        if datas.endswith("$PJL BITMAP START\r\n") :
+            self.isbitmap = True
+        self.logdebug("Escaped datas : [%s]" % repr(datas))
+        return endpos - pos + 1
+        
+    def getJobSize(self) :
+        """Counts pages in an SPL1 document.
+        
+           Algorithm by Jerome Alet.
+        """
+        infileno = self.infile.fileno()
+        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
+        self.pagecount = 0
+        self.escapedStuff = {}   # For escaped datas, mostly PJL commands
+        self.bigEndian()
+        
+        self.isbitmap = False
+        pos = 0
+        try :
+            try :
+                while 1 :
+                    tag = minfile[pos]
+                    if tag in ESCAPECHARS :
+                        pos += self.escape(pos+1)
+                    else :    
+                        if not self.isbitmap :
+                            raise pdlparser.PDLParserError, "Unfortunately SPL1 is incompletely recognized. Parsing aborted. Please report the problem to %s" % version.__authoremail__
+                        offset = unpack(self.unpackLong, minfile[pos:pos+4])[0]
+                        sequencenum = unpack(self.unpackShort, minfile[pos+4:pos+6])[0]
+                        codesop = " ".join([ "%02x" % ord(v) for v in minfile[pos+6:pos+12]])
+                        if codesop != "06 00 00 80 13 40" :
+                            raise pdlparser.PDLParserError, "Unfortunately SPL1 is incompletely recognized. Parsing aborted. Please report the problem to %s" % version.__authoremail__
+                        if not sequencenum :
+                            self.pagecount += 1
+                        pos += 4 + offset
+            except IndexError : # EOF ?            
+                pass
+        finally :
+            minfile.close()
+        return self.pagecount
+        
+if __name__ == "__main__" :    
+    pdlparser.test(Parser)
Index: pkpgcounter/tags/2.18/pkpgpdls/pclxl.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/pclxl.py (revision 456)
+++ pkpgcounter/tags/2.18/pkpgpdls/pclxl.py (revision 456)
@@ -0,0 +1,665 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a page counter for PCLXL (aka PCL6) documents."""
+
+import sys
+import os
+import mmap
+from struct import unpack
+
+import pdlparser
+import pjl
+
+class Parser(pdlparser.PDLParser) :
+    """A parser for PCLXL (aka PCL6) documents."""
+    totiffcommands = [ 'pcl6 -sDEVICE=pdfwrite -r%(dpi)i -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -sOutputFile=- - | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -', 
+                       'pcl6 -sDEVICE=pswrite -r%(dpi)i -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -sOutputFile=- - | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -',
+                     ]
+    mediasizes = { 
+                    0 : "Letter",
+                    1 : "Legal",
+                    2 : "A4",
+                    3 : "Executive",
+                    4 : "Ledger",
+                    5 : "A3",
+                    6 : "COM10Envelope",
+                    7 : "MonarchEnvelope",
+                    8 : "C5Envelope",
+                    9 : "DLEnvelope",
+                    10 : "JB4",
+                    11 : "JB5",
+                    12 : "B5Envelope",
+                    12 : "B5",
+                    14 : "JPostcard",
+                    15 : "JDoublePostcard",
+                    16 : "A5",
+                    17 : "A6",
+                    18 : "JB6",
+                    19 : "JIS8K",
+                    20 : "JIS16K",
+                    21 : "JISExec",
+                    96 : "Default",
+                 }   
+                 
+    mediasources = {             
+                     0 : "Default",
+                     1 : "Auto",
+                     2 : "Manual",
+                     3 : "MultiPurpose",
+                     4 : "UpperCassette",
+                     5 : "LowerCassette",
+                     6 : "EnvelopeTray",
+                     7 : "ThirdCassette",
+                   }
+                   
+    orientations = {               
+                     0 : "Portrait",
+                     1 : "Landscape",
+                     2 : "ReversePortrait",
+                     3 : "ReverseLandscape",
+                     4 : "Default",
+                   }
+            
+    def isValid(self) :    
+        """Returns True if data is PCLXL aka PCL6, else False."""
+        if ((self.firstblock[:128].find("\033%-12345X") != -1) and \
+             (self.firstblock.find(" HP-PCL XL;") != -1) and \
+             ((self.firstblock.find("LANGUAGE=PCLXL") != -1) or \
+              (self.firstblock.find("LANGUAGE = PCLXL") != -1))) :
+            self.logdebug("DEBUG: Input file is in the PCLXL (aka PCL6) format.")
+            return True
+        else :    
+            return False
+            
+    def beginPage(self, nextpos) :
+        """Indicates the beginning of a new page, and extracts media information."""
+        self.pagecount += 1
+        
+        # Default values
+        mediatypelabel = "Plain"
+        mediasourcelabel = "Main"
+        mediasizelabel = "Default"
+        orientationlabel = "Portrait"
+        duplexmode = None
+        
+        # Now go upstream to decode media type, size, source, and orientation
+        # this saves time because we don't need a complete parser !
+        minfile = self.minfile
+        pos = nextpos - 2
+        while pos > 0 : # safety check : don't go back to far !
+            val = ord(minfile[pos])
+            if val in (0x44, 0x48, 0x41) : # if previous endPage or openDataSource or beginSession (first page)
+                break
+            if val == 0x26 :    
+                mediasource = ord(minfile[pos - 2])
+                mediasourcelabel = self.mediasources.get(mediasource, str(mediasource))
+                pos -= 4
+            elif val == 0x25 :
+                while (pos > 0) and (ord(minfile[pos]) != 0xc0) :
+                    # we search the preceding ubyte tag
+                    pos -= 1
+                if pos > 0 :
+                    if ord(minfile[pos-1]) == 0xc8 :
+                        # if we found an ubyte_array then the media
+                        # size is completely spelled
+                        arraylength = ord(minfile[pos+1])
+                        mediasizelabel = minfile[pos+2:pos+2+arraylength].title()
+                        pos -= 1
+                    else :    
+                        # if we just found an ubyte, then the media
+                        # size is known by its index
+                        mediasize = ord(minfile[pos+1])
+                        mediasizelabel = self.mediasizes.get(mediasize, str(mediasize))
+                    pos -= 1 
+                    # self.logdebug("Media size : %s" % mediasizelabel)
+            elif val == 0x28 :    
+                orientation = ord(minfile[pos - 2])
+                orientationlabel = self.orientations.get(orientation, str(orientation))
+                pos -= 4
+            elif val == 0x27 :    
+                savepos = pos
+                pos -= 1
+                startpos = size = None 
+                while pos > 0 : # safety check : don't go back to far !
+                    val = ord(minfile[pos])
+                    pos -= 1    
+                    if val == 0xc8 :
+                        length = self.tags[ord(minfile[pos+2])] # will probably always be a byte or uint16
+                        if length == 1 :    
+                            startpos = pos + 4
+                            size = unpack("B", self.minfile[pos+3:startpos])[0]
+                        elif length == 2 :    
+                            startpos = pos + 5
+                            size = unpack(self.unpackShort, self.minfile[pos+3:startpos])[0]
+                        elif length == 4 :    
+                            startpos = pos + 7
+                            size = unpack(self.unpackLong, self.minfile[pos+3:startpos])[0]
+                        else :    
+                            raise pdlparser.PDLParserError, "Error on size at %s : %s" % (pos+2, length)
+                        break
+                mediatypelabel = minfile[startpos:startpos+size]
+                # self.logdebug("Media type : %s" % mediatypelabel)
+            elif val == 0x34 :    
+                duplexmode = "Simplex"
+                pos -= 2
+            elif val in (0x35, 0x36) :    
+                duplexmode = "Duplex"
+                pos -= 2
+            # else : TODO : CUSTOM MEDIA SIZE AND UNIT ! 
+            else :    
+                pos -= 1  # ignored
+        self.pages[self.pagecount] = { "copies" : 1, 
+                                       "orientation" : orientationlabel, 
+                                       "mediatype" : mediatypelabel, 
+                                       "mediasize" : mediasizelabel,
+                                       "mediasource" : mediasourcelabel,
+                                       "duplex" : duplexmode,
+                                     } 
+        return 0
+        
+    def endPage(self, nextpos) :    
+        """Indicates the end of a page."""
+        pos3 = nextpos - 3
+        minfile = self.minfile
+        if minfile[pos3:nextpos-1] == self.setNumberOfCopies :
+            # The EndPage operator may be preceded by a PageCopies attribute
+            # So set number of copies for current page.
+            # From what I read in PCLXL documentation, the number
+            # of copies is an unsigned 16 bits integer
+            try :
+                nbcopies = unpack(self.unpackShort, minfile[pos3-2:pos3])[0]
+                # self.logdebug("Number of copies : %i" % nbcopies)
+                self.pages[self.pagecount]["copies"] = nbcopies
+            except KeyError :    
+                self.logdebug("It looks like this PCLXL file is corrupted.")
+        return 0
+        
+    def setColorSpace(self, nextpos) :    
+        """Changes the color space."""
+        if self.minfile[nextpos-4:nextpos-1] == self.RGBColorSpace : # TODO : doesn't seem to handle all cases !
+            self.iscolor = 1
+        return 0
+            
+    def array_Generic(self, nextpos, size) :
+        """Handles all arrays."""
+        pos = nextpos
+        datatype = ord(self.minfile[pos])
+        pos += 1
+        length = self.tags[datatype]
+        if callable(length) :
+            length = length(pos)
+        try :
+            return 1 + length + size * unpack(self.unpackType[length], self.minfile[pos:pos+length])[0]
+        except KeyError :
+            raise pdlparser.PDLParserError, "Error on array size at %x" % nextpos
+            
+    def array_8(self, nextpos) :    
+        """Handles byte arrays."""
+        return self.array_Generic(nextpos, 1)
+        
+    def array_16(self, nextpos) :
+        """Handles 16 bits arrays."""
+        return self.array_Generic(nextpos, 2)
+        
+    def array_32(self, nextpos) :
+        """Handles 32 bits arrays."""
+        return self.array_Generic(nextpos, 4)
+        
+    def embeddedDataSmall(self, nextpos) :
+        """Handle small amounts of data."""
+        return 1 + ord(self.minfile[nextpos])
+        
+    def embeddedData(self, nextpos) :
+        """Handle normal amounts of data."""
+        return 4 + unpack(self.unpackLong, self.minfile[nextpos:nextpos+4])[0]
+        
+    def littleEndian(self, nextpos) :
+        """Toggles to little endianness."""
+        self.unpackType = { 1 : "B", 2 : "<H", 4 : "<I" }
+        self.unpackShort = self.unpackType[2]
+        self.unpackLong = self.unpackType[4]
+        return 0
+        
+    def bigEndian(self, nextpos) :
+        """Toggles to big endianness."""
+        self.unpackType = { 1 : "B", 2 : ">H", 4 : ">I" }
+        self.unpackShort = self.unpackType[2]
+        self.unpackLong = self.unpackType[4]
+        return 0
+    
+    def reservedForFutureUse(self, nextpos) :
+        """Outputs something when a reserved byte is encountered."""
+        self.logdebug("Byte at %x is out of the PCLXL Protocol Class 2.0 Specification" % nextpos)
+        return 0    
+        
+    def x46_class3(self, nextpos) :
+        """Undocumented tag 0x46 in class 3.0 streams."""
+        pos = nextpos - 3
+        minfile = self.minfile
+        val = ord(minfile[pos])
+        while val == 0xf8 :
+            funcid = ord(minfile[pos+1])
+            try :
+                offset = self.x46_functions[funcid]
+            except KeyError :    
+                self.logdebug("Unexpected subfunction 0x%02x for undocumented tag 0x46 at %x" % (funcid, nextpos))
+                break
+            else :    
+                pos -= offset
+                length = self.tags[ord(self.minfile[pos])]
+                if callable(length) :
+                    length = length(pos+1)
+                if funcid == 0x92 : # we want to skip these blocks
+                    try :
+                        return unpack(self.unpackType[length], self.minfile[pos+1:pos+length+1])[0]
+                    except KeyError :
+                        raise pdlparser.PDLParserError, "Error on size '%s' at %x" % (length, pos+1)
+            val = ord(minfile[pos])
+        return 0    
+        
+    def escape(self, nextpos) :    
+        """Handles the ESC code."""
+        pos = endpos = nextpos
+        minfile = self.minfile
+        if minfile[pos : pos+8] == r"%-12345X" :
+            endpos = pos + 9
+            endmark = chr(0x0c) + chr(0x00) + chr(0x1b)
+            asciilimit = chr(0x80)
+            quotes = 0
+            while (minfile[endpos] not in endmark) and \
+                   ((minfile[endpos] < asciilimit) or (quotes % 2)) :
+                if minfile[endpos] == '"' :
+                    quotes += 1
+                endpos += 1
+                
+            # Store this in a per page mapping.    
+            # NB : First time will be at page 0 (i.e. **before** page 1) !
+            stuff = self.escapedStuff.setdefault(self.pagecount, [])
+            stuff.append(minfile[pos : endpos])
+            self.logdebug("Escaped datas : [%s]" % repr(minfile[pos : endpos]))
+        return endpos - pos
+        
+    def skipKyoceraPrescribe(self, nextpos) :
+        """Skips Kyocera Prescribe commands."""
+        pos = nextpos - 1
+        minfile = self.minfile
+        if minfile[pos:pos+3] == "!R!" :
+            while (pos - nextpos) < 1024 :   # This is a realistic upper bound, to avoid infinite loops
+                if (minfile[pos] == ";") and (minfile[pos-4:pos] == "EXIT") :
+                    pos += 1
+                    prescribe = self.prescribeStuff.setdefault(self.pagecount, [])
+                    prescribe.append(minfile[nextpos-1:pos])
+                    self.logdebug("Prescribe commands : [%s]" % repr(minfile[nextpos-1:pos]))
+                    break
+                pos += 1    
+            return (pos - nextpos)
+        else :
+            return 0
+            
+    def getJobSize(self) :
+        """Counts pages in a PCLXL (PCL6) document.
+        
+           Algorithm by Jerome Alet.
+           
+           The documentation used for this was :
+         
+           HP PCL XL Feature Reference
+           Protocol Class 2.0
+           http://www.hpdevelopersolutions.com/downloads/64/358/xl_ref20r22.pdf 
+           
+           Protocol Class 2.1 Supplement
+           xl_ref21.pdf
+           
+           Protocol Class 3.0 Supplement
+           xl_refsup30r089.pdf
+        """
+        self.iscolor = None
+        found = False
+        while not found :
+            line = self.infile.readline()
+            if not line :
+                break
+            pos = line.find(" HP-PCL XL;")    
+            if pos != -1 :
+                found = True
+                endian = ord(line[pos - 1])
+                if endian == 0x29 :
+                    self.littleEndian(0)
+                elif endian == 0x28 :    
+                    self.bigEndian(0)
+                # elif endian == 0x27 : # TODO : This is the ESC code : parse it for PJL statements !
+                # 
+                else :    
+                    raise pdlparser.PDLParserError, "Unknown endianness marker 0x%02x at start !" % endian
+        if not found :
+            raise pdlparser.PDLParserError, "This file doesn't seem to be PCLXL (aka PCL6)"
+            
+        # Initialize Media Sources
+        for i in range(8, 256) :
+            self.mediasources[i] = "ExternalTray%03i" % (i - 7)
+            
+        # Initialize table of tags
+        self.tags = [ 0 ] * 256    
+        
+        self.tags[0x1b] = self.escape # The escape code
+        
+        self.tags[0x21] = self.skipKyoceraPrescribe # 0x21 is not normally used
+        
+        # GhostScript's sources tell us that HP printers
+        # only accept little endianness, but we can handle both.
+        self.tags[0x28] = self.bigEndian    # BigEndian
+        self.tags[0x29] = self.littleEndian # LittleEndian
+        
+        self.tags[0x43] = self.beginPage    # BeginPage
+        self.tags[0x44] = self.endPage      # EndPage
+        self.tags[0x45] = self.reservedForFutureUse # reserved
+        
+        self.tags[0x46] = self.x46_class3 
+        
+        self.tags[0x4a] = self.reservedForFutureUse # reserved
+        self.tags[0x4b] = self.reservedForFutureUse # reserved
+        self.tags[0x4c] = self.reservedForFutureUse # reserved
+        self.tags[0x4d] = self.reservedForFutureUse # reserved
+        self.tags[0x4e] = self.reservedForFutureUse # reserved
+        
+        self.tags[0x56] = self.reservedForFutureUse # TODO : documentation not clear about reserved status
+        
+        self.tags[0x57] = self.reservedForFutureUse # reserved
+        
+        self.tags[0x59] = self.reservedForFutureUse # reserved
+        self.tags[0x5a] = self.reservedForFutureUse # reserved
+        
+        self.tags[0x6a] = self.setColorSpace    # to detect color/b&w mode
+        
+        self.tags[0x87] = self.reservedForFutureUse # reserved
+        self.tags[0x88] = self.reservedForFutureUse # reserved
+        self.tags[0x89] = self.reservedForFutureUse # reserved
+        self.tags[0x8a] = self.reservedForFutureUse # reserved
+        
+        self.tags[0x8b] = self.reservedForFutureUse # reserved
+        
+        self.tags[0x8c] = self.reservedForFutureUse # reserved
+        self.tags[0x8d] = self.reservedForFutureUse # reserved
+        self.tags[0x8e] = self.reservedForFutureUse # reserved
+        self.tags[0x8f] = self.reservedForFutureUse # reserved
+        self.tags[0x90] = self.reservedForFutureUse # reserved
+        
+        self.tags[0x9a] = self.reservedForFutureUse # reserved
+        self.tags[0x9c] = self.reservedForFutureUse # reserved
+        
+        self.tags[0xa4] = self.reservedForFutureUse # reserved
+        self.tags[0xa5] = self.reservedForFutureUse # reserved
+        self.tags[0xa6] = self.reservedForFutureUse # reserved
+        self.tags[0xa7] = self.reservedForFutureUse # reserved
+        
+        self.tags[0xaa] = self.reservedForFutureUse # reserved
+        self.tags[0xab] = self.reservedForFutureUse # reserved
+        self.tags[0xac] = self.reservedForFutureUse # reserved
+        self.tags[0xad] = self.reservedForFutureUse # reserved
+        self.tags[0xae] = self.reservedForFutureUse # reserved
+        self.tags[0xaf] = self.reservedForFutureUse # reserved
+        
+        self.tags[0xb7] = self.reservedForFutureUse # reserved
+        
+        self.tags[0xba] = self.reservedForFutureUse # reserved
+        self.tags[0xbb] = self.reservedForFutureUse # reserved
+        self.tags[0xbc] = self.reservedForFutureUse # reserved
+        self.tags[0xbd] = self.reservedForFutureUse # reserved
+        self.tags[0xbe] = self.reservedForFutureUse # reserved
+        
+        # self.tags[0xbf] = self.passThrough # PassThrough mode should already be taken care of automatically
+        
+        self.tags[0xc0] = 1 # ubyte
+        self.tags[0xc1] = 2 # uint16
+        self.tags[0xc2] = 4 # uint32
+        self.tags[0xc3] = 2 # sint16
+        self.tags[0xc4] = 4 # sint32
+        self.tags[0xc5] = 4 # real32
+        
+        self.tags[0xc6] = self.reservedForFutureUse # reserved
+        self.tags[0xc7] = self.reservedForFutureUse # reserved
+        
+        self.tags[0xc8] = self.array_8  # ubyte_array
+        self.tags[0xc9] = self.array_16 # uint16_array
+        self.tags[0xca] = self.array_32 # uint32_array
+        self.tags[0xcb] = self.array_16 # sint16_array
+        self.tags[0xcc] = self.array_32 # sint32_array
+        self.tags[0xcd] = self.array_32 # real32_array
+        
+        self.tags[0xce] = self.reservedForFutureUse # reserved
+        self.tags[0xcf] = self.reservedForFutureUse # reserved
+        
+        self.tags[0xd0] = 2 # ubyte_xy
+        self.tags[0xd1] = 4 # uint16_xy
+        self.tags[0xd2] = 8 # uint32_xy
+        self.tags[0xd3] = 4 # sint16_xy
+        self.tags[0xd4] = 8 # sint32_xy
+        self.tags[0xd5] = 8 # real32_xy
+        self.tags[0xd6] = self.reservedForFutureUse # reserved
+        self.tags[0xd7] = self.reservedForFutureUse # reserved
+        self.tags[0xd8] = self.reservedForFutureUse # reserved
+        self.tags[0xd9] = self.reservedForFutureUse # reserved
+        self.tags[0xda] = self.reservedForFutureUse # reserved
+        self.tags[0xdb] = self.reservedForFutureUse # reserved
+        self.tags[0xdc] = self.reservedForFutureUse # reserved
+        self.tags[0xdd] = self.reservedForFutureUse # reserved
+        self.tags[0xde] = self.reservedForFutureUse # reserved
+        self.tags[0xdf] = self.reservedForFutureUse # reserved
+        
+        self.tags[0xe0] = 4  # ubyte_box
+        self.tags[0xe1] = 8  # uint16_box
+        self.tags[0xe2] = 16 # uint32_box
+        self.tags[0xe3] = 8  # sint16_box
+        self.tags[0xe4] = 16 # sint32_box
+        self.tags[0xe5] = 16 # real32_box
+        self.tags[0xe6] = self.reservedForFutureUse # reserved
+        self.tags[0xe7] = self.reservedForFutureUse # reserved
+        self.tags[0xe8] = self.reservedForFutureUse # reserved
+        self.tags[0xe9] = self.reservedForFutureUse # reserved
+        self.tags[0xea] = self.reservedForFutureUse # reserved
+        self.tags[0xeb] = self.reservedForFutureUse # reserved
+        self.tags[0xec] = self.reservedForFutureUse # reserved
+        self.tags[0xed] = self.reservedForFutureUse # reserved
+        self.tags[0xee] = self.reservedForFutureUse # reserved
+        self.tags[0xef] = self.reservedForFutureUse # reserved
+        
+        self.tags[0xf0] = self.reservedForFutureUse # reserved
+        self.tags[0xf1] = self.reservedForFutureUse # reserved
+        self.tags[0xf2] = self.reservedForFutureUse # reserved
+        self.tags[0xf3] = self.reservedForFutureUse # reserved
+        self.tags[0xf4] = self.reservedForFutureUse # reserved
+        self.tags[0xf5] = self.reservedForFutureUse # reserved
+        self.tags[0xf6] = self.reservedForFutureUse # reserved
+        self.tags[0xf7] = self.reservedForFutureUse # reserved
+        
+        self.tags[0xf8] = 1 # attr_ubyte
+        self.tags[0xf9] = 2 # attr_uint16
+        
+        self.tags[0xfa] = self.embeddedData      # dataLength
+        self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte
+        
+        self.tags[0xfc] = self.reservedForFutureUse # reserved
+        self.tags[0xfd] = self.reservedForFutureUse # reserved
+        self.tags[0xfe] = self.reservedForFutureUse # reserved
+        self.tags[0xff] = self.reservedForFutureUse # reserved
+            
+        # color spaces    
+        self.BWColorSpace = "".join([chr(0x00), chr(0xf8), chr(0x03)])
+        self.GrayColorSpace = "".join([chr(0x01), chr(0xf8), chr(0x03)])
+        self.RGBColorSpace = "".join([chr(0x02), chr(0xf8), chr(0x03)])
+        
+        # set number of copies
+        self.setNumberOfCopies = "".join([chr(0xf8), chr(0x31)]) 
+        
+        # subcodes for undocumented tag 0x46 and the negative
+        # offset to grab the value from.
+        self.x46_functions = { 0x91 : 5,
+                               0x92 : 5,
+                               0x93 : 3,
+                               0x94 : 3,
+                               0x95 : 5,
+                               0x96 : 2,
+                               0x97 : 2,
+                               0x98 : 2,
+                             }
+                             
+        infileno = self.infile.fileno()
+        self.pages = { 0 : { "copies" : 1, 
+                             "orientation" : "Default", 
+                             "mediatype" : "Plain", 
+                             "mediasize" : "Default", 
+                             "mediasource" : "Default", 
+                             "duplex" : None,
+                           } 
+                     }      
+        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
+        tags = self.tags
+        self.pagecount = 0
+        self.escapedStuff = {}   # For escaped datas, mostly PJL commands
+        self.prescribeStuff = {} # For Kyocera Prescribe commands
+        pos = oldpos = 0
+        try :
+            try :
+                while 1 :
+                    try :
+                        tag = ord(minfile[pos])
+                    except OverflowError :    
+                        pos = oldpos + 1
+                    pos += 1
+                    length = tags[tag]
+                    if length :
+                        if callable(length) :    
+                            length = length(pos)
+                        oldpos = pos    
+                        pos += length    
+            except IndexError : # EOF ?            
+                pass
+        finally :
+            self.minfile.close()
+            
+        # now handle number of copies for each page (may differ).
+        if self.iscolor :
+            colormode = "Color"
+        else :    
+            colormode = "BW"
+            
+        defaultduplexmode = "Simplex"
+        defaultpapersize = ""
+        defaultpjlcopies = 1    
+        oldpjlcopies = -1
+        oldduplexmode = ""
+        oldpapersize = ""
+        for pnum in range(1, self.pagecount + 1) :
+            # if no number of copies defined, take 1, as explained
+            # in PCLXL documentation.
+            # NB : is number of copies is 0, the page won't be output
+            # but the formula below is still correct : we want 
+            # to decrease the total number of pages in this case.
+            page = self.pages.get(pnum, self.pages.get(1, { "copies" : 1, "mediasize" : "Default", "duplex" : None }))
+            pjlstuff = self.escapedStuff.get(pnum, self.escapedStuff.get(0, []))
+            if pjlstuff :
+                pjlparser = pjl.PJLParser("".join(pjlstuff))
+                nbdefaultcopies = int(pjlparser.default_variables.get("COPIES", -1))
+                nbcopies = int(pjlparser.environment_variables.get("COPIES", -1))
+                nbdefaultqty = int(pjlparser.default_variables.get("QTY", -1))
+                nbqty = int(pjlparser.environment_variables.get("QTY", -1))
+                if nbdefaultcopies > -1 :
+                    defaultpjlcopies = nbdefaultcopies
+                if nbdefaultqty > -1 :
+                    defaultpjlcopies = nbdefaultqty
+                if nbcopies > -1 :
+                    pjlcopies = nbcopies
+                elif nbqty > -1 :
+                    pjlcopies = nbqty
+                else :
+                    if oldpjlcopies == -1 :    
+                        pjlcopies = defaultpjlcopies
+                    else :    
+                        pjlcopies = oldpjlcopies    
+                if page["duplex"] :        
+                    duplexmode = page["duplex"]
+                else :    
+                    defaultdm = pjlparser.default_variables.get("DUPLEX", "")
+                    if defaultdm :
+                        if defaultdm.upper() == "ON" :
+                            defaultduplexmode = "Duplex"
+                        else :    
+                            defaultduplexmode = "Simplex"
+                    envdm = pjlparser.environment_variables.get("DUPLEX", "")
+                    if envdm :
+                        if envdm.upper() == "ON" :
+                            duplexmode = "Duplex"
+                        else :    
+                            duplexmode = "Simplex"
+                    else :        
+                        if not oldduplexmode :
+                            duplexmode = defaultduplexmode
+                        else :    
+                            duplexmode = oldduplexmode
+                defaultps = pjlparser.default_variables.get("PAPER", "")
+                if defaultps :
+                    defaultpapersize = defaultps
+                envps = pjlparser.environment_variables.get("PAPER", "")
+                if envps :
+                    papersize = envps
+                else :    
+                    if not oldpapersize :
+                        papersize = defaultpapersize
+                    else :    
+                        papersize = oldpapersize
+            else :        
+                if oldpjlcopies == -1 :
+                    pjlcopies = defaultpjlcopies
+                else :    
+                    pjlcopies = oldpjlcopies
+                if not oldduplexmode :
+                    duplexmode = defaultduplexmode
+                else :    
+                    duplexmode = oldduplexmode
+                if not oldpapersize :    
+                    papersize = defaultpapersize
+                else :    
+                    papersize = oldpapersize
+                duplexmode = oldduplexmode
+                papersize = oldpapersize or page["mediasize"]
+            if page["mediasize"] != "Default" :
+                papersize = page["mediasize"]
+            if not duplexmode :    
+                duplexmode = oldduplexmode or defaultduplexmode
+            oldpjlcopies = pjlcopies    
+            oldduplexmode = duplexmode
+            oldpapersize = papersize
+            copies = max(pjlcopies, page["copies"]) # Was : pjlcopies * page["copies"]
+            self.pagecount += (copies - 1)
+            self.logdebug("%s*%s*%s*%s*%s*%s*%s" % (copies, 
+                                                 page["mediatype"], 
+                                                 papersize, 
+                                                 page["orientation"], 
+                                                 page["mediasource"], 
+                                                 duplexmode, 
+                                                 colormode))
+        return self.pagecount
+        
+if __name__ == "__main__" :    
+    pdlparser.test(Parser)
Index: pkpgcounter/tags/2.18/pkpgpdls/dvi.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/dvi.py (revision 443)
+++ pkpgcounter/tags/2.18/pkpgpdls/dvi.py (revision 443)
@@ -0,0 +1,78 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a page counter for DVI documents."""
+
+import sys
+import os
+import mmap
+from struct import unpack
+
+import pdlparser
+
+class Parser(pdlparser.PDLParser) :
+    """A parser for DVI documents."""
+    totiffcommands = [ 'cat >%(fname)s && dvips -q -o - %(fname)s | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -' ]
+    def isValid(self) :        
+        """Returns True if data is DVI, else False."""
+        try :
+            if (ord(self.firstblock[0]) == 0xf7) and (ord(self.lastblock[-1]) == 0xdf) :
+                self.logdebug("DEBUG: Input file is in the DVI format.")
+                return True
+            else :    
+                return False
+        except IndexError :          
+            return False
+            
+    def getJobSize(self) :
+        """Counts pages in a DVI document.
+        
+           Algorithm by Jerome Alet.
+           
+           The documentation used for this was :
+         
+           http://www.math.umd.edu/~asnowden/comp-cont/dvi.html
+        """
+        infileno = self.infile.fileno()
+        minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
+        pagecount = 0
+        pos = -1
+        eofchar = chr(0xdf)
+        postchar = chr(0xf8)
+        try :
+            while minfile[pos] == eofchar :
+                pos -= 1
+            idbyte = minfile[pos]    
+            if idbyte != minfile[1] :
+                raise IndexError, "Invalid DVI file."
+            pos = unpack(">I", minfile[pos - 4:pos])[0]
+            if minfile[pos] != postchar :
+                raise IndexError, "Invalid DVI file."
+            pagecount = unpack(">H", minfile[pos + 27: pos + 29])[0]
+        except IndexError : # EOF ?
+            pass
+        minfile.close() # reached EOF
+        return pagecount
+        
+if __name__ == "__main__" :    
+    pdlparser.test(Parser)
Index: pkpgcounter/tags/2.18/pkpgpdls/pjl.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/pjl.py (revision 455)
+++ pkpgcounter/tags/2.18/pkpgpdls/pjl.py (revision 455)
@@ -0,0 +1,139 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules implements a really minimalist PJL parser."""
+
+# NOTES : QTY= is the number of collated copies for a job.
+# NOTES : COPIES= is the number of uncollated copies for each page of a job
+
+import sys
+
+class PJLParserError(Exception):
+    """An exception for PJLParser related stuff."""
+    def __init__(self, message = ""):
+        self.message = message
+        Exception.__init__(self, message)
+    def __repr__(self):
+        return self.message
+    __str__ = __repr__
+        
+class PJLParser :
+    """A parser for PJL documents.
+    
+       Information extracted for bpl11897.pdf which was
+       downloaded from Hewlett-Packard's website.
+    
+       Only extracts the PJL SET variables. Ignore other statements.
+    """
+    def __init__(self, pjljob, debug=0) :
+        """Initializes PJL Parser."""
+        self.debug = debug
+        self.statements = pjljob.replace("\r\n", "\n").split("\n")
+        self.default_variables = {}
+        self.environment_variables = {}
+        self.parsed = 0
+        self.parse()
+        
+    def __str__(self) :    
+        """Outputs our variables as a string of text."""
+        if not self.parsed :
+            return ""
+        mybuffer = []
+        if self.default_variables :
+            mybuffer.append("Default variables :")
+            for (k, v) in self.default_variables.items() :
+                mybuffer.append("  %s : %s" % (k, v))
+        if self.environment_variables :        
+            mybuffer.append("Environment variables :")
+            for (k, v) in self.environment_variables.items() :
+                mybuffer.append("  %s : %s" % (k, v))
+        return "\n".join(mybuffer)        
+            
+    def logdebug(self, message) :    
+        """Logs a debug message if needed."""
+        if self.debug :
+            sys.stderr.write("%s\n" % message)
+            
+    def cleanvars(self) :        
+        """Cleans the variables dictionnaries."""
+        for dicname in ("default", "environment") :
+            varsdic = getattr(self, "%s_variables" % dicname)
+            for (k, v) in varsdic.items() :
+                if len(v) == 1 :
+                    varsdic[k] = v[0]
+        
+    def parse(self) :
+        """Parses a PJL job."""
+        for i in range(len(self.statements)) :
+            statement = self.statements[i]
+            if statement.startswith("@PJL") :
+                parts = statement.split()
+                nbparts = len(parts)
+                if parts[0] == "@PJL" :
+                    # this is a valid PJL statement, but we don't
+                    # want to examine all of them...
+                    if (nbparts > 2) and (parts[1].upper() in ("SET", "DEFAULT")) :
+                        # this is what we are interested in !
+                        try :    
+                            (varname, value) = "".join(parts[2:]).split("=", 1)
+                        except :    
+                            self.logdebug("Invalid PJL SET statement [%s]" % repr(statement))
+                        else :    
+                            # all still looks fine...
+                            if parts[1].upper() == "DEFAULT" :
+                                varsdic = self.default_variables
+                            else :    
+                                varsdic = self.environment_variables 
+                            variable = varsdic.setdefault(varname.upper(), [])
+                            variable.append(value)
+                    else :
+                        self.logdebug("Ignored PJL statement [%s]" % repr(statement))
+                else :
+                    self.logdebug("Invalid PJL statement [%s]" % repr(statement))
+            else :
+                self.logdebug("Invalid PJL statement [%s]" % repr(statement))
+        self.cleanvars()
+        self.parsed = 1
+        
+def test() :        
+    """Test function."""
+    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
+        sys.argv.append("-")
+    for arg in sys.argv[1:] :
+        if arg == "-" :
+            infile = sys.stdin
+            mustclose = 0
+        else :    
+            infile = open(arg, "rb")
+            mustclose = 1
+        try :
+            parser = PJLParser(infile.read(), debug=1)
+        except PJLParserError, msg :    
+            sys.stderr.write("ERROR: %s\n" % msg)
+            sys.stderr.flush()
+        if mustclose :    
+            infile.close()
+        print str(parser)            
+    
+if __name__ == "__main__" :    
+    test()
Index: pkpgcounter/tags/2.18/pkpgpdls/analyzer.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/analyzer.py (revision 459)
+++ pkpgcounter/tags/2.18/pkpgpdls/analyzer.py (revision 459)
@@ -0,0 +1,259 @@
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This is the main module of pkpgcounter.
+
+It defines the PDLAnalyzer class, which provides a generic way to parse
+input files, by automatically detecting the best parser to use."""
+
+import sys
+import os
+import tempfile
+
+import version, pdlparser, postscript, pdf, pcl345, pclxl, \
+       escp2, dvi, tiff, ooo, zjstream, qpdl, spl1, plain
+import inkcoverage
+
+class AnalyzerOptions :
+    """A class for use as the options parameter to PDLAnalyzer's constructor."""
+    def __init__(self, debug=None,
+                       colorspace=None,
+                       resolution=None) :
+        """Sets initial attributes."""
+        self.debug = debug
+        self.colorspace = colorspace
+        self.resolution = resolution
+    
+    
+class PDLAnalyzer :    
+    """Class for PDL autodetection."""
+    def __init__(self, filename, options=AnalyzerOptions()) :
+        """Initializes the PDL analyzer.
+        
+           filename is the name of the file or '-' for stdin.
+           filename can also be a file-like object which 
+           supports read() and seek().
+        """
+        self.options = options
+        self.filename = filename
+        self.infile = None
+        self.mustclose = None
+        
+    def getJobSize(self) :    
+        """Returns the job's size."""
+        size = 0
+        self.openFile()
+        try :
+            try :
+                pdlhandler = self.detectPDLHandler()
+                size = pdlhandler.getJobSize()
+            except pdlparser.PDLParserError, msg :    
+                raise pdlparser.PDLParserError, "Unknown file format for %s (%s)" % (self.filename, msg)
+        finally :    
+            self.closeFile()
+        return size
+            
+    def getInkCoverage(self, colorspace=None, resolution=None) :
+        """Extracts the percents of ink coverage from the input file."""
+        result = None
+        cspace = colorspace or self.options.colorspace
+        res = resolution or self.options.resolution
+        if (not cspace) or (not res) :
+            raise ValueError, "Invalid colorspace (%s) or resolution (%s)" % (cspace, res)
+        self.openFile()
+        try :
+            try :
+                pdlhandler = self.detectPDLHandler()
+                (handle, filename) = tempfile.mkstemp(".tmp", "pkpgcounter")    
+                os.close(handle)
+                try :
+                    pdlhandler.convertToTiffMultiPage24NC(filename, self.options.resolution)
+                    result = inkcoverage.getInkCoverage(filename, cspace)
+                finally :    
+                    try :
+                        os.remove(filename)
+                    except OSError :
+                        sys.stderr.write("Problem when trying to remove temporary file %s\n" % filename)
+            except pdlparser.PDLParserError, msg :    
+                raise pdlparser.PDLParserError, "Unknown file format for %s (%s)" % (self.filename, msg)
+        finally :    
+            self.closeFile()
+        return result
+        
+    def openFile(self) :    
+        """Opens the job's data stream for reading."""
+        self.mustclose = 0  # by default we don't want to close the file when finished
+        if hasattr(self.filename, "read") and hasattr(self.filename, "seek") :
+            # filename is in fact a file-like object 
+            infile = self.filename
+        elif self.filename == "-" :
+            # we must read from stdin
+            infile = sys.stdin
+        else :    
+            # normal file
+            self.infile = open(self.filename, "rbU")
+            self.mustclose = 1
+            return
+            
+        # Use a temporary file, always seekable contrary to standard input.
+        self.infile = tempfile.TemporaryFile(mode="w+b") # TODO : not opened in universal newline mode, Python 2.5 refuses.
+        while 1 :
+            data = infile.read(pdlparser.MEGABYTE) 
+            if not data :
+                break
+            self.infile.write(data)
+        self.infile.flush()    
+        self.infile.seek(0)
+            
+    def closeFile(self) :        
+        """Closes the job's data stream if we can close it."""
+        if self.mustclose :
+            self.infile.close()    
+        else :    
+            # if we don't have to close the file, then
+            # ensure the file pointer is reset to the 
+            # start of the file in case the process wants
+            # to read the file again.
+            try :
+                self.infile.seek(0)
+            except IOError :    
+                pass    # probably stdin, which is not seekable
+        
+    def detectPDLHandler(self) :    
+        """Tries to autodetect the document format.
+        
+           Returns the correct PDL handler class or None if format is unknown
+        """   
+        # Try to detect file type by reading first and last blocks of datas    
+        # Each parser can read them automatically, but here we do this only once.
+        self.infile.seek(0)
+        firstblock = self.infile.read(pdlparser.FIRSTBLOCKSIZE)
+        try :
+            self.infile.seek(-pdlparser.LASTBLOCKSIZE, 2)
+            lastblock = self.infile.read(pdlparser.LASTBLOCKSIZE)
+        except IOError :    
+            lastblock = ""
+        self.infile.seek(0)
+        if not firstblock :
+            raise pdlparser.PDLParserError, "input file %s is empty !" % str(self.filename)
+        else :    
+            # IMPORTANT : the order is important below. FIXME.
+            for module in (postscript, \
+                           pclxl, \
+                           pdf, \
+                           qpdl, \
+                           spl1, \
+                           dvi, \
+                           tiff, \
+                           zjstream, \
+                           ooo, \
+                           pcl345, \
+                           escp2, \
+                           plain) :     # IMPORTANT : don't move this one up !
+                try :               
+                    return module.Parser(self.infile, self.options.debug, firstblock, lastblock)
+                except pdlparser.PDLParserError :
+                    pass # try next parser
+        raise pdlparser.PDLParserError, "Analysis of first data block failed."
+            
+def main() :    
+    """Entry point for PDL Analyzer."""
+    import optparse
+    from copy import copy
+    
+    def check_cichoice(option, opt, value) :
+        """To add a CaseIgnore Choice option type."""
+        valower = value.lower()
+        if valower in [v.lower() for v in option.cichoices] :
+            return valower
+        else :    
+            choices = ", ".join([repr(o) for o in option.cichoices])
+            raise optparse.OptionValueError(
+                "option %s: invalid choice: %r (choose from %s)"
+                % (opt, value, choices))
+    
+    class MyOption(optparse.Option) :
+        """New Option class, with CaseIgnore Choice type."""
+        TYPES = optparse.Option.TYPES + ("cichoice",)
+        ATTRS = optparse.Option.ATTRS + ["cichoices"]
+        TYPE_CHECKER = copy(optparse.Option.TYPE_CHECKER)
+        TYPE_CHECKER["cichoice"] = check_cichoice
+        
+    parser = optparse.OptionParser(option_class=MyOption, 
+                                   usage="python analyzer.py [options] file1 [file2 ...]")
+    parser.add_option("-v", "--version", 
+                            action="store_true", 
+                            dest="version",
+                            help="Show pkpgcounter's version number and exit.")
+    parser.add_option("-d", "--debug", 
+                            action="store_true", 
+                            dest="debug",
+                            help="Activate debug mode.")
+    parser.add_option("-c", "--colorspace", 
+                            dest="colorspace",
+                            type="cichoice",
+                            cichoices=["bw", "rgb", "cmyk", "cmy", "gc"],
+                            help="Activate the computation of ink usage, and defines the colorspace to use. Supported values are 'BW', 'RGB', 'CMYK', 'CMY', and 'GC'.")
+    parser.add_option("-r", "--resolution", 
+                            type="int", 
+                            default=72, 
+                            dest="resolution",
+                            help="The resolution in DPI to use when checking ink usage. Lower resolution is faster but less accurate. Default is 72 dpi.")
+    (options, arguments) = parser.parse_args()
+    if options.version :
+        print "%s" % version.__version__
+    elif not (72 <= options.resolution <= 1200) :    
+        sys.stderr.write("ERROR: the argument to the --resolution command line option must be between 72 and 1200.\n")
+        sys.stderr.flush()
+    else :
+        if (not arguments) or ((not sys.stdin.isatty()) and ("-" not in arguments)) :
+            arguments.append("-")
+        totalsize = 0    
+        lines = []
+        try :
+            for arg in arguments :
+                try :
+                    parser = PDLAnalyzer(arg, options)
+                    if not options.colorspace :
+                        totalsize += parser.getJobSize()
+                    else :
+                        (cspace, pages) = parser.getInkCoverage()
+                        for page in pages :
+                            lineparts = []
+                            for k in cspace : # NB : this way we preserve the order of the planes
+                                try :
+                                    lineparts.append("%s : %s%%" % (k, ("%f" % page[k]).rjust(10)))
+                                except KeyError :
+                                    pass
+                            lines.append("      ".join(lineparts))     
+                except (IOError, pdlparser.PDLParserError), msg :    
+                    sys.stderr.write("ERROR: %s\n" % msg)
+                    sys.stderr.flush()
+        except KeyboardInterrupt :            
+            sys.stderr.write("WARN: Aborted at user's request.\n")
+            sys.stderr.flush()
+        if not options.colorspace :    
+            print "%s" % totalsize
+        else :    
+            print "\n".join(lines)
+    
+if __name__ == "__main__" :    
+    main()
Index: pkpgcounter/tags/2.18/pkpgpdls/version.py
===================================================================
--- pkpgcounter/tags/2.18/pkpgpdls/version.py (revision 459)
+++ pkpgcounter/tags/2.18/pkpgpdls/version.py (revision 459)
@@ -0,0 +1,46 @@
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+
+"""This modules defines some important constants used in this software."""
+
+
+__version__ = "2.18"
+
+__doc__ = """pkpgcounter : a generic Page Description Languages parser."""
+
+__author__ = "Jerome Alet"
+__authoremail__ = "alet@librelogiciel.com"
+__years__ = "2003, 2004, 2005, 2006, 2007"
+
+__gplblurb__ = """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 2 of the License, 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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA."""
+
Index: pkpgcounter/tags/2.18/setup.py
===================================================================
--- pkpgcounter/tags/2.18/setup.py (revision 443)
+++ pkpgcounter/tags/2.18/setup.py (revision 443)
@@ -0,0 +1,74 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+#
+
+import sys
+import glob
+import os
+import shutil
+try :
+    from distutils.core import setup
+except ImportError, msg :    
+    sys.stderr.write("%s\n" % msg)
+    sys.stderr.write("You need the DistUtils Python module.\nunder Debian, you may have to install the python-dev package.\nOf course, YMMV.\n")
+    sys.exit(-1)
+    
+try :    
+    from PIL import Image
+except ImportError :    
+    sys.stderr.write("You need the Python Imaging Library (aka PIL).\nYou can grab it from http://www.pythonware.com\n")
+    sys.exit(-1)
+    
+try :    
+    import psyco
+except ImportError :    
+    sys.stderr.write("WARN: If you are running on a 32 Bits x86 platform, you should install the Python Psyco module if possible, this would greatly speedup parsing. NB : Psyco doesn't work on other platforms, so don't worry if you're in this case.\n")
+    
+sys.path.insert(0, "pkpgpdls")
+from pkpgpdls.version import __version__, __doc__
+
+data_files = []
+mofiles = glob.glob(os.sep.join(["po", "*", "*.mo"]))
+for mofile in mofiles :
+    lang = mofile.split(os.sep)[1]
+    directory = os.sep.join(["share", "locale", lang, "LC_MESSAGES"])
+    data_files.append((directory, [ mofile ]))
+    
+docdir = "share/doc/pkpgcounter"    
+docfiles = ["README", "COPYING", "BUGS", "CREDITS", "NEWS"]
+data_files.append((docdir, docfiles))
+
+directory = os.sep.join(["share", "man", "man1"])
+manpages = glob.glob(os.sep.join(["man", "*.1"]))    
+data_files.append((directory, manpages))
+
+setup(name = "pkpgcounter", version = __version__,
+      license = "GNU GPL",
+      description = __doc__,
+      author = "Jerome Alet",
+      author_email = "alet@librelogiciel.com",
+      url = "http://www.pykota.com/software/pkpgcounter/",
+      packages = [ "pkpgpdls" ],
+      scripts = [ "bin/pkpgcounter" ],
+      data_files = data_files)
+      
Index: pkpgcounter/tags/2.18/COPYING
===================================================================
--- pkpgcounter/tags/2.18/COPYING (revision 211)
+++ pkpgcounter/tags/2.18/COPYING (revision 211)
@@ -0,0 +1,340 @@
+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+                       51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+			    NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+	    How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    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 2 of the License, 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.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Library General
+Public License instead of this License.
Index: pkpgcounter/tags/2.18/bin/pkpgcounter
===================================================================
--- pkpgcounter/tags/2.18/bin/pkpgcounter (revision 443)
+++ pkpgcounter/tags/2.18/bin/pkpgcounter (revision 443)
@@ -0,0 +1,103 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+#
+#
+
+import sys
+from pkpgpdls.version import __version__, __author__, __authoremail__, \
+                                __years__, __gplblurb__
+from pkpgpdls import analyzer
+
+__doc__ = """pkpgcounter v%(__version__)s (c) %(__years__)s %(__author__)s
+
+pkpgcounter is a generic Page Description Language parser.
+
+pkpgcounter parses any number of input files and/or its standard input
+and outputs the number of pages needed to print these documents.
+
+pkpgcounter can also compute the percent of ink coverage in different
+colorspaces for several file formats.
+
+pkpgcounter currently recognizes the following document formats :
+
+    * PostScript (both DSC compliant and binary)
+    * PDF   
+    * PCLXL (aka PCL6)
+    * PCL3/4/5 (mostly)
+    * DVI
+    * Plain text
+    * TIFF
+    * ESC/P2
+    * OpenDocument (ISO/IEC DIS 26300)
+    * Zenographics ZjStream
+    * Samsung QPDL (aka SPL2)
+    * Samsung SPL1
+
+The five latter ones, as well as some TIFF documents, are currently 
+only supported in page counting mode. 
+
+command line usage :
+
+  pkpgcounter [options] [files]
+
+options :
+
+  -v | --version        Prints pkpgcounter's version number then exits.
+  -h | --help           Prints this message then exits.
+  
+  -d | --debug          Activate debug mode. 
+  
+  -cCOLORSPACE, --colorspace=COLORSPACE
+                        Activate the computation of ink usage, and defines the
+                        colorspace to use. Supported values are 'BW' (Black),
+                        'RGB', 'CMYK', 'CMY', and 'GC' (Grayscale vs Color).
+                        'GC' is useful if you only need to differentiate 
+                        grayscale pages from coloured pages but don't care
+                        about ink usage per se.
+                        
+  -rRESOLUTION, --resolution=RESOLUTION
+                        The resolution in DPI to use when checking ink usage.
+                        Lower resolution is faster but less accurate. Default
+                        is 72 dpi.
+  
+examples :                              
+
+  $ pkpgcounter file1.ps file2.escp2 file3.pclxl <file4.pcl345
+  
+  Will launch pkpgcounter and will output the total number of pages
+  needed to print all the documents specified.
+  
+  $ pkpgcounter --colorspace bw --resolution 150 file1.ps
+  
+  Will output the percent of black ink needed on each page of
+  the file1.ps file rendered at 150 dpi.
+  
+%(__gplblurb__)s  
+
+Please e-mail bugs to: %(__authoremail__)s"""
+
+if __name__ == "__main__" : 
+    if (len(sys.argv) >= 2) and (sys.argv[1] in ("-h", "--help")) :
+        print __doc__ % globals()
+    else :    
+        analyzer.main()
+
Index: pkpgcounter/tags/2.18/MANIFEST.in
===================================================================
--- pkpgcounter/tags/2.18/MANIFEST.in (revision 383)
+++ pkpgcounter/tags/2.18/MANIFEST.in (revision 383)
@@ -0,0 +1,3 @@
+include README FAQ COPYING BUGS TODO NEWS CREDITS MANIFEST.in clean.sh bin/pkpgcounter
+recursive-include man README *.sh *.1
+recursive-include tests README *.ps.gz *.sh *.py colors.pdf
Index: pkpgcounter/tags/2.18/clean.sh
===================================================================
--- pkpgcounter/tags/2.18/clean.sh (revision 235)
+++ pkpgcounter/tags/2.18/clean.sh (revision 235)
@@ -0,0 +1,30 @@
+#! /bin/sh
+#
+# pkpgcounter : a generic Page Description Language parser
+#
+# (c) 2003, 2004, 2005 Jerome Alet <alet@librelogiciel.com>
+# 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 2 of the License, 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.
+# 
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# $Id$
+
+# Use this to clean the tree from temporary files
+
+rm -f MANIFEST
+rm -fr build dist
+find . -name "*.bak" -exec rm -f {} \;
+find . -name "*~" -exec rm -f {} \;
+find . -name "*.pyc" -exec rm -f {} \;
+find . -name "*.pyo" -exec rm -f {} \;
+find . -name "*.jem" -exec rm -f {} \;
Index: pkpgcounter/tags/2.18/man/pkpgcounter.1
===================================================================
--- pkpgcounter/tags/2.18/man/pkpgcounter.1 (revision 459)
+++ pkpgcounter/tags/2.18/man/pkpgcounter.1 (revision 459)
@@ -0,0 +1,88 @@
+.\" DO NOT MODIFY THIS FILE!  It was generated by help2man 1.36.
+.TH PKPGCOUNTER "1" "July 2007" "C@LL - Conseil Internet & Logiciels Libres" "User Commands"
+.SH NAME
+pkpgcounter \- manual page for pkpgcounter 2.18
+.SH DESCRIPTION
+pkpgcounter v2.18 (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet
+.PP
+pkpgcounter is a generic Page Description Language parser.
+.PP
+pkpgcounter parses any number of input files and/or its standard input
+and outputs the number of pages needed to print these documents.
+.PP
+pkpgcounter can also compute the percent of ink coverage in different
+colorspaces for several file formats.
+.PP
+pkpgcounter currently recognizes the following document formats :
+.IP
+* PostScript (both DSC compliant and binary)
+* PDF
+* PCLXL (aka PCL6)
+* PCL3/4/5 (mostly)
+* DVI
+* Plain text
+* TIFF
+* ESC/P2
+* OpenDocument (ISO/IEC DIS 26300)
+* Zenographics ZjStream
+* Samsung QPDL (aka SPL2)
+* Samsung SPL1
+.PP
+The five latter ones, as well as some TIFF documents, are currently
+only supported in page counting mode.
+.PP
+command line usage :
+.IP
+pkpgcounter [options] [files]
+.PP
+options :
+.TP
+\fB\-v\fR | \fB\-\-version\fR
+Prints pkpgcounter's version number then exits.
+.TP
+\fB\-h\fR | \fB\-\-help\fR
+Prints this message then exits.
+.TP
+\fB\-d\fR | \fB\-\-debug\fR
+Activate debug mode.
+.TP
+\fB\-cCOLORSPACE\fR, \fB\-\-colorspace\fR=\fICOLORSPACE\fR
+Activate the computation of ink usage, and defines the
+colorspace to use. Supported values are 'BW' (Black),
+\&'RGB', 'CMYK', 'CMY', and 'GC' (Grayscale vs Color).
+\&'GC' is useful if you only need to differentiate
+grayscale pages from coloured pages but don't care
+about ink usage per se.
+.TP
+\fB\-rRESOLUTION\fR, \fB\-\-resolution\fR=\fIRESOLUTION\fR
+The resolution in DPI to use when checking ink usage.
+Lower resolution is faster but less accurate. Default
+is 72 dpi.
+.PP
+examples :
+.IP
+\f(CW$ pkpgcounter file1.ps file2.escp2 file3.pclxl <file4.pcl345\fR
+.IP
+Will launch pkpgcounter and will output the total number of pages
+needed to print all the documents specified.
+.IP
+\f(CW$ pkpgcounter --colorspace bw --resolution 150 file1.ps\fR
+.IP
+Will output the percent of black ink needed on each page of
+the file1.ps file rendered at 150 dpi.
+.PP
+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 2 of the License, or
+(at your option) any later version.
+.PP
+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.
+.PP
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110\-1301, USA.
+.PP
+Please e\-mail bugs to: alet@librelogiciel.com
Index: pkpgcounter/tags/2.18/man/genman.sh
===================================================================
--- pkpgcounter/tags/2.18/man/genman.sh (revision 443)
+++ pkpgcounter/tags/2.18/man/genman.sh (revision 443)
@@ -0,0 +1,20 @@
+#! /bin/sh
+#
+# pkpgcounter : a generic Page Description Language parser.
+#
+# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+# You're welcome to redistribute this software under the
+# terms of the GNU General Public Licence version 2.0
+# or, at your option, any higher version.
+#
+# You can read the complete GNU GPL in the file COPYING
+# which should come along with this software, or visit
+# the Free Software Foundation's WEB site http://www.fsf.org
+#
+# $Id$
+#
+for prog in pkpgcounter ; do 
+    echo $prog ;
+    help2man --no-info --section=1 --manual "User Commands" --source="C@LL - Conseil Internet & Logiciels Libres" --output=$prog.1 $prog ; 
+    echo ;
+done
Index: pkpgcounter/tags/2.18/NEWS
===================================================================
--- pkpgcounter/tags/2.18/NEWS (revision 456)
+++ pkpgcounter/tags/2.18/NEWS (revision 456)
@@ -0,0 +1,281 @@
+# $Id$
+
+pkpgcounter : a generic Page Description Language parser
+
+(c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+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 2 of the License, 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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+=============================================================================
+
+pkpgcounter News :
+
+  * 2.17 : 
+  
+    - Fixed problems in the handling of PJL number of copies (COPIES= and QTY=)
+      which caused the number of copies for each page to be squared.
+    
+  * 2.16 : 
+  
+    - Fixed a problem in the PCL3/4/5 parser to accomodate line based
+      report generators which expect the printer to skip to next page
+      based on lines per page instead of sending a specific command.
+      
+  * 2.15 :
+   
+    - Fixed a regexp in the PDF parser which caused some files to be
+      incorrectly accounted for.
+    
+    - Improved the detection of the number of copies in PostScript documents.
+    
+  * 2.14 :
+  
+    - Fixed a problem with some PS drivers which don't output %%Page:
+      comments.
+      
+  * 2.13 : 
+   
+    - Nowrecognizes the GC colorspace if you only want to differentiate
+      grayscale pages from coloured pages. In this colorspace, the
+      percents are always "G : 100.0   C : 0.0" or "G : 0.0   C : 100.0"
+      respectively for a grayscale page and a coloured page.
+  
+  * 2.12 :
+  
+    - Fixed a problem with the PostScript parser.
+    
+  * 2.11 :
+  
+    - Improved overall robustness in ink accounting mode.
+    
+  * 2.10 :
+  
+    - Added a plain text parser, with support for both page counting and
+      ink coverage.
+    
+    - Added a minimal SPL1 parser.
+    
+    - Fixed a problem in the PCLXL parser related to Kyocera printer drivers.
+    
+  * 2.00 :
+  
+    - The PCL3/4/5 parser was rewritten from scratch and is now
+      table driven.
+      
+    - Improved the PostScript parser.
+    
+  * 1.85 :
+  
+    - Added support for Samsung QPDL (aka SPL2) file format in page
+      counting mode, thanks to the work done by Aur�en Croc on
+      reverse engineering the file format.
+      
+  * 1.85alpha :
+  
+    - Added test document and program to generate the test document
+      to check the functionning of the ink coverage computation algorithm.
+      
+  * 1.84 :
+  
+    - Computation of ink coverage now works and is documented.
+      The supported file formats are : PS, PDF, PCLXL, PCL3/4/5,
+      DVI and TIFF.
+      
+  * 1.84alpha :
+  
+    - Added initial support for the computation of ink coverage.
+      See python analyzer.py --help for details. The same command
+      line options work for pkpgcounter, although it's not
+      documented yet.
+    
+  * 1.83 :
+  
+    - Fixed a famously known 'brown paper bag' issue with file type autodetection. 
+    
+  * 1.82 :
+  
+    - Fixed PCL3/4/5 parser to detect recent Xerox drivers' output. 
+    
+  * 1.81 :
+  
+    - Improved the gs+Acrobat Reader fix done in 1.78.
+    
+  * 1.80 :
+  
+    - Added support for Zenographics ZjStream input format.
+    
+  * 1.79 :
+  
+    - Fixed a small problem in PostScript parser with dvips output.
+    
+  * 1.78 :
+  
+    - Launches gs less often when printing is done from Acrobat
+      Reader.
+    
+  * 1.77 : 
+  
+    - Fixed some problems with the code introduced in 1.76.
+    
+    - Improved PCLXL parser's speed by almost 10%.
+    
+  * 1.76 :
+  
+    - Improved the PCLXL parser wrt undocumented tags.
+    
+    - Preliminary support for Kyocera Prescribe commands.
+    
+  * 1.75 :
+  
+    - Added preliminary support for Canon ImageRunner's "LIPS" or "UFR"
+      (I don't know which) Page Description Language. 
+      
+  * 1.74 :
+  
+    - Fixed a problem in the retrieval of named media sizes in PCLXL.
+    
+    - Changed copyright years.
+    
+  * 1.73 :
+  
+    - Fixed duplex detection code in PCL3/4/5 parser.
+    
+    - Fixed PCLXL detection code.
+    
+    - Fixed retrieval of custom media types' names in PCLXL.
+    
+    - Added inactive code to compute ink coverage ala PrintBill.
+    
+  * 1.72 :
+  
+    - Improved heuristic to detect when ghostscript has to be used to do
+      the parsing.
+   
+  * 1.71 :
+  
+    - Now uses ghostscript as the parser when the PS stream was created by a
+      particular MSWindows driver.
+    
+    - Only complains about Psyco missing at install time, and stays
+      quiet when running without Psyco.
+      
+  * 1.70 :
+  
+    - Fixed some PJL escaping issue in the PCLXL and PCL3/4/5 parsers.
+    
+  * 1.69 :
+  
+    - Improved PCL3/4/5 parser.
+    
+    - Improved PCLXL parser wrt PJL stuff.
+    
+  * 1.68 :
+  
+    - Improved PostScript parser.
+    
+  * 1.67 :
+  
+    - Improved PostScript parser.
+    
+    - Improved PCL3/4/5 parser.
+    
+  * 1.66 : 
+  
+    - Improved PCLXL parser.
+    
+    - Improved PCL3/4/5 parser.
+    
+  * 1.65 :
+    
+    - Improved PostScript parser.
+    
+    - Improved PCL3/4/5 parser.
+    
+  * 1.64 :
+    
+    - Improved PCL3/4/5 parser.
+    
+  * 1.63 :
+  
+    - Now handles PJL statements to extract number of copies, duplex mode
+      and paper size in the PCLXL and PCL3/4/5 parsers.
+    
+  * 1.62 :
+  
+    - Better handling of the number of copies in the PCLXL parser.
+    
+    - Better handling of the number of copies in the PCL3/4/5 parser.
+      
+  * 1.61 :
+  
+    - Improved PCL3/4/5 parser.
+    
+    - Better handling of the number of copies in the PostScript parser.
+      Now the number can be different from page to page.
+    
+  * 1.60 : 
+  
+    - Improved PCLXL parser.
+    
+  * 1.59 :
+    
+    - Major rewrite of the PDF parser to correctly handle all line endings.
+      
+  * 1.58 :
+  
+    - Fix for PDF files which contain several versions of the same PDF object.
+    
+    - Doesn't break when python-psyco is not available.
+    
+  * 1.57 : 
+  
+    - Fixed a recently introduced bug in binary postscript handling code.  
+    
+  * 1.56 :
+  
+    - Renamed the library from pdlanalyzer into pkpgpdls to avoid problems
+      when the code will be integrated back into PyKota.
+      
+  * 1.55 : 
+  
+    - Added support for OpenOffice.org Writer and Impress documents.
+    
+  * 1.54 :
+   
+    - Added online documentation and a manual page.
+    
+  * 1.53 : 
+  
+    - Moved code around to improve maintainability.
+    
+  * 1.52 : 
+  
+    - Added support for the TIFF format.
+    
+  * 1.51 : 
+  
+    - Added support for the DVI format.
+    
+  * 1.50 :
+  
+    - Major code changes to modularize. The pkpgcounter command line tool
+      is now just an almost empty skeleton, which uses the pdlanalyzer
+      library.
+      
+    - Several improvements to the parsing code.  
+      
+  * 1.00 :
+
+    - First release.
+
Index: pkpgcounter/tags/2.18/CREDITS
===================================================================
--- pkpgcounter/tags/2.18/CREDITS (revision 459)
+++ pkpgcounter/tags/2.18/CREDITS (revision 459)
@@ -0,0 +1,51 @@
+# $Id$
+
+pkpgcounter : a generic Page Description Language parser
+
+(c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+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 2 of the License, 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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+============================================================
+
+The following people helped the pkpgcounter project :
+  
+  
+  - Eduardo Gielamo Oliveira & Rodolfo Broco Manin : initial PCL parser.
+  
+  - Valcir C. Vargas : helped on PCL3GUI support.
+  
+  - Daniel Franklin : pkpgcounter's algorithm for the computation 
+    of ink coverage comes from Daniel's PrintBill project.
+    
+  - Aur�en Croc : reverse engineered Samsung QPDL and published  
+                    a language specification.
+
+  - Franck (?) : sent a path to improve the PostScript parser when
+                 the PS code generated several copies.
+                 
+  - Yves Lavoie : reported a bug with Python 2.5                 
+
+==============================================================
+
+  IF YOUR NAME DOESN'T APPEAR IN THE LISTS ABOVE, AND YOU
+  THINK YOU DESERVE TO BE LISTED, JUST SEND ME AN EMAIL
+  ASKING FOR BEING INCLUDED.
+  
+  I APOLOGIZE IN ADVANCE IF I'VE FORGOTTEN TO ADD YOUR NAME.
+  
+  ALSO, SOME PEOPLE MAY HAVE REFUSED TO BE LISTED HERE, THIS 
+  IS YOUR RIGHT TO DO SO TOO, JUST TELL ME.
+  
+==============================================================
Index: pkpgcounter/tags/2.18/README
===================================================================
--- pkpgcounter/tags/2.18/README (revision 443)
+++ pkpgcounter/tags/2.18/README (revision 443)
@@ -0,0 +1,163 @@
+# $Id$
+
+pkpgcounter : a generic Page Description Language parser
+
+(c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
+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 2 of the License, 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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+=============================================================================
+
+pkpgcounter is a generic Page Description Language parser which can either
+compute the number of pages in a document, or compute the percent of
+ink coverage needed to print each page, in different colorspaces.
+
+pkpgcounter currently recognizes the following document formats :
+
+        - PostScript (both DSC compliant and binary)
+        
+        - PDF
+        
+        - PCL3/4/5
+        
+        - PCLXL (aka PCL6)
+        
+        - DVI
+        
+        - Plain text
+        
+        - TIFF
+        
+        - ESC/P2
+        
+        - OpenDocument (ISO/IEC DIS 26300)
+        
+        - Zenographics ZjStream
+        
+        - Samsung QPDL (aka SPL2)
+        
+        - Samsung SPL1
+        
+The five latter ones, as well as some TIFF documents, are currently 
+only supported in page counting mode. 
+
+By default, when launched pkpgcounter prints on its standard output 
+a single integer representing the total number of pages in all the 
+files which filenames you've passed on the command line. 
+
+With no argument, or with a single dash in non-option arguments,
+pkpgcounter reads datas to parse from its standard input in addition
+to other non-options arguments which are treated as filenames
+representing the files to parse.
+
+See pkpgcounter --help for details and examples.
+
+=============================================================================
+
+Installation :
+--------------
+
+  0 - Download pkpgcounter from :
+  
+        http://www.pykota.com/software/pkpgcounter/download
+        
+      and extract it :  
+      
+        $ tar -zxf pkpgcounter-x.yy.tar.gz
+        
+        where x.yy is pkpgcounter' version number.
+        
+  1 - Run the installation script :
+      
+        $ python setup.py install
+        
+      This will usually install the pkpgcounter into /usr/bin and  
+      the library into /usr/lib/python2.?/site-packages/pkpgpdls/
+        
+  2 - Use pkpgcounter :
+  
+      $ pkpgcounter file1.ps file2.pclxl ... <fileN.escp2
+      
+      pkpgcounter will display the total size in pages of all the files
+      passed on the command line.
+      
+      $ pkpgcounter --colorspace bw --resolution 150 file1.ps
+  
+      Will output the percent of black ink needed on each page of
+      the file1.ps file rendered at 150 dpi.
+      
+  3 - That's all !    
+  
+  
+IMPORTANT : To compute ink coverage, pkpgcounter relies on third party
+software which must be installed. These third party software are :
+
+        - GhostScript (this one is needed for all file formats).
+        
+        - The Python Imaging Library, aka PIL (this one is needed for all
+          file formats).
+        
+        - GhostPCL (this one is needed for the PCL3/4/5 and PCLXL formats)
+          
+        - The LaTeX typesetting software, in particular the dvips command
+          (this one is needed for the DVI file format).
+        
+=============================================================================
+
+Troubleshooting : 
+-----------------
+
+  If pkpgcounter gives incorrect results to you, please make an incorrectly
+  parsed data file available to us on some website, and tell us which 
+  driver was used.
+  
+  If pkpgcounter complain about your system lacking the Python Psyco module,
+  please consider installing it to speedup file parsing. However, don't forget
+  that Psyco currently only runs on the 32 bits x86 platform, so no need to 
+  install it if you've got another system type.
+  
+=============================================================================
+
+Before pkpgcounter v1.86, the PCL3/4/5 parser was a Python backport of an early
+release of the PCLCount software by Eduardo Gielamo Oliveira and Rodolfo Broco
+Manin, available from :
+
+    http://www.fea.unicamp.br/pclcount/
+    
+Their software is distributed under either the terms of a BSD-like license,    
+or the terms of the GNU General Public License of the Free Software Foundation.
+
+Beginning with pkpgcounter v1.86, the PCL3/4/5 parser was rewritten from
+scratch, and is now much more readable, maintainable, and of course accurate.
+
+The old parser is still available, but not used, in the pkpgpdls/oldpcl345.py
+Python module.
+    
+pkpgcounter's PCLXL (aka PCL6) parser doesn't originate from PCLCount, but 
+was written from scratch, just like all the other parsers included in
+pkpgcounter.
+
+=============================================================================
+
+pkpgcounter's ink coverage algorithm for the CMYK colorspace is a 
+direct Python port from the PrintBill project by Daniel Franklin. 
+PrintBill is distributed under the terms of the GNU General Public 
+License of the Free Software Foundation, just like pkpgcounter. The 
+algorithms used for the other colorspaces are a complete rewrite of 
+PrintBill's algorithms using both Python and the Python Imaging 
+Library's facilities. 
+
+=============================================================================
+
+Please e-mail bugs to : alet@librelogiciel.com (Jerome Alet)
