import sys
import Image
import GDprep
import array
from compress import Codec

imageram = GDprep.ImageRAM()

bg = Image.open("gdlogobg.png")
bg64 = Image.new(bg.mode, (512,512))
bg64.paste(bg, (0,0))
(picdata, chrdata, paldata) = GDprep.encode(bg64)
print len(picdata) / 16, "chars"
fn = "logo"
hh = open("../../logo.h", "w")
GDprep.dump(hh, "%s_pic" % fn, picdata)
GDprep.dump(hh, "%s_chr" % fn, chrdata)
GDprep.dump(hh, "%s_pal" % fn, paldata)

fg = Image.open("gdlogofg.png")
(pim, pal) = GDprep.pal555(fg, 15)
sprvals = []
palettes = [GDprep.PALETTE256A, GDprep.PALETTE256B]
for x in range(0, pim.size[0], 16):
    print x
    slice = pim.crop((x, 0, x + 16, pim.size[1]))
    bars = [slice.crop((0, y, 16, y + 1)) for y in range(pim.size[1])]
    nb = [GDprep.isnonblank(b, pal) for b in bars]
    y0 = nb.index(True)
    y1 = slice.size[1] - nb[::-1].index(True)
    for y in range(y0, y1, 16):
        tile = slice.crop((0, y, 16, y + 16))
        tile.save("spr%03d.png" % len(sprvals))
        (pg, sprpal) = imageram.add(array.array('B', tile.tostring()), 16)
        sprval = (8 + x) + ((103 + y) << 16) + (pg << 25) + (palettes[sprpal] << 12)
        sprvals.append(sprval)
        print "%08x" % sprval
print len(imageram.used())
GDprep.dump(hh, "sprvals", array.array('L', sprvals))
if 0:
    GDprep.dump(hh, "sprimg", array.array('B', imageram.used()))
else:
    cc = Codec(b_off = 8, b_len = 3)
    uncompressed = imageram.used().tostring()
    compressed = cc.toarray(uncompressed)
    print "compressed to", len(compressed)
    GDprep.dump(hh, "sprimg_compressed", compressed)
GDprep.dump(hh, "palette16a", array.array('H', pal))
