#---------------------------------------------------------------------------
# Write Galois Field tables as "C" code (from previous computation)
#---------------------------------------------------------------------------
# Author: Cedric Adjih
#---------------------------------------------------------------------------
# Copyright 2013-2017 Inria
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#---------------------------------------------------------------------------

import sys
import json

if len(sys.argv) < 2:
    sys.stderr.write("Syntax: python %s <log2 field order>\n" % sys.argv[0])
    sys.exit(1)

LogOrder = int(sys.argv[1])
Order = 2**LogOrder

f = open("table-gf%s.json" % Order)
info = json.loads(f.read())
f.close()

#---------------------------------------------------------------------------

mul = { (x,y):z for (x,y,z) in info["mulTable"] }
inv = { x:y     for (x,y)   in info["invTable"] }
neg = { x:y     for (x,y)   in info["negTable"] }
add = { (x,y):z for (x,y,z) in info["sumTable"] }
exp = { x:y     for (x,y)   in info["expTable"] }
log = { x:y     for (x,y)   in info["logTable"] }

def mult(x,y):
    if x == 0 or y == 0:
        return 0
    result = log[x]+log[y]
    result = (result % Order) + (result // Order) # mod [Order-1]
    return exp[result]

def checkTable():
    # Sanity checks, assuming GF(2^n)
    for x in range(Order):
        assert neg[x] == x
        for y in range(Order):
            assert add[(x,y)] == x ^ y
            assert mult(x,y) == mul[x,y]

    # Sanity checks for commutative group/ring/field
    for x in range(1, Order):
        assert mul[(inv[x],x)] == 1

    for x in range(Order):
        assert mul[1,x] == x
        assert mul[0,x] == 0
        assert add[0,x] == x

    for x in range(Order):
        for y in range(Order):
            assert mul[(x,y)] == mul[(y,x)]
            assert add[(x,y)] == add[(y,x)]
            for z in range(Order):
                assert mul[mul[x,y], z] == mul[x, mul[y,z]]
                assert add[add[x,y], z] == add[x, add[y,z]]
                assert mul[add[x,y], z] == add[mul[x,z], mul[y,z]]

def showSubGroup():
    visited = set([])
    for x in range(Order):
        if x in visited:
            continue
        subSet = set([])
        y = x
        while y not in subSet:
            subSet.add(y)
            y = mul[(x,y)]
        visited.update(subSet)
        print(x, subSet)

def reprAsCList(dataList, indent="  "):
    r = ""
    for i,v in enumerate(dataList):
        if i != 0:
            r += ","
            if i % 8 == 0: r += "\n"+indent
            else: r += " "
        r += ("%s" % v).rjust(3)
    return r

def computeMulByteTable():
    mulByte = {}

    log2log2Order = 0
    while (1<<(1<<log2log2Order)) < Order:
        log2log2Order += 1

    nbBitPerCoef = (1<<log2log2Order)
    mask = (1<<nbBitPerCoef)-1
    nbCoefPerByte = 8//nbBitPerCoef

    for x in range(Order):
        for y in range(256):
            current = 0
            for j in range(nbCoefPerByte):
                shift = (nbBitPerCoef*j)
                value = (y >> shift) & mask
                product = mul[value,x]
                current = current | (product << shift)
            mulByte[x,y] = current

    return mulByte

Copyright = """
---------------------------------------------------------------------------
 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
 "Software"), to deal in the Software without restriction, including
 without limitation the rights to use, copy, modify, merge, publish,
 distribute, sublicense, and/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to
 the following conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---------------------------------------------------------------------------
"""

def generateTableForC():
    f = open("/proc/self/cmdline")
    cmdLine = f.read().replace(chr(0), " ")
    f.close()
    
    r = "/*\n  File automatically generated by: \n"
    r += "  " + cmdLine 
    r += Copyright
    r += "*/\n\n#include <stdint.h>\n\n"

    r += "static const uint8_t gf%s_log_table[%s] = {\n" % (Order, Order)
    r += "  "+reprAsCList([log.get(x,0) for x in range(Order)])
    r += "};\n\n"

    r += "static const uint8_t gf%s_exp_table[%s] = {\n" % (Order, Order)
    r += "  "+reprAsCList([exp.get(x,0) for x in range(Order)])
    r += "};\n\n"

    f = open("table-explog-gf%s.c" % Order, "w")    
    f.write(r)
    f.close()
    

    mulByte = computeMulByteTable()
    r = "/*\n  File automatically generated by: \n"
    r += "  " + cmdLine
    r += Copyright
    r += "*/\n\n#include <stdint.h>\n\n"

    r += "static const uint8_t gf%s_mul_table[%s][%s] = {\n" % (
        Order, Order, 256)
    for x in range(Order):
        if x != 0: r += ",\n"
        r += "  { "
        r += reprAsCList([mulByte[(x,y)] for y in range(256)], "    ")
        r += " }"
    r += "\n};\n\n"

    r += "static const uint8_t gf%s_inv_table[%s] = {\n" % (Order, Order)
    r += reprAsCList([inv.get(x,0) for x in range(Order)])
    r += "};\n\n"

    f = open("table-mul-gf%s.c" % Order, "w")    
    f.write(r)
    f.close()


#---------------------------------------------------------------------------

if __name__ == "__main__":
    checkTable()
    generateTableForC()

#---------------------------------------------------------------------------
