import binascii
from loadmcs import loadmcs
import gameduino.compress as compress
import gameduino.prep as gdprep
import array

img = loadmcs("gameduino-200a.mcs")
# Careful choice of split points to give four small-enough segments
print "total pages", len(img) / 264
# split on 8-page boundaries
splits = [264*8*c for c in [18, 35, 56]]
part0 = img[:splits[0]]
part1 = img[splits[0]:splits[1]]
part2 = img[splits[1]:splits[2]]
part3 = img[splits[2]:]

hha = open("sketches/flashimgall.h", "w")       # plain binary for Mega2560
hhc = open("sketches/flashimg.h", "w")          # compressed for smaller
cc = compress.Codec(b_off = 7, b_len = 4)

revision = open("../verilog/revision.v").readline().strip()[-2:]
print >>hha, "#define REVISION 0x%s" % revision
print >>hhc, "#define REVISION 0x%s" % revision

offset = 0
for i,plain in enumerate((part0,part1,part2,part3)):
    print >>hhc, "#define P%dCRC 0x%08x" % (i, 0xffffffff & binascii.crc32(plain))
    print >>hhc, "#define P%dOFF %d" % (i, offset)
    print >>hhc, "#define P%dSIZE %d" % (i, len(plain) / 264)
    offset += len(plain) / 264
    # compressed = cc.toarray(plain)
    # print i, len(compressed)
    cc.to_cfile(hhc, plain, "part%d" % i)

STAGEBASE = 568
assert STAGEBASE + (splits[2] / 264) <= 1024, "First three parts must fit in %d pages" % (1024 - STAGEBASE)

STEP=264*8
while (len(img) % STEP) != 0:
    img += chr(0)

# img = img[:40*STEP]
nm = "img"
print >>hha, "#define %s_CRC 0x%08x" % (nm, 0xffffffff & binascii.crc32(img))
print >>hha, "#define %s_SIZE %d" % (nm, len(img) / STEP)
print >>hha, "#define %s_SUM 0x%08x" % (nm, sum(array.array('B', img).tolist()))
already = {}
for i in range(len(img) / STEP):
    pgdat = img[STEP*i:STEP*(i+1)]
    if pgdat in already:
        print >>hha, "#define %s%d %s%d" % (nm, i, nm, already[pgdat])
    else:
        gdprep.dump(hha, "%s%d" % (nm, i), array.array('B', pgdat))
        already[pgdat] = i

# print >>hha, "static PROGMEM prog_uchar* %s[] = {" % nm
# for i in range(len(img) / 264):
#     print >>hha, "%s%d," % (nm, i)
# print >>hha, "};"

print >>hha, "static void loadall() {"
for i in range(len(img) / STEP):
    print >>hha, "  loadpage(%d, GET_FAR_ADDRESS(img%d));" % (8 * i, i)
print >>hha, "}"
