import sys
import Image
import array

import gameduino
import gameduino.prep as gdprep
import gameduino.compress

bg = Image.open("world1-1.png")
bg = bg.crop((0,8,bg.size[0], bg.size[1]-16))
print bg.size

(picdata, chrdata, paldata) = gdprep.encode(bg)
print len(chrdata) / 16, 'chars'
w = bg.size[0] / 8
h = bg.size[1] / 8
tiles = {}
print len(picdata), w, h, w * h
map = []
for y in range(0, h, 2):
    line1 = picdata[y * w:(y+1) * w]
    line2 = picdata[(y+1) * w:(y+2) * w]
    for x in range(0, w, 2):
        tile = (line1[x:x+2] + line2[x:x+2]).tostring()
        if not tile in tiles:
            tiles[tile] = len(tiles)
        map.append(tiles[tile])
map = array.array('B', map).tostring()

cc = gameduino.compress.Codec(b_off = 8, b_len = 6)
print len(tiles), "tiles"
print 'map compressed to', len(cc.toarray(map))

import gameduino.sim
gd = gameduino.sim.Gameduino()
gd.wrstr(gameduino.RAM_CHR, chrdata)
gd.wrstr(gameduino.RAM_PAL, paldata)
gd.fill(0, 255, 4096)
for ti in tiles:
    i = tiles[ti]
    x = (i % 8) * 4
    y = (i / 8) * 4
    gd.putstr(x, y, ti[:2])
    gd.putstr(x, y+1, ti[2:])
gd.im().save("out.png")
