% specdata = '20240411_SpraypH_K0_spec.txt';
% spraydata ='20240411_034_TT_k0_2.txt';

specdata = '20240404_034_K0_SpecpH.txt';
spraydata = '20240404_034_TT_k0.txt';


% Update Deployment ID
depID = '24403401';

% Set filepaths
if filesep == '\' % PC
    basepath = [filesep filesep 'atlas' filesep 'ProjectLibrary' filesep '901805_Coastal_Biogeochemical_Sensing' filesep 'Spray_Data' filesep ,depID, filesep 'calibration_data' filesep ];
    atlasroot = [filesep, filesep,'atlas', filesep, 'projectlibrary', filesep, '901805_Coastal_Biogeochemical_Sensing', filesep, 'Spray_Data', filesep];
else              % Mac
    basepath = [filesep 'Volumes' filesep '901805_Coastal_Biogeochemical_Sensing' filesep 'Spray_Data' filesep ,depID, filesep 'calibration_data' filesep ];
    atlasroot = [filesep, 'Volumes', filesep, '901805_Coastal_Biogeochemical_Sensing', filesep, 'Spray_Data', filesep];
end

[spec_pH, spec_T, CTD_T, CTD_Sal, vrse] = processSprayCalibration(specdata, spraydata);

% Load calibration data from .csv
fn = [atlasroot,filesep,'Calibrations',filesep,'spray_cal_info.csv'];
% Need to define some options first so that the DepID column is read as a
% string array
opts = detectImportOptions(fn);
% Specify 'TextType' as 'string' for the first column
opts = setvartype(opts, 'DepID', 'string');
D = readtable(fn,opts);
snidx = find(strcmp(depID,D.DepID));
cal = table2struct(D(snidx,:));

%% STEP 1:
% calculate insitu pH from discrete measurements
% Change 2270 to spec.TA if it was measured
trex = CO2SYS(2270, spec_pH, 1, 3, CTD_Sal, spec_T, CTD_T, 0, 0, 0, 0, 1, 10, 1);
% Spec pH input for next step
spec_pH_insitu = trex(:,18);

% Calculate k0 from
[k0, ~] = calc_k0_ext(vrse, CTD_T, CTD_Sal, spec_pH, cal.k2);
% Add new k0 to the current deployment
D.k0(snidx) = k0;

%%
[pHext_tot, pHext_free] = calc_dfet_pHext_k0(vrse, CTD_T,  CTD_Sal, k0, cal.k2);
%%
disp(['Spray pH = ' num2str(pHext_tot) ', in situ pH = ' num2str(spec_pH_insitu)])
disp(['k0 = ' num2str(k0)])