def createLine(pattern, outfile, linenum=[5726], memo={}):
    if (tuple(pattern.ravel().tolist()) not in memo):
        if (pattern.shape[0] == 2):
            outfile.write('{} {} {} {} {}\n'.format((pattern.shape[0].bit_length() + 10), pattern[(0, 0)], pattern[(0, 1)], pattern[(1, 0)], pattern[(1, 1)]))
        else:
            subpatterns = pattern.reshape(2, (pattern.shape[0] >> 1), 2, (pattern.shape[0] >> 1)).swapaxes(1, 2)
            outfile.write('{} {} {} {} {}\n'.format((pattern.shape[0].bit_length() + 10), createLine(subpatterns[(0, 0)], outfile), createLine(subpatterns[(0, 1)], outfile), createLine(subpatterns[(1, 0)], outfile), createLine(subpatterns[(1, 1)], outfile)))
        memo[tuple(pattern.ravel().tolist())] = linenum[0]
        linenum[0] += 1
    return memo[tuple(pattern.ravel().tolist())]
def createLine(pattern, outfile, linenum=[5726], memo={}):
    if (tuple(pattern.ravel().tolist()) not in memo):
        if (pattern.shape[0] == 2):
            outfile.write('{} {} {} {} {}\n'.format((pattern.shape[0].bit_length() + 10), pattern[(0, 0)], pattern[(0, 1)], pattern[(1, 0)], pattern[(1, 1)]))
        else:
            subpatterns = pattern.reshape(2, (pattern.shape[0] >> 1), 2, (pattern.shape[0] >> 1)).swapaxes(1, 2)
            outfile.write('{} {} {} {} {}\n'.format((pattern.shape[0].bit_length() + 10), createLine(subpatterns[(0, 0)], outfile), createLine(subpatterns[(0, 1)], outfile), createLine(subpatterns[(1, 0)], outfile), createLine(subpatterns[(1, 1)], outfile)))
        memo[tuple(pattern.ravel().tolist())] = linenum[0]
        linenum[0] += 1
    return memo[tuple(pattern.ravel().tolist())]