#! /usr/bin/env python

import sys

def read_td_box(infile):
  boxes = []
  # read all lines
  with open(infile, "rt") as f:
    for line in f:
      boxes_line = []
      # process all words
      for word in line.split():
        # parse word, should be <dev>-<box> or <dev>-<rox>-[rRh]
        # r: rotated 90 degree clockwise,
        # R: rotated 90 degrees counter-clockwise
        # h: rotated 180 degrees
        parts = word.split("-")
        if len(parts) < 2:
          raise "invalid pixel box string \"%s\"" % (word)
        dev = int(parts[0], 0)
        box = int(parts[1])
        if box < 1 or box > 16:
          raise "invalid box number \"%s\", must be 1..16" % (parts[1])
        rot = 0
        if len(parts) >= 3:
          if parts[2] == 'r':
            rot = 90
          if parts[2] == 'R':
            rot = 270
          if parts[2] == 'h':
            rot = 180
        # append box
        boxes_line.append({"dev": dev, "box": box, "rot": rot})
      # append boxes line
      boxes.append(boxes_line)
      # check that all lines have got the same length
      if len(boxes[0]) != len(boxes[-1]):
        raise "line %u has got different length than line 1" % (len(boxes) + 1)
  return boxes

def boxes2pixels(boxes):
  pixels = []
  for boxes_line in boxes:
    for y in range(0, 8):
      pixel_line = []
      for box in boxes_line:
        for x in range(0, 8):
          rot = box["rot"]
          if rot == 90:
            xx = y
            yy = 7 - x
          elif rot == 270:
            xx = 7 - y
            yy = x
          elif rot == 180:
            xx = 7 - x
            yy = 7 - y
          else:
            xx = x
            yy = y
          pixel_line.append({"dev": box["dev"],
                             "out": (box["box"] - 1) * 2 + yy / 4,
                             "pix": yy % 4 * 8 + xx})
      pixels.append(pixel_line)
  return pixels

def write_td_fmt(outfile, pixels):
  with open(outfile, "wt") as f:
    print >>f, "%u %u" % (len(pixels[0]), len(pixels))
    for pixel_line in pixels:
      line = "";
      for pixel in pixel_line:
        line = line + "%02u-%02u-%02u " % (pixel["dev"], pixel["out"],
                                           pixel["pix"])
      print >>f, line

def main(argv):
  # check parameters
  if len(argv) < 3:
    print >>sys.stderr, "usage td_box2td_fmt <x.td_box> <x.td_fmt>"
    return 2
  infile = argv[1]
  outfile = argv[2]
  # read boxes input file
  boxes = read_td_box(infile)
  # convert boxes to pixels
  pixels = boxes2pixels(boxes)
  # generate output
  write_td_fmt(outfile, pixels)
  return 0

if __name__ == "__main__":
   sys.exit(main(sys.argv))

