% CalcTGA - Funciton to plot and calculate PE/PP percentages by TGA
% Authored by David Kazmer, January 22, 2024

bUse10=false;

sFile{1}='TGA PP1 10.csv';
sFile{2}='TGA PP2 10.csv';
sFile{3}='TGA PP1-1 100.csv';
sFile{4}='TGA PP1-2 100.csv';
sFile{5}='TGA PP2-1 100.csv';
sFile{6}='TGA PP2-2 100.csv';

figure(1);clf;hold on

for i=1:2
    if bUse10
        T=readtable(sFile{i},'VariableNamingRule','preserve');
        d=table2array(T(2:end,:));
        T=d(1:end,1);
        M=d(1:end,2);M=100*M/M(1);
        dM=diff(M);
        dT=diff(T);
        iDT=find(dT>0);
        dMdT=dM(iDT)./dT(iDT);   
        % Use filtering since slow and single run
        [B,A]=butter(1,0.02);
        dMdT_f=filtfilt(B,A,dMdT);
    else
        % Read in replicates and use average
        for j=1:2
            iFile=2*i+j;
            T=readtable(sFile{iFile},'VariableNamingRule','preserve');
            d=table2array(T(2:end,:));
            Tj{j}=d(1:end,1);
            Mj{j}=d(1:end,2);
        end
        T=mean([Tj{1} Tj{2}]')';
        M=mean([Mj{1} Mj{2}]')';M=100*M/M(1);
        dM=diff(M);
        dT=diff(T);
        iDT=find(dT>0);
        dMdT=dM(iDT)./dT(iDT);   
        dMdT_f=dMdT;
    end

    [dMdT_min(i),i_min(i)] = min(dMdT_f(iDT));

    sLabel1=['PP' num2str(i) ', ' num2str(mean(M(end-4:end)),3) '% residual'];
    sLabel2=[sprintf('PP%d, T_P_e_a_k=%.1f\circC',i,T(i_min(i))) '\circC'];
    if i==1
        subplot(2,1,1);hold on
        plot(T(iDT),M(iDT),'k^','MarkerFaceColor','w','MarkerSize',6,'DisplayName',sLabel1);
        subplot(2,1,2);hold on;
        plot(T(iDT),dMdT_f,'k^','MarkerFaceColor','w','MarkerSize',6,'DisplayName',sLabel2);
    else
        subplot(2,1,1);
        plot(T(iDT),M(iDT),'r^','MarkerFaceColor','k','MarkerSize',6,'DisplayName',sLabel1);
        xlim([380 580]);
        subplot(2,1,2);
        plot(T(iDT),dMdT_f,'r^','MarkerFaceColor','k','MarkerSize',6,'DisplayName',sLabel2);
        xlim([380 580]);
    end
    i
    M(end)
end
subplot(2,1,1);
%xlabel('Temperature, \circC');
ylabel('Specimen Mass, %')
grid on;legend('location','southwest')
subplot(2,1,2);
%plot([458.8 458.8],[0 -2.999],'k--','DisplayName','T_P_P_1=458.8\circC')
%plot([465.7 465.7],[0 -2.847],'r-.','DisplayName','T_P_P_2=465.7\circC')

xlabel('Temperature, \circC');ylabel('Mass Rate, % per \circC')
grid on;legend('location','southwest')