Index: pkpgcounter/trunk/pkpgpdls/tiff.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/tiff.py (revision 489)
+++ pkpgcounter/trunk/pkpgpdls/tiff.py (revision 491)
@@ -79,5 +79,2 @@
             minfile.close()
         return pagecount
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/pdlparser.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/pdlparser.py (revision 463)
+++ pkpgcounter/trunk/pkpgpdls/pdlparser.py (revision 491)
@@ -42,19 +42,12 @@
     """Generic PDL parser."""
     totiffcommands = None        # Default command to convert to TIFF
-    def __init__(self, infile, debug=0, firstblock=None, lastblock=None) :
+    openmode = "rb"              # Default file opening mode
+    def __init__(self, filename, debug=0) :
         """Initialize the generic parser."""
-        self.infile = infile
+        self.filename = filename
         self.debug = debug
-        if firstblock is None :
-            self.infile.seek(0)
-            firstblock = self.infile.read(FIRSTBLOCKSIZE)
-            try :
-                self.infile.seek(-LASTBLOCKSIZE, 2)
-                lastblock = self.infile.read(LASTBLOCKSIZE)
-            except IOError :    
-                lastblock = ""
-            self.infile.seek(0)
-        self.firstblock = firstblock
-        self.lastblock = lastblock
+        self.infile = None
+        (self.firstblock, self.lastblock) = self.readBlocks()
+        self.infile = open(self.filename, self.openmode)
         if not self.isValid() :
             raise PDLParserError, "Invalid file format !"
@@ -68,4 +61,23 @@
             # parsing will greatly benefit from this.
             psyco.bind(self.getJobSize)
+            
+    def __del__(self) :
+        """Ensures the input file gets closed."""
+        if self.infile :
+            self.infile.close()
+            
+    def readBlocks(self) :        
+        """Reads first and last block of the input file."""
+        infile = open(self.filename, "rb")
+        try :
+            firstblock = infile.read(FIRSTBLOCKSIZE)
+            try :
+                infile.seek(-LASTBLOCKSIZE, 2)
+                lastblock = infile.read(LASTBLOCKSIZE)
+            except IOError :    
+                lastblock = ""
+        finally :        
+            infile.close()
+        return (firstblock, lastblock)    
             
     def logdebug(self, message) :       
