clear;
RClength=5;
AlphaCr=0.85;
AlphaRc0=0.15;
AlphaRcArray=linspace(1,RClength,RClength);
TauLoverdt=1/AlphaRc0 -1;
AlphaRcArray=1 ./ ( TauLoverdt./AlphaRcArray + 1 );
EnergyStat=zeros(1,3);



foldercount=5
for eventcount=1:1:1000
    filename = "X:\CPU_Collected\ncku_dd\20250610(" + foldercount + ")\20250610(" + foldercount + sprintf(')_%04d.csv', eventcount);
    data=csvread(filename,3);
    timeus=data(:,1);
    dt=timeus(2)-timeus(1);
    datalength=length(data);
    dataAnalyze=zeros(datalength, RClength+2); %1raw+1CR+5RC=7
    dataAnalyze(:,1)=data(:,2);
    %plot(timeus,dataAnalyze(:,1));
    TauH=AlphaCr / (1-AlphaCr)*dt;
    TauL=( 1/AlphaRc0 -1 )*dt;

    for j=2:1:datalength
        dataAnalyze(j,2)=AlphaCr*dataAnalyze(j-1,2) + AlphaCr*( dataAnalyze(j,1) - dataAnalyze(j-1,1) );
        for m=3:1:RClength+2
            dataAnalyze(j,m)=( 1-AlphaRcArray(m-2) )*dataAnalyze(j-1,m) + AlphaRcArray(m-2)*dataAnalyze(j,m-1);
        end
    end
    Energytemp=max(dataAnalyze(:,RClength+2));
    EnergyStd=std(dataAnalyze(:,RClength+2));
    if Energytemp/EnergyStd > 10 
        EnergyStat=[EnergyStat; [Energytemp, foldercount, eventcount]] ;
        plot(timeus,dataAnalyze(:,RClength+2));
        hold on;
    end
end
axis([-0.5 1 -1 10]);
xlabel('Time (us)');
ylabel('Amplitude (a.u.)');
EnergyStat=EnergyStat(2:end,:);
title=["Energy(a.u.)", "folder", "eventNumber"];
filenameoutput="X:\CPU_Collected\ncku_dd\20250610(" + foldercount + ").xlsx";
saveas(gcf, "X:\CPU_Collected\ncku_dd\20250610(" + foldercount + ").png"); 
writematrix([title; EnergyStat], filenameoutput);
hold off;

