function pH_cal_report(k2data, k0data, app_info, save_dir)
% This function relies on data generated from calc_phcal_k2.m &
% calc_phcal_k0.m. It is intended to be used by the pH cal GUI to send out
% some final calibratioon text files based on choices mad in the GUI
%
% If no k2data the function exits, if no k0 data, a truncated report is
% generated

% ************************************************************************
% ************************************************************************
% % TESTING
% 
% % GENERATE PRESSURE CHAMBER TEST DATA
% % dirs.data = 'C:\Users\jplant\Documents\MATLAB\Apps\pH_Calibration\test data\';
% dirs.data = 'C:\temp\';
% fn         = 'DF#308&VL#308_chB-210209.csv';
% % fn         = 'DF290&VL290chC_200612.csv'; % test k2 file
% PTfile    = [dirs.data,fn];
% d = parse_PTchamber_file(PTfile);
% data = d.data;
% hdr  = d.hdr;
% info = d.info;
% % 
% % 
% fit_order = 5;
% save_dir = 'C:\Users\jplant\Documents\MATLAB\Apps\pH_Calibration\test data\';
% % % 
% % % % SUBSET TO CAL ZONE
% I.LSDN = find(strcmp(hdr,'Labview Date/Time') == 1);
% % tSDN   = data(:,I.LSDN) >= datenum(2020,6,14,1,31,0) & ...
% %          data(:,I.LSDN) <= datenum(2020,6,18,7,33,0);
% 
% tSDN = data(:,I.LSDN) >= datenum(2021,2,11,3,18,0) & ... % DF308
%     data(:,I.LSDN) <= datenum(2021,2,15,9,46,0);
% tPdir = true(size(data,1),1); % predim all
% k2data = calc_phcal_k2(data, hdr, info, tSDN, tPdir, fit_order);
% k0data =[];
% clearvars -except k2data save_dir dirs k0data
% % 
% % *********************************************************
% % GENERATE KO TEST DATA
% fn          = 'MSC0904_DURA.dat';
% MSC         = '0904';
% time_offset = 7; % DST, GMT-7
% 
% %
% k0file      = [dirs.data,fn];
% d           = parse_k0_SW_file(k0file); % PUMP ON DATA
% k0hdr       = d.hdr;
% k0data.pON  = d.data;
% k0info.MSC = app.info.MSC;
% k0info.SourceDir = dirs.data;
% k0info.pONfile = fn; 
% 
% d           = parse_k0_SW_file(regexprep(k0file,'DURA','DURA_2')); %PUMP OFF
% k0data.pOFF = d.data;
% k0info.pOFFfile = regexprep(fn,'DURA','DURA_2');
% 
% % GET INDICES
% I.SDN  = find(strcmp(k0hdr,'DATE TIME') == 1);
% % I.SCT  = find(strcmp(k0hdr,'SAMPLE COUNTER') == 1);
% % I.T    = find(strcmp(k0hdr,'CTD TEMP') == 1);
% % I.S    = find(strcmp(k0hdr,'CTD SALINITY') == 1);
% % I.VRS  = find(strcmp(k0hdr,'VRS VOLTS') == 1);
% 
% % merge & sort data files
% data   = [k0data.pON; k0data.pOFF];
% tON    = [ones(size(k0data.pON(:,1))); ones(size(k0data.pOFF(:,1)))*0];
% [~,ia] = sort(data(:, I.SDN));
% data   = data(ia,:);
% tON    = tON(ia);
% tSDN   = data(:,1) >= datenum(2020,8,10,17,42,00) & ...
%     data(:,1) <= datenum(2020,8,12,18,34,00);
% %tSDN   = true(size(data(:,1)));
% clear k0data d
% 
% 
% % get discrete pH samples
% fp            = '\\atlas\chem\DuraFET\K0 for DSD Stems\SpecpH_data\';
% color_pH      = merge_discrete_pH(fp, 'K0',0);
% 
% % Supply k2 slope
% k2 = k2data.avg_k2; 
% fit_order = 1;
% 
% k0data = calc_phcal_k0(data, k0hdr, k0info,tSDN ,tON, k2, color_pH, time_offset, fit_order);
% 
% % % clearvars -except k2data k0data MSC k0hdr save_dir

