#!/usr/bin/python

import os, sys, string

def to_short(bytes):
  return bytes[0] << 8 | bytes[1]

def to_long(bytes):
  return bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8  | bytes[3]

def decode_mario(comp):
  length = to_long(comp[4:8])
  r_off = to_long(comp[8:12])
  v_off = to_long(comp[12:16])
  flags = comp[16:r_off]
  runs = comp[r_off:v_off]
  verbatim = comp[v_off:]
  flags.reverse()
  runs.reverse()
  verbatim.reverse()
  s = ''
  num_flags=0

  while length:
    if num_flags == 0:
      f = to_long([flags.pop(), flags.pop(), flags.pop(), flags.pop()])
      num_flags = 32
    
    if f & 0x80000000:
      s = s + chr(verbatim.pop())
      length = length - 1
    else:
      code = to_short([runs.pop(), runs.pop()])
      runlen = ((code >> 12) & 0xf) + 3
      offset = len(s) - (code & 0xfff) - 1
      while runlen:
        s = s + s[offset]
        offset = offset + 1
        runlen = runlen - 1
        length = length - 1
    f = f << 1
    num_flags = num_flags - 1

  return s

out = []
lines = open(sys.argv[1]).readlines()
for l in lines:
  if string.find(l, ',') != -1:
    s = string.split(l, ',')
    for h in s:
      if h != '\n':
        out.append(string.atoi(h, 16))

t = decode_mario(out)
    
sys.stdout.write("P6\n%s %s\n255\n" % (sys.argv[2], sys.argv[3]))
for i in xrange(0, len(t), 2):
  s = ord(t[i]) << 8 | ord(t[i+1])
  r = (s >> 11) & 0x1f
  g = (s >>  6) & 0x1f
  b = (s >>  1) & 0x1f
  sys.stdout.write(chr(r<<3))
  sys.stdout.write(chr(g<<3))
  sys.stdout.write(chr(b<<3))



