#!/usr/bin/python

import sys, re, urllib

SOURCE_URL = "https://raw.githubusercontent.com/mozilla/gecko-dev/master/layout/mathml/mathfont.properties"
OUTPUT_FILE = "crengine/src/mathml_operators.h"

pat = re.compile("^operator.([^.]+).(\w+) = lspace:(\d+) rspace:(\d+)(.*?) # (.*)$")
SEEN_FLAGS = {}
SEEN_OPERATORS = {}

u = urllib.urlopen(SOURCE_URL)
for line in u.readlines():
    line = line.strip()
    if line.startswith("#") or line == "":
        continue;
    mo = pat.match(line)
    if not mo:
        print "ERR %s" % line
    operator, pos, lspace, rspace, flags, comment = mo.groups()
    operator = operator.replace("\\u", "\\x")
    pos = "MATHML_OP_%s" % pos.upper()
    lspace = int(lspace)
    rspace = int(rspace)
    flags = flags.strip().split()
    oflags = []
    for flag in flags:
        if flag.startswith("direction:"):
            flag = flag[10:]
        oflag = "MATHML_OP_%s" % flag.upper()
        oflags.append(oflag)
        SEEN_FLAGS[oflag] = True
    flags = "|".join(oflags)
    if not flags:
        flags = "0"
    oline = """{U"%s", %18s, %d, %d, %s}, // %s""" % (operator, pos, lspace, rspace, flags, comment)
    if not SEEN_OPERATORS.has_key(operator):
        SEEN_OPERATORS[operator] = []
    SEEN_OPERATORS[operator].append(oline)

f = open(OUTPUT_FILE, "w")
f.write("/* Generated by tools/gen_mathml_operators_h.py */\n")
for text, lines in sorted(SEEN_OPERATORS.items()):
    for line in sorted(lines):
        f.write("%s\n" % line)
f.close()
for flag in sorted(SEEN_FLAGS):
    print flag
