#!/usr/bin/python3

import re
import sys
import pandas as pd

# Read argument: either D-0.10 or D-0.01
exp_name = sys.argv[1]
defect = exp_name[2:]
pattern = r"-0\.125-" + re.escape(defect) + r"\.pec"
# Read CSV file generated by table-generator
df = pd.read_csv("./csv/Miter-" + exp_name + ".table.csv", sep="\t")
# Drop useless rows
df = df.drop([0, 1])
# Adjust circuit names
df = df.replace(regex=pattern, value="")
df = df.replace(regex=r"mem_ctrl", value="mem\_ctrl")
# Drop useless columns
df = df.drop(["ABC "], axis=1)
df.columns = ["Circuit", "PI", "AI", "And", "Level"]
# Read ISCAS and EPFL statistics
df_ISCAS = pd.read_csv("./csv/parsed-ISCAS.csv", sep="\t")
df_EPFL = pd.read_csv("./csv/parsed-EPFL.csv", sep="\t")
df_merged = pd.concat([df_ISCAS, df_EPFL])
# Sort the merged table and reset indices
df_sorted = df_merged.sort_values(by=["Circuit"])
df_sorted.reset_index(drop=True, inplace=True)
df.reset_index(drop=True, inplace=True)
# Compute the numbers of auxiliary inputs
df["AI"] = pd.to_numeric(df["PI"]) - df_sorted["PI"]
df["PI"] = df_sorted["PI"]
# Write out two parsed csv file
df[df["Circuit"].str.contains(r"c\d+")].to_csv(
    "./csv/parsed-ISCAS-Miter-" + exp_name + ".csv", sep="\t", index=False
)
df[~df["Circuit"].str.contains(r"c\d+")].to_csv(
    "./csv/parsed-EPFL-Miter-" + exp_name + ".csv", sep="\t", index=False
)
