import os
import csv

input_folder = "results_UAI_old"
output_folder = "results_UAI"
os.makedirs(output_folder, exist_ok=True)

def parse_edges_from_line(line):
    try:
        parts = line.strip().split(',')
        for part in parts:
            if 'edges' in part:
                return int(part.strip().split('=')[1])
    except Exception:
        return None
    return None

def process_csv_file(input_path, output_path):
    with open(input_path, 'r') as f:
        lines = f.readlines()

    new_lines = []
    edges = None

    for i, line in enumerate(lines):
        if line.strip().startswith("samples"):
            edges = parse_edges_from_line(line)
            new_lines.append(line)

        elif edges is not None and line.startswith("Acc"):
            values = line.strip().split(',')
            label = values[0]
            metrics = [float(v.strip()) for v in values[1:]]

            shd_vals = metrics[0]
            n_shd_vals = [shd / edges if edges != 0 else 0 for shd in [shd_vals]]
            new_values = [label] + [f"{v:.10f}" for v in n_shd_vals] + [f"{v:.3f}" for v in metrics]
            new_lines.append(",".join(new_values) + "\n") 

        elif edges is not None and line.startswith("Std"):
            values = line.strip().split(',')
            label = values[0]
            metrics = [float(v.strip()) for v in values[1:]]

            std_shd_vals = metrics[0]
            std_n_shd_vals = [std / (edges ** 2) if edges != 0 else 0 for std in [std_shd_vals]]
            new_std_values = [label] + [f"{v:.10f}" for v in std_n_shd_vals] + [f"{v:.3f}" for v in metrics]
            new_lines.append(",".join(new_std_values) + "\n")

        else:
            new_lines.append(line)

    with open(output_path, 'w') as f:
        f.writelines(new_lines)

# Process all CSV files
for filename in os.listdir(input_folder):
    if filename.endswith(".csv"):
        input_path = os.path.join(input_folder, filename)
        output_path = os.path.join(output_folder, filename)
        process_csv_file(input_path, output_path)

print("Processing complete. Normalized files saved to:", output_folder)
