#!/usr/bin/python

# tz_gimp_gpl.py
#       --copyright--                   Copyright 2007 (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--
#       August 17, 2008         bar
#       August 29, 2008         bar     basestring instead of StringType because of unicode strings and others
#       February 26, 2009       bar     allow comma separated names
#       November 5, 2011        bar     correct url
#       November 12, 2011       bar     correct (c)
#       --eodstamps--
##      \file
#
#
#       Do things with Gimp .gpl palette files.
#
#


import  re



colors_re   = re.compile(r"^[ \t]*(\d+)[ \t]+(\d+)[ \t]+(\d+)(?:[ \t]+(.*))?$", re.MULTILINE)


class   a_color(object) :

    def __init__(me, red, green, blue, name = "") :
        me.red      = red
        me.green    = green
        me.blue     = blue
        name        = name or ""
        name        = re.sub(r"\s+", " ", name)
        me.names    = [ s for s in [ n.strip() for n in name.split(",") ] if s ]
        me.name     = ""
        if  me.names :
            me.name = me.names[0]
        pass

    def __str__(me) :
        return("red=%03u:0x%02x green=%03u:0x%02x blue=%03u:0x%02x name=%s" % ( me.red, me.red, me.green, me.green, me.blue, me.blue, me.name ) )

    pass            # a_color



def read(fi) :
    """ Read a .gpl file and return the palette in an array of a_colors. """

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

    fd  = fi.read()
    if  fn :
        fi.close()


    pal = []

    ca  =   colors_re.findall(fd)
    for c in ca :
        pal.append(a_color(int(c[0]), int(c[1]), int(c[2]), c[3].rstrip()))

    return(pal)



if  __name__ == '__main__' :
    import  sys

    del(sys.argv[0])

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

        print   fn
        for c in xrange(len(pal)) :
            print "%03u:0x%02x %s" % ( c, c, pal[c] )

        print

    pass



#
#
# eof

