#!/usr/bin/env python3
import re
import sys
import os
from pathlib import Path

if(len(sys.argv)!=3):
        sys.exit("[ERROR] Usage: map_ports YOSYS_BLIF_FILE MOCKTURTLE_BLIF_FILE")

yosys_file = sys.argv[1]
mockturtle_file = sys.argv[2]

print("mapping: " + mockturtle_file + " to " + yosys_file)

os.system('pwd')

inputVariables = []
outputVariables = []

with open(yosys_file, 'r') as infile:
    lines = infile.readlines()


for line in lines:
    if line.startswith(".inputs"):
        inputs = line.split()
        inputVariables = inputs[1:]

    if line.startswith(".outputs"):
        outputs = line.split()
        outputVariables = outputs[1:]

#print('input variables',inputVariables)
#print('ouput variables',outputVariables)

replacementList = {}

for x in range(len(inputVariables)):
    inputReplaceVar = "pi" + str(x + 1)
    replacementList.update({inputReplaceVar:inputVariables[x]})

for x in range(len(outputVariables)):
    inputReplaceVar = "po" + str(x)
    replacementList.update({inputReplaceVar:outputVariables[x]})

#print('replacement list:',replacementList)

#construct mapped path
#mapped_file_parts = mockturtle_file.split('/')
#mapped_file_parts[-1] = "muxig" + mapped_file_parts[-1]
#mapped_file = "/".join(mapped_file_parts)
mapped_path = Path(mockturtle_file)
mapped_name = mapped_path.name.replace("_temp", "")
mapped_file = mapped_path.with_name(mapped_name)

#replace the replacement items in the blif Mockturtle file back to yosys input and outputs
with open(mockturtle_file, 'r') as mockfile:
    with open(mapped_file, 'w') as outfile:
        for line in mockfile:
            for src, target in replacementList.items():
                line = line.replace(src + " ", target + " ")
                if line.endswith(src+'\n'):
                    line = line[:-len(src)-1] + target + '\n'
            outfile.write(line)

#print("Output written to ", mapped_file)
