import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Clear equivalent
plt.close('all')

# Parameters
RClength = 5
AlphaCr = 0.85
AlphaRc0 = 0.15
AlphaRcArray = np.linspace(1, RClength, RClength)
TauLoverdt = 1 / AlphaRc0 - 1
AlphaRcArray = 1 / (TauLoverdt / AlphaRcArray + 1)
EnergyStat = [[0, 0, 0]]  # Initialize with a dummy first row like MATLAB zeros(1,3)

foldercount = 12
for eventcount in range(1, 1000+1):
    filename = f"X:/CPU_Collected/ncku_dd/20250610({foldercount})/20250610({foldercount})_{eventcount:04d}.csv"
    data = np.loadtxt(filename, delimiter=",", skiprows=3)
    
    timeus = data[:, 0]
    dt = timeus[1] - timeus[0]
    datalength = len(data)
    
    dataAnalyze = np.zeros((datalength, RClength + 2))  # 1 raw + 1 CR + 5 RC
    dataAnalyze[:, 0] = data[:, 1]  # raw signal

    TauH = AlphaCr / (1 - AlphaCr) * dt
    TauL = (1 / AlphaRc0 - 1) * dt

    for j in range(1, datalength):
        dataAnalyze[j, 1] = AlphaCr * dataAnalyze[j - 1, 1] + AlphaCr * (dataAnalyze[j, 0] - dataAnalyze[j - 1, 0])
        for m in range(2, RClength + 2):
            dataAnalyze[j, m] = (1 - AlphaRcArray[m - 2]) * dataAnalyze[j - 1, m] + AlphaRcArray[m - 2] * dataAnalyze[j, m - 1]

    Energytemp = np.max(dataAnalyze[:, RClength + 1])
    EnergyStd = np.std(dataAnalyze[:, RClength + 1])
    
    if Energytemp / EnergyStd > 10:
        EnergyStat.append([Energytemp, foldercount, eventcount])
        plt.plot(timeus, dataAnalyze[:, RClength + 1])
        plt.hold = True  # Not required in matplotlib; use plt.plot repeatedly

# Axis and labels
plt.axis([-0.5, 1, -1, 10])
plt.xlabel('Time (us)')
plt.ylabel('Amplitude (a.u.)')

## Remove dummy row
EnergyStat = np.array(EnergyStat[1:])  # skip the first zero row

# Save plot
plt.savefig(f"X:/CPU_Collected/ncku_dd/20250610({foldercount})_python.png")

# Save results to Excel
title = ["Energy(a.u.)", "folder", "eventNumber"]
df = pd.DataFrame(EnergyStat, columns=title)
output_filename = f"X:/CPU_Collected/ncku_dd/20250610({foldercount})_python.xlsx"
df.to_excel(output_filename, index=False)
plt.show()
