%%2022-03-24
% Output overlapping compounds from two metabolomics experiments

[f2019,f2019_Dir] = uigetfile('*.xlsx','Select "Manual_metabolomics_data.xlsx"');
[f2020,f2020_Dir] = uigetfile('*.xlsx','Select "Classifier_metabolomics_data.xlsx"');

f2019 = strcat(f2019_Dir,f2019);
f2020 = strcat(f2020_Dir,f2020);

outDir = getParentDir(f2019_Dir);
overlap = strcat(outDir,"supp_overlap.txt");

thresh = 5e-6; % error threshold, in ppm

d2019 = readtable(f2019);
d2020 = readtable(f2020);
hOverlap = fopen(overlap,'w');

mw2019 = d2019{:,'MolecularWeight'};
mw2020 = d2020{:,'MolecularWeight'};

fprintf(hOverlap,'MW_19\tMW_20\tName_19\tName_20\tFormula_19\tFormula_20\tS_NS_19\tS_NS_20\tS_C_19\tS_C_20\n');

massIns = '%.5f';
numIns = '%.2f';
tab = '\t';

for i=1:length(mw2019)
    mwdiff = mw2019(i)-mw2020;
    [val,idx] = min(abs(mwdiff));
    if val<=(thresh*mw2019(i))
        name_2020 = d2020{idx,'Name'};
        name_2020 = char(name_2020);
        form_2020 = d2020{idx,'Formula'};
        form_2020 = char(form_2020);
        area_2020 = d2020{idx,'GroupArea_S'};
        ratio_2020 = 1/d2020{idx,'Ratio__NS___S_'};
        adjp_2020 = d2020{idx,'Adj_P_value__NS___S_'};
        p_2020 = d2020{idx,'P_value__NS___S_'};
        cratio_2020 = d2020{idx,'Ratio__S___C_'};
        
        name_2019 = d2019{i,'Name'};
        name_2019 = char(name_2019);
        form_2019 = d2019{i,'Formula'};
        form_2019 = char(form_2019);
        area_2019 = d2019{i,'GroupArea_CNEEplus'};
        ratio_2019 = d2019{i,'Ratio__CNEEplus___CNEEminus_'};
        adjp_2019 = d2019{i,'Adj_P_value__CNEEplus___CNEEminus_'};   
        p_2019 = d2019{i,'E__E_PVal'};
        mz_2019 = d2019{i,'MzCloud'};
        mz_2019 = char(mz_2019);
        cratio_2019 = 1/d2019{i,'Ratio__CNEEplus___CNEC_'};
            
        outLine = [massIns,tab,massIns,tab,name_2019,tab,name_2020,tab,form_2019,tab,form_2020,tab,numIns,tab,numIns,tab,numIns,tab,numIns,'\n'];
        fprintf(hOverlap,outLine,mw2019(i),mw2020(idx),ratio_2019,ratio_2020,cratio_2019,cratio_2020);
    end
end

fclose(hOverlap);