#!/usr/bin/python3
import gzip

N = 6
with gzip.open('bb.6x2.unknown.txt.gz', 'rt') as f_in, open('bb.6x2.unknown.db', 'wb') as f_out:
    TMs = [l.strip() for l in f_in]
    header = bytearray(30)
    header[:4] = header[4:8] = header[8:12] = len(TMs).to_bytes(4, 'big')
    f_out.write(header)
    for TM in TMs:
        bin_tm = bytearray(6*N)
        for s in range(N):
            if s: assert TM[7*s-1] == '_'
            for b in range(2):
                write, move, goto = TM[7*s+3*b : 7*s+3*(b+1)]
                if goto == '-':
                    continue  # leave it zeroed
                write = {'0': 0, '1': 1}[write]
                move = {'L': 1, 'R': 0}[move]
                goto = ord(goto) - ord('A') + 1
                if goto > N:
                    goto = 0 # "Z" convention
                bin_tm[6*s+3*b : 6*s+3*(b+1)] = (write, move, goto)
        f_out.write(bin_tm)
