%% Methods for adjusting THOON WireWalker pH
%
% Wrapper function takes in data filename (file), k2, pressure coefficients (Pcoefs), and savefile (0 or 1).
% readncTHOON: converts the .nc file provided by Jacob Partida into a .mat file with appropriate variable names and adds some necessary variables for canyonB.
% THOONK0Calc: recalculates k0 using estimated insitu pH from the canyonB algorithm. Since the file is quite large, only running CanB on data between 70 to 74 m.
% THOONpH_adj: recalculates pH using the new k0 (k0_adj) that is the mean value from the full timeseries at the specified depths. We use the deepest water available because pH is more stable at depth and the canyonB algorithm will likely be more accurate.
%

file = '\\atlas.shore.mbari.org\ProjectLibrary\901805_Coastal_Biogeochemical_Sensing\WireWalker\THOON\Deployment_data\2024_06\THWW01-d04_20240602-20240712_t_profiles.nc';
k2 = -0.000966638000000000;
Pcoefs = -4.11000000000000e-06;
warmup = 60;
mindepth = 70;
maxdepth = 74;
savefile = 1;

%

[ww] = Wrapper_pH_adj_fulltimeseries(file,k2,Pcoefs,warmup,mindepth,maxdepth, savefile);

%

disp(['k0_adj = ', num2str(ww.k0_adj)])
disp(['k0_adj_std = ', num2str(ww.k0_std)])
disp(['mean pH free before adjusting k0 = ', num2str(mean(ww.pH_free,'all','omitnan')), ', Max: ', num2str(max(ww.pH_free,[],'all')), ', Min: ', num2str(min(ww.pH_free,[],'all'))])
disp(['mean pH free after adjusting k0 = ', num2str(mean(ww.pH_free_adj,'all','omitnan')), ', Max: ', num2str(max(ww.pH_free_adj,[],'all')), ', Min: ', num2str(min(ww.pH_free_adj,[],'all'))])
disp(['k2 = ', num2str(k2)])
disp(['Pcoefs = ', num2str(Pcoefs)])

%
%% Plotting Results

figure(1)
clf
pcolor(ww.Datenum,ww.Depth,ww.pH_free)
colormap hot(10)
cb = colorbar;
cb.Label.String = {['pH free'],['k0 = -1.4214']};
% cb.Limits = [7.5 9];
% cb.Ticks = 7.5:.25:9;
shading("flat")
datetick
title('THOON WW pH free, Original')
subtitle([datestr(ww.Datetime(1),'dd-mmm-yyyy'), ' to ', datestr(ww.Datetime(end),'dd-mmm-yyyy')])

%

figure(2)
clf
pcolor(ww.Datenum,ww.Depth,ww.pH_free_adj)
colormap hot(10)
cb = colorbar;
cb.Label.String = {['pH free'],['k0 = ', num2str(ww.k0_adj)]};
% cb.Limits = [7.5 9];
% cb.Ticks = 7.5:.25:9;
shading("flat")
datetick
title('Thoon WW pH free, adjusted')
subtitle([datestr(ww.Datetime(1),'dd-mmm-yyyy'), ' to ', datestr(ww.Datetime(end),'dd-mmm-yyyy')])

%
% Time series of pH at surface, 20, 40, and 65 m?
%

figure(3)
clf
tl = tiledlayout(4,1,"TileSpacing","compact");
ylabel(tl,'pH free')

nexttile
plot(ww.Datetime,ww.pH_free_adj(361,:))
title('2 m')

nexttile
plot(ww.Datetime,ww.pH_free_adj(271,:))
title('20 m')

nexttile
plot(ww.Datetime,ww.pH_free_adj(171,:))
title('40 m')

nexttile
plot(ww.Datetime,ww.pH_free_adj(46,:))
title('65 m')