# Calculate the IRNSS G2 offset table for lm_catab.c
from mutils import *
from group_mp_slope import hex2array, lfsr

# 1 + x^2 + x^12 + x^13 + x^14 : 14-bit version
taps_14 = [2,12,13,14]
# 1 + x^3 + x^10
taps_10 = [3,10]

def array2hex(ary):
    word = 0
    for val in reversed(ary):
        word = (word<<1) | val
    return word

def do_table(taps,n_bits,f_out):
    code_len = int(2**n_bits)
    reg = hex2array(code_len-1, n_bits)
    count = 1
    out = [0]*code_len
    while True:
        out[array2hex(reg)] = count
        lfsr( taps, reg )
        count += 1
        if count == code_len:
            break
    n_digits = int(log10(max(out)))+2
    fmt_str = "%%%dd," % n_digits
    n_cols = round(70/(n_digits+2))
    for i,val in enumerate(out):
        print(fmt_str%val,end='',file=f_out)
        if i%n_cols==n_cols-1:
            print('',file=f_out)

print("generating temp.txt - lm_catab.c's g1_14b_revlookup")
with open('temp.txt','w') as f_out:
    #do_table(taps_10,10,f_out)
    do_table(taps_14,14,f_out)
