#!/usr/bin/python
import sys
import Image

def read_bad_cell(f):
    while not (f.read(1)) == '[': pass

    enclosure = 1
    while True:
        ch = f.read(1)
        
        if   ch == '[':
            enclosure += 1
        elif ch == ']':
            enclosure -= 1

        if enclosure == 0:
            return "000000"

def read_matrix_cell(f):
    mode = False
    cell = ""

    while True:
        ch = f.read(1)

        if   ch == '}': return None
        elif ch == ',': pass
        elif ch == ' ': pass
        elif ch == '"' and (mode == False):
            mode = True
        elif ch == '"' and (mode == True):
            return cell
        elif ch == 'S':
            return read_bad_cell(f)
        elif mode:
            cell += ch
        else: pass

def read_matrix_row(f):
    while True:
        ch = f.read(1)
        if   ch == '}': return None
        elif ch == '{': break
        elif ch == ',': pass

    row = []
    while True:
        x = read_matrix_cell(f)
        if x == None:
            return row
        row.append(x)

def read_matrix_rows(f):
    while not (f.read(1)) == '{': 
        pass

    rows = []
    while True:
        x = read_matrix_row(f)
        if x == None:
            return rows
        rows.append(x)

def to_color(s):
    t = (s[0:2], s[2:4], s[4:6])
    return tuple(map(lambda x: int(x, 16), t))

def file_to_matrix(filename):
    try:
        f = file(filename)
    except:
        sys.exit(1)

    return read_matrix_rows(f)

if __name__ == '__main__':
    ifilename = sys.argv[1]
    ofilename = sys.argv[2]

    m = file_to_matrix(ifilename)

    import Image
    (w, h) = (len(m[0]), len(m))
    im = Image.new('RGB', (w, h))

    for row in xrange(0, h):
        for col in xrange(0, w):
            im.putpixel((col, row), to_color(m[row][col]))

    im.save(ofilename)
