import sys
import csv

def next_l(it):
    n = next(it)
    while not n.strip():
        n = next(it)
    return n.strip()

def next_s(it):
    n = next(it)
    return n.strip()

def parse_bit(s):
    if ':' in s:
        a, b = s.split(':')
        return int(a, 10), int(b, 10)
    else:
        return int(s, 10)

def parse(lines):
    it = iter(lines)

    while True:
        try:
            name = next_l(it)
            assert name not in {'Bit', 'Description'}
        except StopIteration:
            return
        n = next_l(it)
        assert n == 'Bit', n
        bits = []
        n = next_s(it)
        while n != 'Description' and n != 'Name':
            bits.append(parse_bit(n))
            n = next_s(it)
        names = []
        if n == 'Name':
            n = next_s(it)
            while n != 'Description':
                names.append(n)
                n = next_s(it)
        assert n == 'Description'
        descriptions = []
        n = next_s(it)
        while n != '':
            descriptions.append(n)
            n = next_s(it)
        assert len(descriptions) == len(bits), (descriptions, bits)
        if names:
            assert len(names) == len(bits), (names, bits)
        yield name, bits, names, descriptions

def generate_csv(parsed):
    with open(sys.argv[2], 'w', newline='') as f:
        writer = csv.writer(f)
        for name, bits, _, descriptions in parsed:
            for bit, description in zip(bits, descriptions):
                bits = str(bit) if type(bit) is int else ':'.join(map(str, bit))
                writer.writerow([name, bits, description])
            writer.writerow([])

with open(sys.argv[1], 'r') as f:
    buf = f.read()
lines = buf.split('\n')
#list(parse(lines))
generate_csv(parse(lines))
