#!/usr/bin/python

# tz_netpbm.py
#       --copyright--                   Copyright 2012 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       September 1, 2012       bar
#       December 26, 2012       bar     add a missing assignment that isn't used, really
#       --eodstamps--
##      \file
#       \namespace              tzpython.tz_netpbm
#
#
#       Do what I need to do with .pbm .pgm .ppm files.
#
#       This IS NOT RIGHT!  http://netpbm.sourceforge.net/doc/pbm.html  has the skivvy.
#           But it gets the comments from files put out by a special program.
#
#


import  re



##                  The start of a files

MAGIC_BYTES_TO_EXT      = {
                            "P1" : '.pbm',
                            "P2" : '.pgm',
                            "P3" : '.ppm',
                            "P4" : '.pbm',
                            "P5" : '.pgm',
                            "P6" : '.ppm',
                          }

EXT_TO_MAGIC_ASC_BYTES  = {
                            '.pbm' : "P1",
                            '.pgm' : "P2",
                            '.ppm' : "P3",
                          }
EXT_TO_MAGIC_BIN_BYTES  = {
                            '.pbm' : "P4",
                            '.pgm' : "P5",
                            '.ppm' : "P6",
                          }

MAGIC_BYTES_TO_ASC      = {
                            "P1" : True,
                            "P2" : True,
                            "P3" : True,
                            "P4" : False,
                            "P5" : False,
                            "P6" : False,
                          }


class a_netpbm_file(object) :
    """ Class whose objects are .pbm .pgm .ppm file data and information. """

    def __init__(me, fi) :
        """ Constructor. """

        me.comments         = []
        me.fn               = None
        me.width            = 0
        me.hite             = 0
        me.maxp             = 0

        if  fi              :

            if  isinstance(fi, basestring) :
                me.fn       = fi
                fi          = open(fi, "rb")

            me.magic_bytes  = fi.read(2)
            if  me.magic_bytes not in MAGIC_BYTES_TO_EXT :
                if  me.fn   :
                    fi.close()
                raise ValueError("File %s not a netpbm (.pbm .pgm .ppm) file!" % str(me.fn))

            me.all          = me.magic_bytes + fi.read()

            es              = ""
            if  me.fn       :
                fi.close()
                es          = me.fn

            la              = re.split(r"\n", me.all)
            i               = 1
            while i < len(la) :
                s           = la[i]
                if  not s.startswith('#') :
                    break
                me.comments.append(s[1:].rstrip())
                i          += 1

            if  i >= len(la) :
                raise ValueError("File %s does not have width hite!" % es)
            g               = re.search(r"\s*(\d+)\s+(\d+)", la[i])
            if  not g       :
                raise ValueError("File %s does not have valid width hite [%s]!" % ( es, la[i], ) )
            me.width        = int(g.group(1))
            me.hite         = int(g.group(2))
            i              += 1

            me.maxp         = 1
            if  la[0][0:2] not in [ 'P1', 'P4' ] :
                me.maxp     = 0

                if  i >= len(la) :
                    raise ValueError("File %s does not have max pixel value!" % es)
                g               = re.search(r"\s*(\d+)", la[i])
                if  not g       :
                    raise ValueError("File %s does not have valid max pixel value!" % es)
                me.maxp         = int(g.group(1))
            pass

        pass


    pass        #       a_netpbm_file


if  __name__ == '__main__' :
    import  sys

    import  TZCommandLineAtFile


    program_name    = sys.argv.pop(0)
    TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)

    while len(sys.argv) :
        fn  = sys.argv.pop(0)

        im  = a_netpbm_file(fn)

        print "Fn=[%s] comments=%s width=%d hite=%d maxp=%d" % ( fn, str(im.comments), im.width, im.hite, im.maxp )

    pass



#
#
# eof
