
def bbchex(s):
    if s[0] == '-':
        return -bbchex(s[1:])
    if s[0] == '&':
        return int(s[1:], 16)
    else:
        return int(s)


def ring(L):
    """ Given a vertex list, returns the edge list """
    ee = zip(L, L[1:]) + [(L[-1],L[0])]
    return [tuple(sorted(e)) for e in ee]

class Item:
    def __init__(self, name):
        self.name = name
        self.vertices = []
        self.faces = []

    def normalize(self):
        g = max([abs(c) for c in sum(self.vertices, [])])
        print self.name, g
        dim = 63
        if g > 0:
            print self.name
            s = float(dim) / g
            self.vertices = [(int(x*s), int(y*s), int(z*s)) for (x,y,z) in self.vertices]

    def dump(self, dst):

        self.normalize()

        arr = "static PROGMEM prog_%s %s[] = {"
        print >>dst, arr % ("char", self.name + "_vertices")
        print >>dst, ", ".join(["%d,%d,%d" % tuple(v) for v in self.vertices])
        print >>dst, "};"

        print >>dst, arr % ("uchar", self.name + "_edges")
        edges = set(sum([ring(f) for f in self.faces], []))
        print >>dst, ", ".join(["%d,%d" % tuple(e) for e in edges])
        print >>dst, "};"
        return '{ "%s", %d, %s_vertices, %d, %s_edges },' % (self.name, len(self.vertices), self.name, len(edges), self.name)

item = None
db = []
for l in open("ELITE.TXT"):
    def ignore(ll):
        pass
    def vx(ll):
        global item
        item.vertices.append([bbchex(e) for e in ll])
    def fc(ll):
        global item
        item.faces.append([int(e) for e in ll[5:]])
    def newname(ll):
        global item
        if not '&' in ll[0]:
            item = Item(ll[0])
            db.append(item)
    l = l.strip()
    if l == "" or l.startswith("REM"):
        pass
    elif l == ":":
        handle = newname
    elif l == "vertices":
        handle = vx
    elif l == "faces":
        handle = fc
    elif l == "hue-lig-sat":
        handle = ignore
    else:
        handle(l.split(','))

dst = open("eliteships.h", "wt")
decls = []
for i in db:
    decls.append(i.dump(dst))
print >>dst, "static ship eliteships[] = {"
print >>dst, "\n".join(decls)
print >>dst, "};"
