import Image
import array

chars = Image.open("chr.png")
charset = [chars.crop((x, y, x+8, y+8)) for y in range(0, 128, 8) for x in range(0, 128, 8)]
map = array.array('B', open("map").read())
tileset = array.array('B', open("tiles").read())

final = Image.new("RGB", (512, 2048))
used = set()
for y in range(128):
    for x in range(32):
        t = map[y * 32 + x]
        tile = tileset[4*t:4*t+4]
        used |= set(tile)
        final.paste(charset[tile[0]], (16 * x, 16 * y))
        final.paste(charset[tile[1]], (16 * x + 8, 16 * y))
        final.paste(charset[tile[2]], (16 * x, 16 * y + 8))
        final.paste(charset[tile[3]], (16 * x + 8, 16 * y + 8))
final.save("final.png")

if 1:
    chars = Image.new("L", (128,128))
    for y in range(16):
        for x in range(16):
            cc = 16 * y + x
            if cc in used:
                chars.paste(charset[cc], (8 * x, 8 * y))
    chars.save("usedchr.png")