@@ -87,66 +99,47 @@
         """   
         if self.totiffcommands :
-            for totiffcommand in self.totiffcommands :
-                self.infile.seek(0)
-                error = False
-                commandline = totiffcommand % locals()
-                child = popen2.Popen4(commandline)
-                try :
+            infile = open(self.filename, "rb")
+            try :
+                for totiffcommand in self.totiffcommands :
+                    infile.seek(0)
+                    error = False
+                    commandline = totiffcommand % locals()
+                    child = popen2.Popen4(commandline)
                     try :
-                        data = self.infile.read(MEGABYTE)    
-                        while data :
-                            child.tochild.write(data)
-                            child.tochild.flush()
-                            data = self.infile.read(MEGABYTE)
-                    except (IOError, OSError) :    
+                        try :
+                            data = infile.read(MEGABYTE)    
+                            while data :
+                                child.tochild.write(data)
+                                child.tochild.flush()
+                                data = infile.read(MEGABYTE)
+                        except (IOError, OSError) :    
+                            error = True
+                    finally :    
+                        child.tochild.close()    
+                        dummy = child.fromchild.read()
+                        child.fromchild.close()
+                        
+                    try :
+                        status = child.wait()
+                    except OSError :    
                         error = True
-                finally :    
-                    child.tochild.close()    
-                    dummy = child.fromchild.read()
-                    child.fromchild.close()
-                    
-                try :
-                    status = child.wait()
-                except OSError :    
-                    error = True
-                else :    
-                    if os.WIFEXITED(status) :
-                        if os.WEXITSTATUS(status) :
+                    else :    
+                        if os.WIFEXITED(status) :
+                            if os.WEXITSTATUS(status) :
+                                error = True
+                        else :        
                             error = True
+                        
+                    if not os.path.exists(fname) :
+                        error = True
+                    elif not os.stat(fname).st_size :
+                        error = True
                     else :        
-                        error = True
-                    
-                if not os.path.exists(fname) :
-                    error = True
-                elif not os.stat(fname).st_size :
-                    error = True
-                else :        
-                    break       # Conversion worked fine it seems.
-                self.logdebug("Command failed : %s" % repr(commandline))
+                        break       # Conversion worked fine it seems.
+                    self.logdebug("Command failed : %s" % repr(commandline))
+            finally :        
+                infile.close()
             if error :
                 raise PDLParserError, "Problem during conversion to TIFF."
         else :        
             raise PDLParserError, "Impossible to compute ink coverage for this file format."
-            
-def test(parserclass) :        
-    """Test function."""
-    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
-        sys.argv.append("-")
-    totalsize = 0    
-    for arg in sys.argv[1:] :
-        if arg == "-" :
-            infile = sys.stdin
-            mustclose = 0
-        else :    
-            infile = open(arg, "rbU")
-            mustclose = 1
-        try :
-            parser = parserclass(infile, debug=1)
-            totalsize += parser.getJobSize()
-        except PDLParserError, msg :    
-            sys.stderr.write("ERROR: %s\n" % msg)
-            sys.stderr.flush()
-        if mustclose :    
-            infile.close()
-    print "%s" % totalsize
-    
Index: pkpgcounter/trunk/pkpgpdls/ooo.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/ooo.py (revision 463)
+++ pkpgcounter/trunk/pkpgpdls/ooo.py (revision 491)
@@ -62,5 +62,2 @@
                 raise pdlparser.PDLParserError, "OpenOffice.org's spreadsheet documents are not yet supported."
         return pagecount
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/lidil.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/lidil.py (revision 488)
+++ pkpgcounter/trunk/pkpgpdls/lidil.py (revision 491)
@@ -29,10 +29,9 @@
 """
 
-import sys
-import os
-import mmap
 import struct
 
 import pdlparser
+
+HEADERSIZE = 10 # LIDIL header is 10 bytes long
 
 # Packet types taken from hplip-2.7.10/prnt/ldl.py
@@ -74,32 +73,27 @@
         unpack = struct.unpack
         ejectpage = loadpage = 0
-        infileno = self.infile.fileno()
-        minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
-        pos = 0
-        try :
-            try :
-                while 1 :
-                    if minfile[pos] != "$" :    # Frame Sync
-                        raise pdlparser.PDLParserError, "This file doesn't seem to be valid Hewlett-Packard LIDIL datas"
-                    try :    
-                        (framesync,     
-                         cmdlength,
-                         dummy,
-                         packettype,
-                         commandnumber,
-                         referencenumber,
-                         datalength) = unpack(">BHBBBHH", minfile[pos:pos+10])
-                    except struct.error :    
-                        raise pdlparser.PDLParserError, "This file doesn't seem to be valid Hewlett-Packard LIDIL datas"
-                    if packettype == PACKET_TYPE_COMMAND :
-                        if commandnumber == LDL_LOAD_PAGE :
-                            loadpage += 1
-                        elif commandnumber == LDL_EJECT_PAGE :
-                            ejectpage += 1
-                    pos += (cmdlength + datalength)
-            except IndexError : # EOF ?
-                pass 
-        finally :        
-            minfile.close()
+        while True :
+            header = self.infile.read(HEADERSIZE)
+            if not header :
+                break
+            if (len(header) != HEADERSIZE) or (header[0] != "$") :
+                # Invalid header or no Frame Sync byte.
+                raise pdlparser.PDLParserError, "This file doesn't seem to be valid Hewlett-Packard LIDIL datas."
+            try :    
+                (framesync,     
+                 cmdlength,
+                 dummy,
+                 packettype,
+                 commandnumber,
+                 referencenumber,
+                 datalength) = unpack(">BHBBBHH", header)
+            except struct.error :    
+                raise pdlparser.PDLParserError, "This file doesn't seem to be valid Hewlett-Packard LIDIL datas."
+            if packettype == PACKET_TYPE_COMMAND :
+                if commandnumber == LDL_LOAD_PAGE :
+                    loadpage += 1
+                elif commandnumber == LDL_EJECT_PAGE :
+                    ejectpage += 1
+            self.infile.seek(cmdlength + datalength - len(header), 1) # relative seek
             
         # Number of page eject commands should be sufficient,
