import sys
import time
import math
import array
import Image
import math
import pickle

def readz80(z80file):
    z80 = array.array('B', open(z80file).read()).tolist()
    mem = []
    comp = z80[30:]
    while True:
      if comp == [0, 0xed, 0xed, 0]:
        break
      if comp[0:2] == [0xed, 0xed]:
        mem += [comp[3]] * comp[2]
        comp = comp[4:]
      else:
        mem.append(comp.pop(0))
    assert len(mem) == 0xc000
    return array.array('B', mem)

m = array.array('B', [0]*0x4000) + readz80("kl1.z80")
open("dump", "w").write(m.tostring())
sprite_offset = array.array('H', m[0x7112:0x728a].tostring())
storage = 0
sprites = [None for i in range(256)]
for i,a in enumerate(sprite_offset):
    w = m[a] & 7
    h = m[a+1]
    if w:
        data = m[a+2:a+2+(w*h)*2]
        msk = Image.fromstring("1", (8 * w, h), data[::2].tostring()).transpose(Image.FLIP_TOP_BOTTOM)
        spr = Image.fromstring("1", (8 * w, h), data[1::2].tostring()).transpose(Image.FLIP_TOP_BOTTOM)
        sprites[i] = (msk, spr)
        preview = Image.blend(spr.convert("L"), msk.convert("L"), 0.25)
        preview.save("x%03d.png" % i)
        req = ((w + 1) & ~1) * ((h + 15) & ~15) * 2
        storage += req

bgtypes = []
for bg in array.array('H', m[0x6ce2:0x6d12].tostring()):
    a = bg
    dat = []
    while m[a]:
        spr,x,y,z,xd,yd,zd,flips = m[a:a+8]
        a += 8
        dat.append((spr,x,y,z,xd,yd,zd,flips))
    bgtypes.append(dat)

im = Image.new("L", (256, 192), 64)
for (spr,x,y,z,xd,yd,zd,flips) in bgtypes[0x0]:
    py = 40 + (x / 2) + (y / 2)
    x &= ~15
    y &= ~15
    px = 128 + (x - y)
    print spr, (x, y, z), (xd,yd,zd), "%#02x" % flips, (px, py)
    # im.putpixel((px, py), 255)
    (msk,spr) = sprites[spr]
    py -= msk.size[1]
    if flips & 128:
        msk = msk.transpose(Image.FLIP_LEFT_RIGHT)
        spr = spr.transpose(Image.FLIP_LEFT_RIGHT)
    ma = Image.new("L", (256, 192))
    ma.paste(msk, (px, py))
    co = Image.new("L", (256, 192))
    co.paste(spr, (px,py))
    im = Image.composite(co, im, ma)
im.save("out.png")
