import os
import glob
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
import argparse

# Argument parser for input/output file names
parser = argparse.ArgumentParser(description='Plot sigma factor gene averages.')
parser.add_argument('--input', type=str, default='genes_averages.csv', help='Input CSV file with gene averages')
parser.add_argument('--output', type=str, default='sigmas-plot.png', help='Output PNG file for the plot')
args = parser.parse_args()

# Step 1: Load gene averages
ga = pd.read_csv(args.input, sep=';')[['Gene name', 'average']]

# Step 2: Collect per-sigma lists of matched averages
sigma_groups = {}  # Use a dictionary to store sigma groups for easier modification

# First, process sigma70
sigma70_genes = []
path = next((p for p in sorted(glob.glob('sigma/sigma*-genes.csv')) if 'sigma70' in p), None)

if path:
    sigma = os.path.basename(path).split('-')[0]
    gene_names = []
    with open(path, 'r') as f:
        for line in f:
            try:
                gene_name = line.strip().split(',')[0]
                if gene_name:
                    gene_names.append(gene_name)
            except Exception:
                continue
    
    df = pd.DataFrame({'gene_name': gene_names})
    avgs = (
        df['gene_name']
        .map(lambda g: ga.loc[ga['Gene name'] == g, 'average'].iloc[0]
             if g in set(ga['Gene name']) else None)
        .dropna()
        .tolist()
    )
    if avgs:
        sigma_groups[sigma] = avgs
        sigma70_genes = df['gene_name'].tolist()

# Now, process other sigma factors
for path in sorted(glob.glob('sigma/sigma*-genes.csv')):
    if 'sigma70' in path:
        continue  # Skip sigma70 since it's already processed
    
    sigma = os.path.basename(path).split('-')[0]
    gene_names = []
    with open(path, 'r') as f:
        for line in f:
            try:
                gene_name = line.strip().split(',')[0]
                if gene_name and gene_name not in sigma70_genes:  # Skip if in sigma70
                    gene_names.append(gene_name)
            except Exception:
                continue
    
    df = pd.DataFrame({'gene_name': gene_names})
    avgs = (
        df['gene_name']
        .map(lambda g: ga.loc[ga['Gene name'] == g, 'average'].iloc[0]
             if g in set(ga['Gene name']) else None)
        .dropna()
        .tolist()
    )
    if avgs:
        sigma_groups[sigma] = avgs

# Convert sigma_groups dictionary to list of tuples for plotting
sigma_groups_list = [(sigma, avgs) for sigma, avgs in sigma_groups.items()]

# Step 3: Prepare bar positions, heights, and colors
positions = []
heights = []
colors = []

cur_pos = 0
group_gap = 1
bar_width = 0.8

cmap = plt.get_cmap('tab10')

for idx, (sigma, avgs) in enumerate(sigma_groups_list):
    col = cmap(idx % 10)
    for a in avgs:
        positions.append(cur_pos)
        heights.append(a)
        colors.append(col)
        cur_pos += 1
    cur_pos += group_gap

# Step 4: Plot
plt.figure(figsize=(10, 6))
plt.bar(positions, heights, width=bar_width, color=colors)

plt.xticks([], [])
plt.xlabel('')
plt.ylabel('Average')

legend_handles = [
    Patch(color=cmap(i % 10), label=sigma_groups_list[i][0])
    for i in range(len(sigma_groups_list))
]
plt.legend(handles=legend_handles, title='Sigma Factor')
plt.ylim(0, 1000)
plt.tight_layout()
plt.savefig(args.output, dpi=300)  # Save as 1080p PNG (1920x1080 at 300 dpi for ~6.4x3.6 in)

Modify the code so instead of plotting it creates a new csv file, called "genes-sigmas.csv". There, take the input file and add a new column called sigmas. In that column list sigmas, if there are multiple sigmas sepate them with comma. Keep separation of columns in file with ;