@@ -110,5 +104,2 @@
         self.logdebug("Load : %i    Eject : %i" % (loadpage, ejectpage))
         return max(loadpage, ejectpage)
-
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/escpages03.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/escpages03.py (revision 475)
+++ pkpgcounter/trunk/pkpgpdls/escpages03.py (revision 491)
@@ -93,5 +93,2 @@
             minfile.close()
         return pagecount
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/zjstream.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/zjstream.py (revision 463)
+++ pkpgcounter/trunk/pkpgpdls/zjstream.py (revision 491)
@@ -23,8 +23,5 @@
 """This modules implements a page counter for ZjStream documents."""
 
-import sys
-import os
-import mmap
-from struct import unpack
+import struct
 
 import pdlparser
@@ -36,10 +33,8 @@
         if self.firstblock[:4] == "ZJZJ" :
             self.logdebug("DEBUG: Input file is in the Zenographics ZjStream (little endian) format.")
-            self.littleEndian()
-            return True
+            return self.littleEndian()
         elif self.firstblock[:4] == "JZJZ" :    
             self.logdebug("DEBUG: Input file is in the Zenographics ZjStream (big endian) format.")
-            self.bigEndian()
-            return True
+            return self.bigEndian()
         else :    
             return False
@@ -47,60 +42,53 @@
     def littleEndian(self) :
         """Toggles to little endianness."""
-        self.unpackType = { 1 : "B", 2 : "<H", 4 : "<I" }
-        self.unpackShort = self.unpackType[2]
-        self.unpackLong = self.unpackType[4]
-        return 0
+        self.unpackHeader = "<IIIHH"
+        return True
         
     def bigEndian(self) :
         """Toggles to big endianness."""
-        self.unpackType = { 1 : "B", 2 : ">H", 4 : ">I" }
-        self.unpackShort = self.unpackType[2]
-        self.unpackLong = self.unpackType[4]
-        return 0
+        self.unpackHeader = ">IIIHH"
+        return True
         
     def getJobSize(self) :
         """Computes the number of pages in a ZjStream document."""
-        infileno = self.infile.fileno()
-        minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
-        pos = 4
+        unpack = struct.unpack
+        self.infile.seek(4, 0) # Skip ZJZJ/JZJZ header
         startpagecount = endpagecount = 0
-        try :
-            try :
-                while 1 :
-                    header = minfile[pos:pos+16]
-                    if len(header) != 16 :
-                        break
-                    totalChunkSize = unpack(self.unpackLong, header[:4])[0]
-                    chunkType = unpack(self.unpackLong, header[4:8])[0]
-                    numberOfItems = unpack(self.unpackLong, header[8:12])[0]
-                    reserved = unpack(self.unpackShort, header[12:14])[0]
-                    signature = unpack(self.unpackShort, header[14:])[0]
-                    pos += totalChunkSize
-                    if chunkType == 0 :
-                        self.logdebug("startDoc")
-                    elif chunkType == 1 :    
-                        self.logdebug("endDoc")
-                    elif chunkType == 2 :    
-                        self.logdebug("startPage")
-                        startpagecount += 1
-                    elif chunkType == 3 :
-                        self.logdebug("endPage")
-                        endpagecount += 1
-                        
-                    #self.logdebug("Chunk size : %s" % totalChunkSize)
-                    #self.logdebug("Chunk type : 0x%08x" % chunkType)
-                    #self.logdebug("# items : %s" % numberOfItems)
-                    #self.logdebug("reserved : 0x%04x" % reserved)
-                    #self.logdebug("signature : 0x%04x" % signature)
-                    #self.logdebug("\n")
-            except IndexError : # EOF ?
-                pass 
-        finally :        
-            minfile.close()
+        while True :
+            header = self.infile.read(16)
+            if not header :
+                break
+            try :    
+                (totalChunkSize,
+                 chunkType,
+                 numberOfItems,
+                 reserved,
+                 signature) = unpack(self.unpackHeader, header)
+            except struct.error :
+                raise pdlparser.PDLParserError, "This file doesn't seem to be valid ZjStream datas."
+            self.infile.seek(totalChunkSize - len(header), 1)
+            if chunkType == 2 :    
+                #self.logdebug("startPage")
+                startpagecount += 1
+            elif chunkType == 3 :
+                #self.logdebug("endPage")
+                endpagecount += 1
+            #elif chunkType == 0 :
+            #    self.logdebug("startDoc")
+            #elif chunkType == 1 :    
+            #    self.logdebug("endDoc")
+                
+            #self.logdebug("Chunk size : %s" % totalChunkSize)
+            #self.logdebug("Chunk type : 0x%08x" % chunkType)
+            #self.logdebug("# items : %s" % numberOfItems)
+            #self.logdebug("reserved : 0x%04x" % reserved)
+            #self.logdebug("signature : 0x%04x" % signature)
+            #self.logdebug("\n")
             
