import sys
import Image
from array import array

mem = array('B', [0] * 16384)
i = 0
for l in open(sys.argv[1]):
    if l[0] != '@':
        for vv in l.split():
            if len(vv) == 2:
                mem[i] = int(vv, 16)
                i += 1
            elif len(vv) == 4:
                mem[i] = int(vv[2:], 16)
                i += 1
                mem[i] = int(vv[:2], 16)
                i += 1

cims = []
for ch in range(256):
    cim = Image.new("P", (8, 8))
    pixels = array('B', 64 * [0])
    chr = mem[4096 + 16 * ch:4096 + 16 * (ch + 1)]
    for y in range(8):
        for x in range(8):
            b = chr[y * 2 + (x / 4)] << (x & 3)
            b1 = (b & 0x80) != 0
            b0 = (b & 0x08) != 0
            # print x, y, hex(b), b1, b0, 2 * b1 + b0
            pixels[8 * y + x] = 2 * b1 + b0
    cim.fromstring(pixels)

    pal = array('H', mem[8192 + 8 * ch:8192 + 8 * (ch + 1)].tostring())
    pal.byteswap()
    def rgb(v):
        (r,g,b) = (8 * (31 & (v >> 10)), 8 * (31 & (v >> 5)), 8 * (31 & v))
        r &= 0xe0
        g &= 0xe0
        b &= 0xe0
        return (r, g, b)
    flatpal = sum([rgb(p) for p in pal], ())
    cim.putpalette(flatpal)
    cims.append(cim.convert("RGB"))

screen = Image.new("RGB", (512, 512))
for y in range(64):
    for x in range(64):
        screen.paste(cims[mem[64 * y + x]], (8 * x, 8 * y))
screen.save("screen.png")