% ************************************************************************
% ************************************************************************


% *************************************************************************
% *************************************************************************
% BUILD CALIBRATION TEXT FILE

cal_fn = [k2data.DF_TYPE,k2data.DF_SN,'_Calibration_',datestr(now,'yyyymmdd'),'.TXT'];
fid    = fopen([save_dir,cal_fn],'w');

iSN = find(strcmp(k2data.Results(:,1),'Durafet SN:') == 1);
iSS = find(strcmp(k2data.Results(:,1),'Data subset:') == 1);

fprintf(fid, 'PH CALIBRATION FILE GENERATED ON: %s\r\n', ...
    datestr(now,'mm/dd/yyyy HH:MM'));
fprintf(fid, '%s %s\r\n',k2data.DF_TYPE, k2data.DF_SN);
fprintf(fid, 'MSC %s\r\n', app_info.MSC);

if ~isempty(app_info.APEX_ID)
    APEX_ID = app_info.APEX_ID;
else
    APEX_ID = 'XXXXX';
end
    
fprintf(fid, 'APEX ID %s\r\n\r\n', APEX_ID);

% PRINT CONFIG FILE COPY BLOCK
fprintf(fid, '** START CONFIG FILE COPY BLOCK **\r\n');
% reverse order for config file & drop poly fit k0
Pcoefs = flip(k2data.Pcoefs(1:end-1));
if strcmp(k2data.stem_mfg, 'SBE')
    Pcoefs = flip(k2data.Pcoefs); % intercept alrready removed in pdf parsing function
end

% GET K0 HCL
if strcmp(k2data.stem_mfg, 'MBARI') || strcmp(app_info.FileType, 'SBE raw')
    k0_HCL = k2data.BinK2_data(1,4); % surface most k2 intercept- what is best HCL k0?
elseif strcmp(k2data.stem_mfg, 'SBE')
    k0_HCL = k2data.k0_HCL;
end

fprintf(fid,'Durafet SN = %s, APEX# %s\r\n',k2data.DF_SN,APEX_ID);
fprintf(fid,'%0.0f, number of calibration coefficients\r\n',numel(Pcoefs)+2);
if isempty(k0data)
    fprintf(fid,'NO K0 DATA WAS PEOCESSED YET OR LOADED INTO GUI!!!!\r\n');
elseif strcmp(k2data.stem_mfg, 'MBARI') || strcmp(app_info.FileType, 'SBE raw')
    fmt_str = '%0.5f, =k0 Pon; %0.5f =k0 Poff; %0.5f =k0 HCl\r\n';
    fprintf(fid, fmt_str, k0data.avg_k0_pON(1), k0data.avg_k0_pOFF(1), k0_HCL);
elseif strcmp(k2data.stem_mfg, 'SBE')
    fmt_str = '%0.5f, =k0 Pon; %0.5f =k0 Poff; %0.5f =k0 HCl\r\n';
    fprintf(fid, fmt_str, k0data.avg_k0_pON(1), k0data.avg_k0_pOFF(1), k0_HCL);
%     fmt_str = '%0.5f, =k0 Pon; %0.5f =k0 Poff\r\n';
%     fprintf(fid, fmt_str, k0data.avg_k0_pON(1), k0data.avg_k0_pOFF(1));
end


if k2data.k2_Pcoefs(1) == 0 && size(k2data.k2_Pcoefs,2) == 2
    fprintf(fid, '%0.5e, =k2*T\r\n', k2data.k2_Pcoefs(2));
