#!/usr/bin/env python
import re
import sys

# maybe https://github.com/fukatani/Pyverilog-1

txt = open(sys.argv[1], 'r').read()

modname = None
params = []
ios = []

for l in txt.split('\n'):
    l = l.strip()

    # module RAMB18E1 (
    m = re.match(r'module (.*) ', l)
    if m:
        modname = m.group(1)
        continue

    # input CLKARDCLK,
    # input [13:0] ADDRARDADDR,
    # output [1:0] DOPBDOP
    m = re.match(r'(input|output)( \[([0-9]*):([0:9]*)\] | )([a-zA-Z0-9_ ,]+)', l)
    if m:
        names = m.group(5)
        aio = m.group(1)
        
        for name in names.split(','):
            name = name.strip()
            if not name:
                continue
            wout = None
            width = m.group(2).strip()
            if width:
                mw = re.match(r'\[([0-9]*):([0:9]*)\]', width)
                wl = int(mw.group(1))
                wr = int(mw.group(2))
                wout = (wl, wr)

            ios.append((name, aio, wout))
        continue

    # output DPO, SPO,
    # input  D, WCLK, WE,
    m = re.match(r'(input|output)(.*)', l)
    if m:
        aio = m.group(1)
        wout = None
        for name in m.group(2).split(','):
            name = name.strip()
            if not name:
                continue
            ios.append((name, aio, wout))

    # parameter SIM_DEVICE = "VIRTEX6";
    m = re.match(r'parameter([ ])([a-zA-Z0-9_]+) = (.+);', l)
    if m:
        #aio = m.group(1)
        name = m.group(2)
        defval = m.group(3)

        wout = None
        params.append((name, wout, defval))


    # input A0, A1, A2, A3, A4, A5, D, WCLK, WE;
    
modinst = modname

print '''\
module my_%s (input clk, input [7:0] din, output [7:0] dout);
    parameter LOC = "";
''' % modname

print '    (* LOC=LOC, KEEP, DONT_TOUCH *)'
print '    %s #(' % modname
for pi, p in enumerate(params):
    name, wout, defval = p
    comma = ',' if pi != len(params) - 1 else ''

    print '            .%s(%s)%s' % (name, defval, comma)

print '        ) %s (' % modinst

DII_N = 8
DOI_N = 8
dii = 0
doi = 0
for ioi, io in enumerate(ios):
    name, aio, wout = io
    comma = ',' if ioi != len(ios) - 1 else ');'

    if aio == 'input':
        if wout:
            n = int(abs(wout[1] - wout[0]) + 1)
            if dii + n >= DII_N:
                dii = 0
            wire = 'din[%d:%d]' % (dii + n, dii)
            dii = (dii + n) % DII_N
        else:
            wire = 'din[%d]' % dii
            dii = (dii + 1) % DII_N
    else:
        if wout:
            n = int(abs(wout[1] - wout[0]) + 1)
            wire = 'dout[%d:%d]' % (doi + n, doi)
            doi = doi + n
        else:
            wire = 'dout[%d]' % doi
            doi += 1
    print '            .%s(%s)%s' % (name, wire, comma)

print 'endmodule'

