import os
import sys
import re
import io
import codecs
from xml.sax.saxutils import quoteattr

def encode_name(name):
    def allowed(char):
        if ord('0') <= char <= ord('9'):
            return True
        if ord('A') <= char <= ord('Z'):
            return True
        if ord('a') <= char <= ord('z'):
            return True
        if char == ord('.') or char == ord('-') or char == ord('_'):
            return True
        return False

    def magic(x):
        if x < 10:
            return 48 + x # '0' + x
        else:
            return 65 + (x-10) # 'A' + (x-10)

    def tohex(char):
        result = bytearray(b'$')

        lo = char & 0xF
        hi = (char >> 4) & 0xF

        result.append(magic(hi))
        result.append(magic(lo))

        return result


    name = bytearray(name, encoding='utf-8')
    result = bytearray()

    for char in name:
        if allowed(char):
            result.append(char)
        else:
            result += tohex(char)

    return result.decode('utf-8')

def make_elem(label, code, defn):
    fmt = '<node name={} label={} code={} proj4={} />'

    name = quoteattr(encode_name(label))
    label = quoteattr(label)
    code = quoteattr(code)
    defn = quoteattr(defn)

    return fmt.format(name, label, code, defn)

label_re = re.compile(r'#\s+(?P<label>.*)')
defn_re = re.compile(r'<(?P<code>\d+)>\s+(?P<defn>.*)')


with io.open(sys.argv[1], 'r', encoding='utf-8') as fp:
    label = None
    defn = None
    code = None

    outputFile = codecs.open("epsg.xml", "w", "utf-8")
    outputFile.write('<node name="epsg">\n')
    for line in fp:
        mo = label_re.match(line)
        if mo:
            label = mo.group('label')
            continue

        mo = defn_re.match(line)
        if mo:
            code = mo.group('code')
            defn = mo.group('defn')

            outputFile.write(make_elem(label, code, defn))
            outputFile.write('\n')

            label = code = defn = None

    outputFile.write('</node>')
    outputFile.close()