else
    fmt_str = [repmat('%0.5e,', 1, size(k2data.k2_Pcoefs,2)),' =k2(fP)*T\r\n'];
    fprintf(fid, fmt_str, k2data.k2_Pcoefs);
end


for i = 1:numel(Pcoefs)
%     if i == 1
%         fprintf(fid, '%0.5e, =k%0.0f*P\r\n',Pcoefs(i),i+2);
%     else
%         fprintf(fid, '%0.5e, =k%0.0f*P^%0.0f\r\n',Pcoefs(i),i+2,i+1);
%     end

    fprintf(fid, '%0.5e, =k%0.0f*P^%0.0f\r\n',Pcoefs(i),i+2,i);
end
fprintf(fid, '** END CONFIG FILE COPY BLOCK **\r\n\r\n');

% ***************************************
% PRINT pHlog.xlsx COPY BLOCK
Pcoefs = k2data.Pcoefs;

fprintf(fid, '** START pHlog.xlsx COPY BLOCK **\r\n');
fprintf(fid,['Ptchamber\tCh\tPT runs\tVrsDrift\t', ...
    'k2 f(P) C6\tk2 f(P) C5\tk2 f(P) C4\tk2 f(P) C3\tk2 f(P) C2\t', ...
    'k2 f(P) C1\tk2 f(P) C0\tk0(HCl)\tR^2\t']);
%fprintf(fid,'k6\tk5\tk4\tk3\tk2\tk1\tk0\tR^2\t');
fprintf(fid,'f(P) k8\tf(P) k7\tf(P) k6\tf(P) k5\tf(P) k4\tf(P) k3\tf(P) k2\tf(P) k1\tf(P) k0\tR^2\t');
fprintf(fid,'pH Design\tDie\tDF#\tk0CalDates\tk0Soln\t');
fprintf(fid,'k0_pOFF\tStdk0_pOFF\tk0_pON\tStdk0_pON\r\n');	

% ************************************************************************
% fill k2 info
k2Pcoef_cols = 7;
num_k2_coefs = size(k2data.k2_Pcoefs,2);
if strcmp(k2data.stem_mfg, 'MBARI') || strcmp(app_info.FileType, 'SBE raw')
    k2cal_dates = datevec(k2data.cal_win);
    cal_datestr = sprintf('%02.0f/%02.0f-%02.0f/%02.0f/%0.0f', ...
        k2cal_dates(1,2:3),k2cal_dates(2,[2:3,1]));
    k0_HCL = k2data.BinK2_data(1,4); % surface most k2 intercept- what is best HCL k0?
    
    if ~isnan(k2data.Vrs_Drift(1))
    fprintf(fid,'%s\t%s\t\t%0.3f\t', cal_datestr, k2data.DF_CH, ...
        k2data.Vrs_Drift(1)*1000);
    else
        fprintf(fid,'%s\t%s\t\t\t', cal_datestr, k2data.DF_CH); 
    end
    
    % k2 is a constant just fill last col with avergag K2
    if k2data.k2_Pcoefs(1) == 0 && num_k2_coefs == 2 % k2 is a constant
        fprintf(fid, [repmat('\t',1,k2Pcoef_cols-1),'%0.5e\t'], k2data.k2_Pcoefs(2));
    % not const but not not 6th order    
    elseif num_k2_coefs < k2Pcoef_cols 
        fmt = [repmat('\t',1,k2Pcoef_cols-num_k2_coefs), ... % fill empty
            repmat('%0.5e\t',1,num_k2_coefs)];
        fprintf(fid, fmt, k2data.k2_Pcoefs);
    else % 6th order
        fprintf(fid, repmat('%0.5e\t',1,5), k2data.k2_Pcoefs); 
    end  
    fprintf(fid,'%0.5f\t%0.4f\t',  k0_HCL, median(k2data.BinK2_data(1,6),'omitnan'));

