% Calibrate the pH sensor by re-calculating k0
% 
% INPUT: compiled and averaged data from test tank data of discrete pH and
% pH sampled from the Spray Glider (.xslx file in deployment folder - may
% need to create if not already generated, follow steps under Gdrive/Spray
% Documents/Pre Deployment/pH calibration steps.docx
%
% Written by: Jacki Long June 13 2022

clear all; close all

% Move to directory to make sure you call the correct functions
cd('/Users/jlong/Documents/GitHub/Spray_Processing/Calibration_related/Functions/')

% Update Deployment ID
depID = '23C02902';

% 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

% % Load CTD data and in situ pH data
% T = readtable([basepath depID '_Spray_TT_O2_pH_Values.xlsx'], 'Range', 'A:F');
% T = T(1,:);
T = struct;
[T.spec_pH, T.spec_T, T.CTD_T, T.CTD_Sal, T.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, T.pH_tot, 1, 3, T.CTDsal, T.Temp_used, T.CTDtc, 0, 0, 0, 0, 1, 10, 1);
% Spec pH input for next step
spec_pH_insitu = trex(:,18);

%IMPORTANT for k0 cal_JKW


%% STEP 2:
%copied from cal_22602901.m
% if contains(depID,'29')
%     UseDefaultk2 = -1.0296E-03;% SG 29
% elseif contains(depID,'34')
%     UseDefaultk2 = -1.0626e-03; % SG 34
%     UseDefaultk2 = -9.6415E-04; % For DSD384
% end
% Use k2 from calibration .csv sheet
% UseDefaultk2 = cal.k2;

% Calculate k0 from
[k0, ~] = calc_k0_ext(T.VRSE, T.CTDtc, T.CTDsal, spec_pH_insitu, cal.k2);
% Add new k0 to the current deployment
D.k0(snidx) = k0;

%IMPORTANT for k0 cal_JKW


%% Diagnostic plot of k0 over time

% Find data for this spray glider
idx = find(D.SN == str2num(depID(5:6)));

set(gcf,'Units','Inches');
set(gcf,'position',[ 0.20    11    8   3])
% Compare to previous k0 values
plot(D.k0(idx),'ko','MarkerFaceColor',rgb('lightblue'))
set(gca, 'XTick', 1:numel(D.k0(idx)), 'XTickLabel', (D.DepID(idx)));

xticklabels(D.DepID(idx))
title(['Log of k0 values collected pre-deployment for spray ' depID(5:6)])
ylabel('k0')
xlabel('Deployment IDs')
set(findall(gcf,'-property','Fontname'),'Fontname','Avenir','fontsize',12)
% Save figure
exportgraphics(gca,[basepath depID '_k0_timeseries.png'],'Resolution',200)


%% STEP 3: if you want to look at adjusted pH
% Once you have the k0, you use calc_dfet_pHext_k0
% [pHext_tot, pHext_free] = calc_dfet_pHext_k0(Eext, tempC, salt, k0, UseDefaultk2);
[pHext_tot, pHext_free] = calc_dfet_pHext_k0(T.VRSE, T.CTDtc,  T.CTDsal, k0, cal.k2);

%IMPORTANT for k0 cal_JKW

%% Spray pH compared to in situ pH from spec
disp(['Spray pH = ' num2str(pHext_tot) ', in situ pH = ' num2str(spec_pH_insitu)])
disp(['k0 = ' num2str(k0)])



