#!/usr/bin/env python

import sys
import struct

import serial
import Image

speed = 9600
speed = 1000000

im = Image.new("RGB", (400,300))
pix = im.load()

# klog = open("keys.log", "r")
log = open("log", "w")
print ">>>"
ser = serial.Serial(sys.argv[1], speed)
while True:
    ser.write(chr(101))
    s = ser.read(1)
    chk = ord(s)
    if chk != 0xa5:
        sys.stdout.write(s)
        sys.stdout.flush() 
        log.write(s)
    else:
        (frame,) = struct.unpack("<H", ser.read(2))
        if chk == 0x50:
            s = klog.read(2)
            ser.write(s[1])
        else:
            assert chk == 0xa5, "Expected sync byte 0xa5 but got byte %x instead" % chk
            filename = "screenshot%05d.png" % frame
            print "dumping frame", frame, "to", filename
            total = 0
            for y in range(300):
                (yy,) = struct.unpack("H", ser.read(2))
                x = 0
                while x < 400:
                    (v,) = struct.unpack("H", ser.read(2))
                    total += 2
                    if v & 0x8000:
                        for i in range(v & 0x7fff):
                            pix[x, yy] = 0;
                            x += 1
                    else:
                        r = (v >> 10) & 31
                        g = (v >> 5) & 31
                        b = v & 31
                        pix[x, yy] = (r * 8, g * 8, b * 8)
                        x += 1
            print "Took", total, "instead of", 300 * 400 * 2
            im.save(filename)