elseif strcmp(k2data.stem_mfg, 'SBE')
    k0_HCL = k2data.k0_HCL;
    fprintf(fid,'\t\t\t\t%0.5e\t%0.5f\t\t',k2data.avg_k2, k0_HCL);
end

% % fill k2 info
% if strcmp(k2data.stem_mfg, 'MBARI')
%     k0_HCL = k2data.BinK2_data(1,4); % surface most k2 intercept- what is best HCL k0?
%     fprintf(fid,'%0.3f\t%0.5e\t%0.5f\t%0.4f\t', k2data.Vrs_Drift(1)*1000, ...
%         k2data.avg_k2, k0_HCL, median(k2data.BinK2_data(1,6),'omitnan'));
% elseif strcmp(k2data.stem_mfg, 'SBE')
%     k0_HCL = k2data.k0_HCL;
%     fprintf(fid,'\t%0.5e\t%0.5f\t\t',k2data.avg_k2, k0_HCL);
% end

Pcoef_cols = 9;
num_fp_coefs = size(Pcoefs,2);
if (strcmp(k2data.stem_mfg, 'MBARI') ||strcmp(app_info.FileType, 'SBE raw')) ...
        && num_fp_coefs < Pcoef_cols 
        fmt = [repmat('\t',1,Pcoef_cols-num_fp_coefs), ... % fill empty
            repmat('%0.5e\t',1,num_fp_coefs),'%0.4f\t'];
        fprintf(fid, fmt, Pcoefs, k2data.fP_RR);
elseif strcmp(k2data.stem_mfg, 'MBARI') ||strcmp(app_info.FileType, 'SBE raw')
    fmt = [repmat('%0.5e\t',1,num_fp_coefs),'%0.4f\t'];
    fprintf(fid, fmt, Pcoefs,k2data.fP_RR);
elseif strcmp(k2data.stem_mfg, 'SBE')
    fmt = [repmat('\t',1,Pcoef_cols-num_fp_coefs), ... % fill empty
        repmat('%0.5e\t',1,num_fp_coefs),'\t\t'];
    fprintf(fid, fmt_str, Pcoefs);
end

fprintf(fid,'%s\t\t%s\t', k2data.DF_TYPE,k2data.DF_SN); % sensor type & SN
    


% % fill Pcoef info
% if numel(Pcoefs)<Pcoef_cols && strcmp(k2data.stem_mfg, 'MBARI')
%     
%     fill_ct = Pcoef_cols - numel(Pcoefs);
%     fmt_str = '';
%     for i = 1:Pcoef_cols+1
%         if i == Pcoef_cols+1
%             fmt_str = [fmt_str,'%0.4f\t']; % fP RR
%         elseif i == Pcoef_cols
%             fmt_str = [fmt_str,'%0.5f\t']; % K2
%         elseif i <= fill_ct
%             fmt_str = [fmt_str,'\t'];
%         else
%             fmt_str = [fmt_str,'%0.5e\t'];
%         end
%     end
%     fprintf(fid, fmt_str, Pcoefs, k2data.fP_RR);
%     
% elseif strcmp(k2data.stem_mfg, 'MBARI')
%     fmt_str = [repmat('%0.5e\t',1,6),'%0.5f\t%0.4f\t'];
%     fprintf(fid, fmt_str, Pcoefs, k2data.fP_RR);
%     
% % SBE intercept alrready removed in parsing function & no fit params
% elseif strcmp(k2data.stem_mfg, 'SBE')
%     num_coef = numel(Pcoefs);
%     fmt_str = [repmat('\t',1,6-num_coef), repmat('%0.5e\t',1,num_coef), ...
%         '\t\t'];
%     fprintf(fid, fmt_str, Pcoefs);
% end

if ~isempty(k0data)
% fill meta k0 info
cal_dates = datevec(k0data.k0_cal_win);
cal_datestr = sprintf('%02.0f/%02.0f-%02.0f/%02.0f/%0.0f', ...
    cal_dates(1,2:3),cal_dates(2,[2:3,1]));