-        if startpagecount != endpagecount :    
-            sys.stderr.write("ERROR: Incorrect ZjStream datas.\n")
+        # Number of endpage commands should be sufficient,
+        # but we never know : someone could try to cheat the printer
+        # by starting a page but not ending it, and ejecting it manually
+        # later on. Not sure if the printers would support this, but
+        # taking the max value works around the problem in any case.
+        self.logdebug("StartPage : %i    EndPage : %i" % (startpagecount, endpagecount))
         return max(startpagecount, endpagecount)
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/qpdl.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/qpdl.py (revision 463)
+++ pkpgcounter/trunk/pkpgpdls/qpdl.py (revision 491)
@@ -292,5 +292,2 @@
                                            duplexmode))
         return self.pagecount
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/plain.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/plain.py (revision 463)
+++ pkpgcounter/trunk/pkpgpdls/plain.py (revision 491)
@@ -23,10 +23,6 @@
 """This modules implements a page counter for plain text documents."""
 
-import sys
-import os
-
 import pdlparser
 import version
-
 
 class Parser(pdlparser.PDLParser) :
@@ -35,4 +31,5 @@
                        'a2ps --borders 0 --quiet --portrait --no-header --columns 1 --output - | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -',
                      ]  
+    openmode = "rU"                 
     def isValid(self) :    
         """Returns True if data is plain text, else False.
@@ -57,5 +54,5 @@
         linecount = 0
         for line in self.infile :
-            if line.endswith("\n") or line.endswith("\r") :
+            if line.endswith("\n") :
                 linecount += 1    
                 if (linecount > pagesize) :
@@ -70,5 +67,2 @@
                 raise pdlparser.PDLParserError, "Unsupported file format. Please send the file to %s" % version.__authoremail__
         return pagecount + 1    # NB : empty files are catched in isValid()
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/pdf.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/pdf.py (revision 463)
+++ pkpgcounter/trunk/pkpgpdls/pdf.py (revision 491)
@@ -23,5 +23,4 @@
 """This modules implements a page counter for PDF documents."""
 
-import sys
 import re
 
@@ -34,4 +33,6 @@
         self.major = major
         self.minor = minor
+        self.majori = int(major)
+        self.minori = int(minor)
         self.description = description
         self.comments = []
@@ -43,4 +44,5 @@
     """A parser for PDF documents."""
     totiffcommands = [ 'gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -' ]
+    openmode = "rU"
     def isValid(self) :    
         """Returns True if data is PDF, else False."""
@@ -62,5 +64,5 @@
         objre = re.compile(r"\s?(\d+)\s+(\d+)\s+obj[<\s/]?")
         for line in self.infile :
-            line = line.strip()
+            line = line.strip()    
             if line.startswith("% ") :    
                 if inobject :
@@ -72,5 +74,5 @@
                 result = objre.search(line)
                 if result is not None :
-                    (major, minor) = [int(num) for num in line[result.start():result.end()].split()[:2]]
+                    (major, minor) = line[result.start():result.end()].split()[:2]
                     obj = PDFObject(major, minor, lastcomment)
                     obj.content.append(line[result.end():])
@@ -86,6 +88,8 @@
                         # if we want the first one, just use > instead of >=
                         oldobject = objects.setdefault(major, obj)
-                        if minor >= oldobject.minor :
+                        if int(minor) >= oldobject.minori :
                             objects[major] = obj
+                            # self.logdebug("Object(%i, %i) overwritten with Object(%i, %i)" % (oldobject.majori, oldobject.minori, obj.majori, obj.minori))
+                        # self.logdebug("Object(%i, %i)" % (obj.majori, obj.minori))
                         inobject = 0        
                 else :    
@@ -94,5 +98,4 @@
                         
         # Now we check each PDF object we've just created.
-        # colorregexp = re.compile(r"(/ColorSpace) ?(/DeviceRGB|/DeviceCMYK)[/ \t\r\n]", re.I)
         newpageregexp = re.compile(r"(/Type)\s?(/Page)[/>\s]", re.I)
         pagecount = 0
@@ -103,5 +106,2 @@
                 pagecount += count
         return pagecount    
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/hbp.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/hbp.py (revision 489)
+++ pkpgcounter/trunk/pkpgpdls/hbp.py (revision 491)
@@ -74,5 +74,2 @@
             minfile.close() # reached EOF
         return pagecount
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/postscript.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/postscript.py (revision 463)
+++ pkpgcounter/trunk/pkpgpdls/postscript.py (revision 491)
@@ -34,4 +34,5 @@
     """A parser for PostScript documents."""
     totiffcommands = [ 'gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -' ]
+    openmode = "rU"
     def isValid(self) :    
         """Returns True if data is PostScript, else False."""
@@ -52,28 +53,34 @@
         """Get the count through GhostScript, useful for non-DSC compliant PS files."""
         self.logdebug("Internal parser sucks, using GhostScript instead...")
-        self.infile.seek(0)
         command = 'gs -sDEVICE=bbox -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET - 2>&1 | grep -c "%%HiResBoundingBox:" 2>/dev/null'
-        child = popen2.Popen4(command)
+        pagecount = 0
+        # we need to reopen the input file in binary mode again, just in case
+        # otherwise we might break the original file's contents.
+        infile = open(self.filename, "rb")
         try :
-            data = self.infile.read(pdlparser.MEGABYTE)    
-            while data :
-                child.tochild.write(data)
-                data = self.infile.read(pdlparser.MEGABYTE)
-            child.tochild.flush()
-            child.tochild.close()    
-        except (IOError, OSError), msg :    
-            raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
+            child = popen2.Popen4(command)
+            try :
+                data = infile.read(pdlparser.MEGABYTE)    
+                while data :
+                    child.tochild.write(data)
+                    data = infile.read(pdlparser.MEGABYTE)
+                child.tochild.flush()
+                child.tochild.close()    
+            except (IOError, OSError), msg :    
+                raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
+                
+            pagecount = 0
+            try :
+                pagecount = int(child.fromchild.readline().strip())
+            except (IOError, OSError, AttributeError, ValueError), msg :
+                raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
+            child.fromchild.close()
             
-        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
+            try :
+                child.wait()
+            except OSError, msg :    
+                raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
+        finally :        
+            infile.close()
         self.logdebug("GhostScript said : %s pages" % pagecount)    
         return pagecount * self.copies
@@ -81,5 +88,4 @@
     def natively(self) :
         """Count pages in a DSC compliant PostScript document."""
-        self.infile.seek(0)
         pagecount = 0
         self.pages = { 0 : { "copies" : 1 } }
@@ -90,5 +96,6 @@
         acrobatmarker = 0
         pagescomment = None
-        for line in self.infile : 
+        for line in self.infile :
+            line = line.strip()
             if (not prescribe) and line.startswith(r"%%BeginResource: procset pdf") \
                and not acrobatmarker :
@@ -121,5 +128,5 @@
             elif line.startswith(r"%%Requirements: numcopies(") :    
                 try :
-                    number = int(line.strip().split('(')[1].split(')')[0])
+                    number = int(line.split('(')[1].split(')')[0])
                 except :     
                     pass
@@ -130,5 +137,5 @@
                 # handle # of copies set by some Windows printer driver
                 try :
-                    number = int(line.strip().split()[2])
+                    number = int(line.split()[2])
                 except :     
                     pass
@@ -139,5 +146,5 @@
                 # handle # of copies set by mozilla/kprinter
                 try :
-                    number = int(line.strip().split()[4])
+                    number = int(line.split()[4])
                 except :     
                     pass
@@ -148,5 +155,5 @@
                 # handle # of copies set by firefox/kprinter/cups (alternate syntax)
                 try :
-                    number = int(line.strip().split()[6])
+                    number = int(line.split()[6])
                 except :
                     pass
@@ -156,5 +163,5 @@
             elif line.startswith("/languagelevel where{pop languagelevel}{1}ifelse 2 ge{1 dict dup/NumCopies") :
                 try :
-                    number = int(previousline.strip()[2:])
+                    number = int(previousline[2:])
                 except :
                     pass
@@ -164,5 +171,5 @@
             elif line.startswith("/#copies ") :
                 try :
-                    number = int(line.strip().split()[1])
+                    number = int(line.split()[1])
                 except :     
                     pass
@@ -172,5 +179,5 @@
             elif line.startswith(r"%RBINumCopies: ") :   
                 try :
-                    number = int(line.strip().split()[1])
+                    number = int(line.split()[1])
                 except :     
                     pass
@@ -207,5 +214,2 @@
                 self.logdebug(msg)
         return max(nbpages, newnbpages)    
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/pcl345.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/pcl345.py (revision 478)
+++ pkpgcounter/trunk/pkpgpdls/pcl345.py (revision 491)
@@ -571,5 +571,2 @@
         
         return self.pagecount
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/escp2.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/escp2.py (revision 473)
+++ pkpgcounter/trunk/pkpgpdls/escp2.py (revision 491)
@@ -74,5 +74,2 @@
         else :    
             return int(pagecount1 / 2)       
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/spl1.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/spl1.py (revision 487)
+++ pkpgcounter/trunk/pkpgpdls/spl1.py (revision 491)
@@ -125,5 +125,2 @@
             minfile.close()
         return self.pagecount
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/pclxl.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/pclxl.py (revision 479)
+++ pkpgcounter/trunk/pkpgpdls/pclxl.py (revision 491)
@@ -700,5 +700,2 @@
                                                  colormode))
         return self.pagecount
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/dvi.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/dvi.py (revision 489)
+++ pkpgcounter/trunk/pkpgpdls/dvi.py (revision 491)
@@ -75,5 +75,2 @@
             minfile.close() # reached EOF
         return pagecount
-        
-if __name__ == "__main__" :    
-    pdlparser.test(Parser)
Index: pkpgcounter/trunk/pkpgpdls/analyzer.py
===================================================================
--- pkpgcounter/trunk/pkpgpdls/analyzer.py (revision 485)
+++ pkpgcounter/trunk/pkpgpdls/analyzer.py (revision 491)
@@ -54,5 +54,5 @@
         self.options = options
         self.filename = filename
-        self.infile = None
+        self.workfile = None 
         self.mustclose = None
         
@@ -82,14 +82,6 @@
             try :
                 pdlhandler = self.detectPDLHandler()
-                (handle, filename) = tempfile.mkstemp(".tmp", "pkpgcounter")    
-                os.close(handle)
-                try :
-                    pdlhandler.convertToTiffMultiPage24NC(filename, self.options.resolution)
-                    result = inkcoverage.getInkCoverage(filename, cspace)
-                finally :    
-                    try :
-                        os.remove(filename)
-                    except OSError :
-                        sys.stderr.write("Problem when trying to remove temporary file %s\n" % filename)
+                pdlhandler.convertToTiffMultiPage24NC(self.filename, self.options.resolution)
+                result = inkcoverage.getInkCoverage(self.filename, cspace)
             except pdlparser.PDLParserError, msg :    
                 raise pdlparser.PDLParserError, "Unknown file format for %s (%s)" % (self.filename, msg)
@@ -100,5 +92,5 @@
     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
+        self.mustclose = False  # 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 
@@ -109,31 +101,23 @@
         else :    
             # normal file
-            self.infile = open(self.filename, "rbU")
-            self.mustclose = 1
+            self.workfile = open(self.filename, "rb")
+            self.mustclose = True
             return
             
         # Use a temporary file, always seekable contrary to standard input.
-        self.infile = tempfile.TemporaryFile(mode="w+b") # TODO : not opened in universal newline mode, Python 2.5 refuses.
-        while 1 :
+        self.workfile = tempfile.NamedTemporaryFile(mode="w+b")
+        self.filename = self.workfile.name
+        while True :
             data = infile.read(pdlparser.MEGABYTE) 
             if not data :
                 break
-            self.infile.write(data)
-        self.infile.flush()    
-        self.infile.seek(0)
+            self.workfile.write(data)
+        self.workfile.flush()    
+        self.workfile.seek(0)
             
     def closeFile(self) :        
-        """Closes the job's data stream if we can close it."""
+        """Closes the job's data stream if we have to."""
         if self.mustclose :
