Index: pkpgcounter/tags/1.50/BUGS
===================================================================
--- pkpgcounter/tags/1.50/BUGS (revision 211)
+++ pkpgcounter/tags/1.50/BUGS (revision 211)
@@ -0,0 +1,28 @@
+# $Id$
+
+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.
+
+=============================================================================
+
+pkpgcounter Bugs :
+   
+  - The PCL3/4/5 parser have to be rewritten as a table driven parser, which
+    will be more easily extensible.
+    
+  - The ESC/P2 parser needs more testing.  
+
Index: pkpgcounter/tags/1.50/tests/README
===================================================================
--- pkpgcounter/tags/1.50/tests/README (revision 211)
+++ pkpgcounter/tags/1.50/tests/README (revision 211)
@@ -0,0 +1,36 @@
+# $Id$
+
+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.
+
+====================================================================
+
+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
Index: pkpgcounter/tags/1.50/tests/runtest.sh
===================================================================
--- pkpgcounter/tags/1.50/tests/runtest.sh (revision 201)
+++ pkpgcounter/tags/1.50/tests/runtest.sh (revision 201)
@@ -0,0 +1,18 @@
+#! /bin/sh
+
+echo -n "Generating testsuite..."
+gunzip <master.ps.gz >master2.ps
+for device in 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 ; do
+    if ! [ -f "testsuite.$device" ]  ; then
+        gs -dQUIET -dBATCH -dNOPAUSE -sOutputFile="testsuite.$device" -sDEVICE="$device" master2.ps ; 
+    fi ;
+    done
+echo 
+
+echo -n "File master.ps should be 16 pages long, result is : "
+python ../pdlanalyzer/analyzer.py master2.ps
+
+echo "Analyzing testsuite..."
+for file in testsuite.* ; do
+    echo -n "$file ===> " && python ../pdlanalyzer/analyzer.py "$file" ;
+done    
Index: pkpgcounter/tags/1.50/pdlanalyzer/pdf.py
===================================================================
--- pkpgcounter/tags/1.50/pdlanalyzer/pdf.py (revision 211)
+++ pkpgcounter/tags/1.50/pdlanalyzer/pdf.py (revision 211)
@@ -0,0 +1,68 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# 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$
+#
+
+import sys
+import re
+
+from pdlanalyzer import pdlparser
+
+class PDFParser(pdlparser.PDLParser) :
+    """A parser for PDF documents."""
+    def getJobSize(self) :    
+        """Counts pages in a PDF document."""
+        self.iscolor = None
+        newpageregexp = re.compile(r"(/Type) ?(/Page)[/ \t\r\n]", re.I)
+        colorregexp = re.compile(r"(/ColorSpace) ?(/DeviceRGB|/DeviceCMYK)[/ \t\r\n]", re.I)
+        pagecount = 0
+        for line in self.infile.xreadlines() : 
+            pagecount += len(newpageregexp.findall(line))
+            if colorregexp.match(line) :
+                self.iscolor = 1
+                if self.debug :
+                    sys.stderr.write("ColorSpace : %s\n" % line)
+        return pagecount    
+        
+def test() :        
+    """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, "rb")
+            mustclose = 1
+        try :
+            parser = PDFParser(infile, debug=1)
+            totalsize += parser.getJobSize()
+        except pdlparser.PDLParserError, msg :    
+            sys.stderr.write("ERROR: %s\n" % msg)
+            sys.stderr.flush()
+        if mustclose :    
+            infile.close()
+    print "%s" % totalsize
+    
+if __name__ == "__main__" :    
+    test()
Index: pkpgcounter/tags/1.50/pdlanalyzer/pcl345.py
===================================================================
--- pkpgcounter/tags/1.50/pdlanalyzer/pcl345.py (revision 211)
+++ pkpgcounter/tags/1.50/pdlanalyzer/pcl345.py (revision 211)
@@ -0,0 +1,358 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# 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$
+#
+
+import sys
+import os
+import mmap
+
+from pdlanalyzer import pdlparser
+
+class PCL345Parser(pdlparser.PDLParser) :
+    """A parser for PCL3, PCL4, PCL5 documents."""
+    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 setPageDict(self, pages, number, attribute, value) :
+        """Initializes a page dictionnary."""
+        dict = pages.setdefault(number, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait"})
+        dict[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
+                   }  
+        pagecount = resets = ejects = backsides = startgfx = endgfx = 0
+        starb = ampl = ispcl3 = escstart = 0
+        mediasourcecount = mediasizecount = orientationcount = mediatypecount = 0
+        tag = None
+        pages = {}
+        pos = 0
+        try :
+            while 1 :
+                char = minfile[pos] ; pos += 1
+                if char == "\014" :    
+                    pagecount += 1
+                elif char == "\033" :    
+                    starb = ampl = 0
+                    #
+                    #     <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) :
+                            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 ?
+            minfile.close() # reached EOF
+                            
+        # 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)
+        
+#        if not pagecount :
+#            pagecount = (pagecount or ((resets - 3) * (resets > 2)))
+#        else :    
+#            # here we add counters for other ways new pages may have
+#            # been printed and ejected by the printer
+#            pagecount += ejects + backsides
+#        
+#        # now handle number of copies for each page (may differ).
+#        # in duplex mode, number of copies may be sent only once.
+#        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 })))
+#            pagecount += (page["copies"] - 1)
+#            
+#        # in PCL3 files, there's one Start Gfx tag per page
+#        if ispcl3 :
+#            if endgfx == int(startgfx / 2) : # special case for cdj1600
+#                pagecount = endgfx 
+#            elif startgfx :
+#                pagecount = startgfx
+#            elif endgfx :    
+#                pagecount = endgfx
+                
+            
+        if pagecount == mediasourcecount == escstart : 
+            pass        # should be OK.
+        elif (not startgfx) and (not endgfx) :
+            pagecount = ejects or pagecount
+        elif startgfx == endgfx :    
+            pagecount = startgfx
+        elif startgfx == (endgfx - 1) :    
+            pagecount = startgfx
+        elif (startgfx == 1) and not endgfx :    
+            pass
+        else :    
+            pagecount = abs(startgfx - endgfx)
+            
+        if self.debug :        
+            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"})))
+                sys.stderr.write("%s*%s*%s*%s*%s\n" % (page["copies"], page["mediatype"], page["mediasize"], page["orientation"], page["mediasource"]))
+                
+        return pagecount
+        
+def test() :        
+    """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, "rb")
+            mustclose = 1
+        try :
+            parser = PCL345Parser(infile, debug=1)
+            totalsize += parser.getJobSize()
+        except pdlparser.PDLParserError, msg :    
+            sys.stderr.write("ERROR: %s\n" % msg)
+            sys.stderr.flush()
+        if mustclose :    
+            infile.close()
+    print "%s" % totalsize
+    
+if __name__ == "__main__" :    
+    test()
Index: pkpgcounter/tags/1.50/pdlanalyzer/postscript.py
===================================================================
--- pkpgcounter/tags/1.50/pdlanalyzer/postscript.py (revision 211)
+++ pkpgcounter/tags/1.50/pdlanalyzer/postscript.py (revision 211)
@@ -0,0 +1,124 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# 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$
+#
+
+import sys
+import popen2
+
+from pdlanalyzer import pdlparser
+
+class PostScriptParser(pdlparser.PDLParser) :
+    """A parser for PostScript documents."""
+    def throughGhostScript(self) :
+        """Get the count through GhostScript, useful for non-DSC compliant PS files."""
+        if self.debug :
+            sys.stderr.write("Internal parser sucks, using GhostScript instead...\n")
+        self.infile.seek(0)
+        command = 'gs -sDEVICE=bbox -dNOPAUSE -dBATCH -dQUIET - 2>&1 | grep -c "%%HiResBoundingBox:" 2>/dev/null'
+        child = popen2.Popen4(command)
+        try :
+            data = self.infile.read(MEGABYTE)    
+            while data :
+                child.tochild.write(data)
+                data = self.infile.read(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
+        return pagecount * self.copies
+        
+    def natively(self) :
+        """Count pages in a DSC compliant PostScript document."""
+        self.infile.seek(0)
+        pagecount = 0
+        for line in self.infile.xreadlines() : 
+            if line.startswith(r"%%Page: ") :
+                pagecount += 1
+            elif line.startswith(r"%%Requirements: numcopies(") :    
+                try :
+                    number = int(line.strip().split('(')[1].split(')')[0])
+                except :     
+                    pass
+                else :    
+                    if number > self.copies :
+                        self.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.copies :
+                        self.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.copies :
+                        self.copies = number
+        return pagecount * self.copies
+        
+    def getJobSize(self) :    
+        """Count pages in PostScript document."""
+        self.copies = 1
+        return self.natively() or self.throughGhostScript()
+        
+def test() :        
+    """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, "rb")
+            mustclose = 1
+        try :
+            parser = PostScriptParser(infile, debug=1)
+            totalsize += parser.getJobSize()
+        except pdlparser.PDLParserError, msg :    
+            sys.stderr.write("ERROR: %s\n" % msg)
+            sys.stderr.flush()
+        if mustclose :    
+            infile.close()
+    print "%s" % totalsize
+    
+if __name__ == "__main__" :    
+    test()
Index: pkpgcounter/tags/1.50/pdlanalyzer/escp2.py
===================================================================
--- pkpgcounter/tags/1.50/pdlanalyzer/escp2.py (revision 211)
+++ pkpgcounter/tags/1.50/pdlanalyzer/escp2.py (revision 211)
@@ -0,0 +1,88 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# 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$
+#
+
+import sys
+
+from pdlanalyzer import pdlparser
+
+class ESCP2Parser(pdlparser.PDLParser) :
+    """A parser for ESC/P2 documents."""
+    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)       
+        
+def test() :        
+    """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, "rb")
+            mustclose = 1
+        try :
+            parser = ESCP2Parser(infile, debug=1)
+            totalsize += parser.getJobSize()
+        except pdlparser.PDLParserError, msg :    
+            sys.stderr.write("ERROR: %s\n" % msg)
+            sys.stderr.flush()
+        if mustclose :    
+            infile.close()
+    print "%s" % totalsize
+    
+if __name__ == "__main__" :    
+    test()
Index: pkpgcounter/tags/1.50/pdlanalyzer/pdlparser.py
===================================================================
--- pkpgcounter/tags/1.50/pdlanalyzer/pdlparser.py (revision 211)
+++ pkpgcounter/tags/1.50/pdlanalyzer/pdlparser.py (revision 211)
@@ -0,0 +1,42 @@
+#
+# 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$
+#
+
+import sys
+
+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."""
+    def __init__(self, infile, debug=0) :
+        """Initialize the generic parser."""
+        self.debug = debug
+        self.infile = infile
+                
+    def getJobSize(self) :            
+        """Counts pages in the document."""
+        raise RuntimeError, "Not implemented !"
Index: pkpgcounter/tags/1.50/pdlanalyzer/__init__.py
===================================================================
--- pkpgcounter/tags/1.50/pdlanalyzer/__init__.py (revision 211)
+++ pkpgcounter/tags/1.50/pdlanalyzer/__init__.py (revision 211)
@@ -0,0 +1,20 @@
+#
+# 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$
+#
Index: pkpgcounter/tags/1.50/pdlanalyzer/pclxl.py
===================================================================
--- pkpgcounter/tags/1.50/pdlanalyzer/pclxl.py (revision 211)
+++ pkpgcounter/tags/1.50/pdlanalyzer/pclxl.py (revision 211)
@@ -0,0 +1,383 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# 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$
+#
+
+import sys
+import os
+import mmap
+from struct import unpack
+
+from pdlanalyzer import pdlparser
+
+class PCLXLParser(pdlparser.PDLParser) :
+    """A parser for PCLXL (aka PCL6) documents."""
+    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",
+                    14 : "JPostcard",
+                    15 : "JDoublePostcard",
+                    16 : "A5",
+                    17 : "A6",
+                    18 : "JB6",
+                 }   
+                 
+    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",
+                   }
+            
+    def beginPage(self) :
+        """Indicates the beginning of a new page, and extracts media information."""
+        self.pagecount += 1
+        
+        # Default values
+        mediatypelabel = "Plain"
+        mediasourcelabel = "Main"
+        mediasizelabel = "Default"
+        orientationlabel = "Portrait"
+        
+        # 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 = self.pos - 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 = pos - 4
+            elif val == 0x25 :
+                mediasize = ord(minfile[pos - 2])
+                mediasizelabel = self.mediasizes.get(mediasize, str(mediasize))
+                pos = pos - 4
+            elif val == 0x28 :    
+                orientation = ord(minfile[pos - 2])
+                orienationlabel = self.orientations.get(orientation, str(orientation))
+                pos = pos - 4
+            elif val == 0x27 :    
+                savepos = pos
+                pos = pos - 1
+                while pos > 0 : # safety check : don't go back to far !
+                    val = ord(minfile[pos])
+                    pos -= 1    
+                    if val == 0xc8 :
+                        break
+                mediatypelabel = minfile[pos:savepos] # TODO : INCORRECT, WE HAVE TO STRIP OUT THE UBYTE ARRAY'S LENGTH !!!
+            # else : TODO : CUSTOM MEDIA SIZE AND UNIT ! 
+            else :    
+                pos = pos - 2   # ignored
+        self.pages[self.pagecount] = { "copies" : 1, 
+                                       "orientation" : orientationlabel, 
+                                       "mediatype" : mediatypelabel, 
+                                       "mediasize" : mediasizelabel,
+                                       "mediasource" : mediasourcelabel,
+                                     } 
+        return 0
+        
+    def endPage(self) :    
+        """Indicates the end of a page."""
+        pos = self.pos
+        pos3 = pos - 3
+        minfile = self.minfile
+        if minfile[pos3:pos-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
+            self.pages[self.pagecount]["copies"] = unpack(self.endianness + "H", minfile[pos-5:pos3])[0]
+        return 0
+        
+    def setColorSpace(self) :    
+        """Changes the color space."""
+        if self.minfile[self.pos-4:self.pos-1] == self.RGBColorSpace :
+            self.iscolor = 1
+        return 0
+            
+    def array_8(self) :    
+        """Handles byte arrays."""
+        pos = self.pos
+        datatype = self.minfile[pos]
+        pos += 1
+        length = self.tags[ord(datatype)]
+        if callable(length) :
+            self.pos = pos
+            length = length()
+            pos = self.pos
+        posl = pos + length
+        self.pos = posl
+        if length == 1 :    
+            return unpack("B", self.minfile[pos:posl])[0]
+        elif length == 2 :    
+            return unpack(self.endianness + "H", self.minfile[pos:posl])[0]
+        elif length == 4 :    
+            return unpack(self.endianness + "I", self.minfile[pos:posl])[0]
+        else :    
+            raise pdlparser.PDLParserError, "Error on array size at %s" % self.pos
+        
+    def array_16(self) :    
+        """Handles byte arrays."""
+        pos = self.pos
+        datatype = self.minfile[pos]
+        pos += 1
+        length = self.tags[ord(datatype)]
+        if callable(length) :
+            self.pos = pos
+            length = length()
+            pos = self.pos
+        posl = pos + length
+        self.pos = posl
+        if length == 1 :    
+            return 2 * unpack("B", self.minfile[pos:posl])[0]
+        elif length == 2 :    
+            return 2 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
+        elif length == 4 :    
+            return 2 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
+        else :    
+            raise pdlparser.PDLParserError, "Error on array size at %s" % self.pos
+        
+    def array_32(self) :    
+        """Handles byte arrays."""
+        pos = self.pos
+        datatype = self.minfile[pos]
+        pos += 1
+        length = self.tags[ord(datatype)]
+        if callable(length) :
+            self.pos = pos
+            length = length()
+            pos = self.pos
+        posl = pos + length
+        self.pos = posl
+        if length == 1 :    
+            return 4 * unpack("B", self.minfile[pos:posl])[0]
+        elif length == 2 :    
+            return 4 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
+        elif length == 4 :    
+            return 4 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
+        else :    
+            raise pdlparser.PDLParserError, "Error on array size at %s" % self.pos
+        
+    def embeddedDataSmall(self) :
+        """Handle small amounts of data."""
+        pos = self.pos
+        length = ord(self.minfile[pos])
+        self.pos = pos + 1
+        return length
+        
+    def embeddedData(self) :
+        """Handle normal amounts of data."""
+        pos = self.pos
+        pos4 = pos + 4
+        self.pos = pos4
+        return unpack(self.endianness + "I", self.minfile[pos:pos4])[0]
+        
+    def littleEndian(self) :        
+        """Toggles to little endianness."""
+        self.endianness = "<" # little endian
+        return 0
+        
+    def bigEndian(self) :    
+        """Toggles to big endianness."""
+        self.endianness = ">" # big endian
+        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 
+        """
+        self.iscolor = None
+        self.endianness = None
+        found = 0
+        while not found :
+            line = self.infile.readline()
+            if not line :
+                break
+            if line[1:12] == " HP-PCL XL;" :
+                found = 1
+                endian = ord(line[0])
+                if endian == 0x29 :
+                    self.littleEndian()
+                elif endian == 0x28 :    
+                    self.bigEndian()
+                # 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 table of tags
+        self.tags = [ 0 ] * 256    
+        
+        # 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[0x6a] = self.setColorSpace    # to detect color/b&w mode
+        
+        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[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[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[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[0xf8] = 1 # attr_ubyte
+        self.tags[0xf9] = 2 # attr_uint16
+        
+        self.tags[0xfa] = self.embeddedData      # dataLength
+        self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte
+            
+        # 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)]) 
+        
+        infileno = self.infile.fileno()
+        self.pages = {}
+        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.pos = pos = self.infile.tell()
+        try :
+            while 1 :
+                char = minfile[pos]
+                pos += 1
+                length = tags[ord(char)]
+                if not length :
+                    continue
+                if callable(length) :    
+                    self.pos = pos
+                    length = length()
+                    pos = self.pos
+                pos += length    
+        except IndexError : # EOF ?
+            self.minfile.close() # reached EOF
+            
+        # now handle number of copies for each page (may differ).
+        if self.iscolor :
+            colormode = "Color"
+        else :    
+            colormode = "Black"
+        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, 1)
+            copies = page["copies"]
+            self.pagecount += (copies - 1)
+            if self.debug :
+                sys.stderr.write("%s*%s*%s*%s*%s*%s\n" % (copies, 
+                                                          page["mediatype"], 
+                                                          page["mediasize"], 
+                                                          page["orientation"], 
+                                                          page["mediasource"], 
+                                                          colormode))
+            
+        return self.pagecount
+        
+def test() :        
+    """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, "rb")
+            mustclose = 1
+        try :
+            parser = PCLXLParser(infile, debug=1)
+            totalsize += parser.getJobSize()
+        except pdlparser.PDLParserError, msg :    
+            sys.stderr.write("ERROR: %s\n" % msg)
+            sys.stderr.flush()
+        if mustclose :    
+            infile.close()
+    print "%s" % totalsize
+    
+if __name__ == "__main__" :    
+    test()
Index: pkpgcounter/tags/1.50/pdlanalyzer/analyzer.py
===================================================================
--- pkpgcounter/tags/1.50/pdlanalyzer/analyzer.py (revision 211)
+++ pkpgcounter/tags/1.50/pdlanalyzer/analyzer.py (revision 211)
@@ -0,0 +1,231 @@
+#
+# 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$
+#
+
+import sys
+import tempfile
+
+from pdlanalyzer import version, pdlparser, postscript, pdf, pcl345, pclxl, escp2
+
+KILOBYTE = 1024    
+MEGABYTE = 1024 * KILOBYTE    
+LASTBLOCKSIZE = int(KILOBYTE / 4)
+
+class PDLAnalyzer :    
+    """Class for PDL autodetection."""
+    def __init__(self, filename, debug=0) :
+        """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.debug = debug
+        self.filename = filename
+        try :
+            import psyco 
+        except ImportError :    
+            sys.stderr.write("pkpgcounter : you should install psyco if possible, this would greatly speedup parsing.\n")
+            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, 
+            # for PostScript and PDF the difference is
+            # barely noticeable since they are already
+            # almost optimal, and much more speedy anyway.
+            psyco.bind(postscript.PostScriptParser.getJobSize)
+            psyco.bind(pdf.PDFParser.getJobSize)
+            psyco.bind(escp2.ESCP2Parser.getJobSize)
+            psyco.bind(pcl345.PCL345Parser.getJobSize)
+            psyco.bind(pclxl.PCLXLParser.getJobSize)
+        
+    def getJobSize(self) :    
+        """Returns the job's size."""
+        self.openFile()
+        try :
+            pdlhandler = self.detectPDLHandler()
+        except pdlparser.PDLParserError, msg :    
+            self.closeFile()
+            raise pdlparser.PDLParserError, "ERROR : Unknown file format for %s (%s)" % (self.filename, msg)
+        else :
+            try :
+                size = pdlhandler(self.infile, self.debug).getJobSize()
+            finally :    
+                self.closeFile()
+            return size
+        
+    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, "rb")
+            self.mustclose = 1
+            return
+            
+        # Use a temporary file, always seekable contrary to standard input.
+        self.infile = tempfile.TemporaryFile(mode="w+b")
+        while 1 :
+            data = infile.read(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 :    
+                pass    # probably stdin, which is not seekable
+        
+    def isPostScript(self, sdata, edata) :    
+        """Returns 1 if data is PostScript, else 0."""
+        if sdata.startswith("%!") or \
+           sdata.startswith("\004%!") or \
+           sdata.startswith("\033%-12345X%!PS") or \
+           ((sdata[:128].find("\033%-12345X") != -1) and \
+             ((sdata.find("LANGUAGE=POSTSCRIPT") != -1) or \
+              (sdata.find("LANGUAGE = POSTSCRIPT") != -1) or \
+              (sdata.find("LANGUAGE = Postscript") != -1))) or \
+              (sdata.find("%!PS-Adobe") != -1) :
+            if self.debug :  
+                sys.stderr.write("%s is a PostScript file\n" % str(self.filename))
+            return 1
+        else :    
+            return 0
+        
+    def isPDF(self, sdata, edata) :    
+        """Returns 1 if data is PDF, else 0."""
+        if sdata.startswith("%PDF-") or \
+           sdata.startswith("\033%-12345X%PDF-") or \
+           ((sdata[:128].find("\033%-12345X") != -1) and (sdata.upper().find("LANGUAGE=PDF") != -1)) or \
+           (sdata.find("%PDF-") != -1) :
+            if self.debug :  
+                sys.stderr.write("%s is a PDF file\n" % str(self.filename))
+            return 1
+        else :    
+            return 0
+        
+    def isPCL(self, sdata, edata) :    
+        """Returns 1 if data is PCL, else 0."""
+        if sdata.startswith("\033E\033") or \
+           (sdata.startswith("\033*rbC") and (not edata[-3:] == "\f\033@")) or \
+           sdata.startswith("\033%8\033") or \
+           (sdata.find("\033%-12345X") != -1) :
+            if self.debug :  
+                sys.stderr.write("%s is a PCL3/4/5 file\n" % str(self.filename))
+            return 1
+        else :    
+            return 0
+        
+    def isPCLXL(self, sdata, edata) :    
+        """Returns 1 if data is PCLXL aka PCL6, else 0."""
+        if ((sdata[:128].find("\033%-12345X") != -1) and \
+             (sdata.find(" HP-PCL XL;") != -1) and \
+             ((sdata.find("LANGUAGE=PCLXL") != -1) or \
+              (sdata.find("LANGUAGE = PCLXL") != -1))) :
+            if self.debug :  
+                sys.stderr.write("%s is a PCLXL (aka PCL6) file\n" % str(self.filename))
+            return 1
+        else :    
+            return 0
+            
+    def isESCP2(self, sdata, edata) :        
+        """Returns 1 if data is ESC/P2, else 0."""
+        if sdata.startswith("\033@") or \
+           sdata.startswith("\033*") or \
+           sdata.startswith("\n\033@") or \
+           sdata.startswith("\0\0\0\033\1@EJL") : # ESC/P Raster ??? Seen on Stylus Photo 1284
+            if self.debug :  
+                sys.stderr.write("%s is an ESC/P2 file\n" % str(self.filename))
+            return 1
+        else :    
+            return 0
+    
+    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 block of datas    
+        self.infile.seek(0)
+        firstblock = self.infile.read(16 * KILOBYTE)
+        try :
+            self.infile.seek(-LASTBLOCKSIZE, 2)
+            lastblock = self.infile.read(LASTBLOCKSIZE)
+        except IOError :    
+            lastblock = ""
+        self.infile.seek(0)
+        if self.isPostScript(firstblock, lastblock) :
+            return postscript.PostScriptParser
+        elif self.isPCLXL(firstblock, lastblock) :    
+            return pclxl.PCLXLParser
+        elif self.isPDF(firstblock, lastblock) :    
+            return pdf.PDFParser
+        elif self.isPCL(firstblock, lastblock) :    
+            return pcl345.PCL345Parser
+        elif self.isESCP2(firstblock, lastblock) :    
+            return escp2.ESCP2Parser
+        else :    
+            raise pdlparser.PDLParserError, "Analysis of first data block failed."
+            
+def main() :    
+    """Entry point for PDL Analyzer."""
+    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
+        sys.argv.append("-")
+        
+    if ("-h" in sys.argv[1:]) or ("--help" in sys.argv[1:]) :
+        print "usage : pkpgcounter file1 file2 ... fileN"
+    elif ("-v" in sys.argv[1:]) or ("--version" in sys.argv[1:]) :
+        print "%s" % version.__version__
+    else :
+        totalsize = 0    
+        debug = 0
+        minindex = 1
+        if sys.argv[1] == "--debug" :
+            minindex = 2
+            debug = 1
+        for arg in sys.argv[minindex:] :
+            try :
+                parser = PDLAnalyzer(arg, debug)
+                totalsize += parser.getJobSize()
+            except pdlparser.PDLParserError, msg :    
+                sys.stderr.write("ERROR: %s\n" % msg)
+                sys.stderr.flush()
+        print "%s" % totalsize
+    
+if __name__ == "__main__" :    
+    main()
Index: pkpgcounter/tags/1.50/pdlanalyzer/version.py
===================================================================
--- pkpgcounter/tags/1.50/pdlanalyzer/version.py (revision 211)
+++ pkpgcounter/tags/1.50/pdlanalyzer/version.py (revision 211)
@@ -0,0 +1,27 @@
+#
+# 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$
+#
+
+__version__ = "1.50"
+
+__doc__ = """pkpgcounter : a generic Page Description Languages parser."""
+
+__author__ = """Jerome Alet - alet@librelogiciel.com"""
+
Index: pkpgcounter/tags/1.50/setup.py
===================================================================
--- pkpgcounter/tags/1.50/setup.py (revision 211)
+++ pkpgcounter/tags/1.50/setup.py (revision 211)
@@ -0,0 +1,62 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# 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$
+#
+#
+
+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)
+
+sys.path.insert(0, "pdlanalyzer")
+from pdlanalyzer.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.librelogiciel.com/software/",
+      packages = [ "pdlanalyzer" ],
+      scripts = [ "bin/pkpgcounter" ],
+      data_files = data_files)
Index: pkpgcounter/tags/1.50/COPYING
===================================================================
--- pkpgcounter/tags/1.50/COPYING (revision 211)
+++ pkpgcounter/tags/1.50/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/1.50/bin/pkpgcounter
===================================================================
--- pkpgcounter/tags/1.50/bin/pkpgcounter (revision 213)
+++ pkpgcounter/tags/1.50/bin/pkpgcounter (revision 213)
@@ -0,0 +1,36 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+#
+# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id$
+#
+#
+
+import sys
+from pdlanalyzer.version import __version__
+from pdlanalyzer import analyzer
+
+if __name__ == "__main__" : 
+    if (len(sys.argv) >= 2) and (sys.argv[1] in ("-h", "--help")) :
+        print "usage :  pkpgcounter  file1  [ file2  ... fileN [ <anotherfile ] ]"
+    elif (len(sys.argv) >= 2) and (sys.argv[1] in ("-v", "--version")) :
+        print __version__
+    else :    
+        analyzer.main()
+
Index: pkpgcounter/tags/1.50/MANIFEST.in
===================================================================
--- pkpgcounter/tags/1.50/MANIFEST.in (revision 197)
+++ pkpgcounter/tags/1.50/MANIFEST.in (revision 197)
@@ -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
Index: pkpgcounter/tags/1.50/clean.sh
===================================================================
--- pkpgcounter/tags/1.50/clean.sh (revision 211)
+++ pkpgcounter/tags/1.50/clean.sh (revision 211)
@@ -0,0 +1,28 @@
+#! /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
+
+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/1.50/NEWS
===================================================================
--- pkpgcounter/tags/1.50/NEWS (revision 211)
+++ pkpgcounter/tags/1.50/NEWS (revision 211)
@@ -0,0 +1,35 @@
+# $Id$
+
+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.
+
+=============================================================================
+
+pkpgcounter News :
+   
+  * 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/1.50/CREDITS
===================================================================
--- pkpgcounter/tags/1.50/CREDITS (revision 211)
+++ pkpgcounter/tags/1.50/CREDITS (revision 211)
@@ -0,0 +1,40 @@
+# $Id$
+
+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.
+
+============================================================
+
+The following people helped the pkpgcounter project :
+  
+  
+  - Eduardo Gielamo Oliveira & Rodolfo Broco Manin : initial PCL parser.
+  - Valcir C. Vargas : helped on PCL3GUI support.
+
+
+==============================================================
+
+  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/1.50/README
===================================================================
--- pkpgcounter/tags/1.50/README (revision 211)
+++ pkpgcounter/tags/1.50/README (revision 211)
@@ -0,0 +1,89 @@
+# $Id$
+
+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.
+
+=============================================================================
+
+pkpgcounter is a generic Page Description Language parser.
+
+It can currently compute the number of pages in several types of files :
+
+        - PostScript (both DSC compliant and binary)
+        
+        - PDF
+        
+        - PCL3/4/5
+        
+        - PCLXL (aka PCL6)
+        
+        - ESC/P2
+        
+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.
+
+In the future other possibilities will be added.        
+
+=============================================================================
+
+Installation :
+--------------
+
+  0 - Download pkpgcounter from :
+  
+        http://www.librelogiciel.com/software/pkpgcounter/action_Presentation
+        
+      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/pdlanalyzer/
+        
+  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.
+      
+  3 - That's all !    
+  
+=============================================================================
+
+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.
+  
+=============================================================================
+
+Please e-mail bugs to : alet@librelogiciel.com (Jerome Alet)