fprintf(fid,'%s\t\t', cal_datestr);
% fill  k0 values   
fprintf(fid,'%0.5f\t%0.5e\t%0.5f\t%0.5e\r\n', k0data.avg_k0_pOFF, ...
    k0data.avg_k0_pON);
else
    fprintf(fid,'\t\t\t\t\t');
    fprintf(fid,'\t\t\t\r\n');
end
    
fprintf(fid, '** END pHlog.xlsx COPY BLOCK **\r\n\r\n');
% ***************************************


if strcmp(k2data.stem_mfg, 'MBARI') ||strcmp(app_info.FileType, 'SBE raw')
    % PRINT SOME BASIC INFO: SN's time windows, file names, etc
    fprintf(fid,'\r\n** SUMMARY K2 DATA: **\r\n');
    D = k2data.Results(iSN:iSS,:)';
    fprintf(fid,'%s\t%s\t%s\r\n',D{:});
    
    % PRINT K2 RELATED DATA (AVERAGE)
    iVD = find(strcmp(k2data.Results(:,1),'Vrs drift rate:') == 1);
    iSD = find(strcmp(k2data.Results(:,1),'Std dev Ib:') == 1);
    D = k2data.Results(iVD:iSD,:)';
    
    fprintf(fid,'%s\t%s\t%s\r\n',D{:});
    
    % PRINT PRESSURE BINNED K2 DATA
    fprintf(fid,'\r\n** PRESSURE BINNED K2 DATA: **\r\n');
    fprintf(fid,'%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n',k2data.BinK2_hdr{:});
    k2bin  = k2data.BinK2_data;
    rk2bin = size(k2bin,1);
    bin_fmt ='%0.1f\t%0.4e\t%0.4e\t%0.4f\t%0.4e\t%0.4f\t%0.0f\t%0.1f\t%0.1f\r\n';
    for i = 1:rk2bin
        fprintf(fid, bin_fmt, k2bin(i,:));
    end
end

% PRESSURE COEFFICENT DATA
pcoefs = flip(k2data.Pcoefs);
iFP = find(strncmp(k2data.Results(:,1),'f(P)',4) == 1);
D = k2data.Results(min(iFP):max(iFP),:)';
fprintf(fid,'\r\n** PH POLYNOMIAL PRESSURE COEFFICIENTS: **\r\n');
fprintf(fid,'%s\t%s\t%s\r\n',D{:});

% ************************************************************************
% ADD k0 calibration info
if isempty(k0data) 
    fprintf(fid,'\r\nNO KO DATA FILE LOADED INTO CALIBRATION GUI!!!:\r\n');
    fprintf(fid,'Has the k0 calibration be completed yet?:\r\n');
    fprintf(fid,'Is the MSC # correct? Check MSC / SN match up:\r\n');
    fclose(fid);
    return
end

iFD = find(strcmp(k0data.Results(:,1),'k0 Source directory :') == 1);
D = k0data.Results(1:iFD,:)';
fprintf(fid,'\r\n** KO CALIBRATION SUMMARY: **\r\n');
fprintf(fid,'%s\t%s\t%s\r\n',D{:});


% REARRANGE pON pOFF DATA
fprintf(fid,'\r\nParameter\tPump ON\tPump OFF\tUnits\r\n');
tON  = ~cellfun(@isempty, regexp(k0data.Results(:,1),'pump ON','once'));
tOFF = ~cellfun(@isempty, regexp(k0data.Results(:,1),'pump OFF','once'));
params = regexprep(k0data.Results(tON,1),' pump ON','');
D = [params, k0data.Results(tON, 2),k0data.Results(tOFF, 2), ...
    k0data.Results(tON, 3)]';
fprintf(fid,'%s\t%s\t%s\t%s\r\n',D{:});

fclose(fid);