-            self.infile.close()    
-        else :    
-            # if we don't have to close the file, then
-            # ensure the file pointer is reset to the 
-            # start of the file in case the process wants
-            # to read the file again.
-            try :
-                self.infile.seek(0)
-            except IOError :    
-                pass    # probably stdin, which is not seekable
+            self.workfile.close()    
         
     def detectPDLHandler(self) :    
@@ -142,37 +126,26 @@
            Returns the correct PDL handler class or None if format is unknown
         """   
-        # Try to detect file type by reading first and last blocks of datas    
-        # Each parser can read them automatically, but here we do this only once.
-        self.infile.seek(0)
-        firstblock = self.infile.read(pdlparser.FIRSTBLOCKSIZE)
-        try :
-            self.infile.seek(-pdlparser.LASTBLOCKSIZE, 2)
-            lastblock = self.infile.read(pdlparser.LASTBLOCKSIZE)
-        except IOError :    
-            lastblock = ""
-        self.infile.seek(0)
-        if not firstblock :
+        if not os.stat(self.filename).st_size :
             raise pdlparser.PDLParserError, "input file %s is empty !" % str(self.filename)
-        else :    
-            # IMPORTANT : the order is important below. FIXME.
-            for module in (postscript, \
-                           pclxl, \
-                           pdf, \
-                           qpdl, \
-                           spl1, \
-                           dvi, \
-                           tiff, \
-                           zjstream, \
-                           ooo, \
-                           hbp, \
-                           lidil, \
-                           pcl345, \
-                           escp2, \
-                           escpages03, \
-                           plain) :     # IMPORTANT : don't move this one up !
-                try :               
-                    return module.Parser(self.infile, self.options.debug, firstblock, lastblock)
-                except pdlparser.PDLParserError :
-                    pass # try next parser
+        # IMPORTANT : the order is important below. FIXME.
+        for module in (postscript, \
+                       pclxl, \
+                       pdf, \
+                       qpdl, \
+                       spl1, \
+                       dvi, \
+                       tiff, \
+                       zjstream, \
+                       ooo, \
+                       hbp, \
+                       lidil, \
+                       pcl345, \
+                       escp2, \
+                       escpages03, \
+                       plain) :     # IMPORTANT : don't move this one up !
+            try :               
+                return module.Parser(self.filename, self.options.debug)
+            except pdlparser.PDLParserError :
+                pass # try next parser
         raise pdlparser.PDLParserError, "Analysis of first data block failed."
             
@@ -254,5 +227,5 @@
             sys.stderr.flush()
         if not options.colorspace :    
-            print "%s" % totalsize
+            print "%i" % totalsize
         else :    
             print "\n".join(lines)
