import sys
import Image
from array import array

# im = Image.open("0-4.png").convert("P", palette=Image.WEB, colors = 255)

if 0:
    im = Image.open("ball.gif")
    transparent = im.info['transparency']

def rotations(im):
    nf = 4
    (w,h) = im.size
    frames = Image.new(im.mode, (w,h*nf))
    for i in range(nf):
        frames.paste(im.rotate(i*90/nf, Image.NEAREST) , (0,h*i))
    return frames

def tile(im):
    (w,h) = im.size
    n = Image.new(im.mode, (16, (w/16) * h))
    i = 0   # tile counter
    for y in range(0, h, 16):
        for x in range(0, w, 16):
            n.paste(im.crop((x,y,x+16,y+16)), (0, 16 * i))
            i += 1
    n.save("preview.png")
    return n

if 1:
    im = Image.open("rock1.png")
    im = rotations(im)
    im = tile(im)
    # Get the alpha band
    if im.mode == "RGBA":
        alpha = im.split()[3]
        # Convert the image into P mode but only use 255 colors in the palette out of 256
        im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
        # Set all pixel values below 128 to 255,
        # and the rest to 0
        mask = Image.eval(alpha, lambda a: 255 if a <=128 else 0)
        # Paste the color of index 255 and use alpha as a mask
        im.paste(255, mask)
        transparent = 255
    else:
        im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
        transparent = None

lut = im.resize((256,1))
lut.putdata(range(256))
palstr = lut.convert("RGB").tostring()
if 0:
    rgbs = zip(*(array('B', palette[i:i+256]) for i in [0,256,512]))
else:
    rgbs = zip(*(array('B', palstr[i::3]) for i in range(3)))
rgb555 = [(((r / 8) << 10) | ((g / 8) << 5) | (b / 8)) for (r,g,b) in rgbs]
paldump = open("palette", "w")
for i,e in enumerate(rgbs):
    print >>paldump, i, e
if transparent is not None:
    rgb555[transparent] |= 0x8000

def dump(hh, name, data):
    print >>hh, "PROGMEM prog_uchar %s[] = {" % name
    for c in array('B', data.tostring()):
        print >>hh, "0x%02x," % c
    print >>hh, "};"

hh = open("/home/jamesb/sketchbook/gameduino/data.h", "w")
dump(hh, "palette", array('H', rgb555))
dump(hh, "image", im);
