%% trinidad_head_timeseries.m  –  Full time-series pH section for Trinidad Head

%% ── Inputs ───────────────────────────────────────────────────────────────
data_file  = "C:\Users\bwerb\Documents\ProposalFigures\data\25B68601sat.mat";
pH_field   = 'pHin';
pH_offset  = -0.16;
pH_clim    = [7.5  8.05];
bin_size   = 50;

%% ── Load and bin ─────────────────────────────────────────────────────────
d = load(data_file);
s = d.s;

sdn_g = s.sdn;
dep_g = s.depth(:, 1);
pH_g  = s.(pH_field) + pH_offset;

date_start = min(sdn_g);
date_end   = max(sdn_g);
out_file   = sprintf('trinidad_head_timeseries_%s_%s.png', ...
    datestr(date_start, 'yyyymmdd'), datestr(date_end, 'yyyymmdd'));

bin_edges = 0 : bin_size : max(dep_g);
bin_ctrs  = bin_edges(1:end-1) + bin_size/2;
n_bins    = numel(bin_ctrs);
pH_binned = NaN(n_bins, numel(sdn_g));
for b = 1:n_bins
    rows = dep_g >= bin_edges(b) & dep_g < bin_edges(b+1);
    pH_binned(b, :) = mean(pH_g(rows, :), 1, 'omitnan');
end

%% ── Figure ───────────────────────────────────────────────────────────────
fig = figure(1);  clf(fig);
set(fig, 'Units','inches', 'Position',[0.5 0.5 12 5]);
set(fig, 'DefaultAxesFontSize', 14);

ax = axes(fig);
contourf(ax, sdn_g, bin_ctrs(:), pH_binned, 50, 'LineStyle', 'none')
shading(ax, 'interp')
axis(ax, 'ij')
clim(ax, pH_clim)
xlim(ax, [date_start  date_end])
ylim(ax, [0  1000])
colormap(ax, turbo)
grid(ax, 'on')
title(ax, 'Trinidad Head, OR')
ylabel(ax, 'Depth (m)')

n_ticks = 6;
contour_ticks      = linspace(date_start, date_end, n_ticks);
contour_ticklabels = cellstr(datestr(contour_ticks, 'mmm dd yyyy'));
xticks(ax, contour_ticks)
xticklabels(ax, contour_ticklabels)

pos = ax.Position;
cb  = colorbar(ax, 'eastoutside');
cb.Label.String = 'pH_{in situ} [total]';
cb.FontSize = 10;
ax.Position = pos;

%% ── Export ───────────────────────────────────────────────────────────────
set(fig, 'PaperUnits','inches', 'PaperSize',[12 5], ...
         'PaperPositionMode','manual', 'PaperPosition',[0 0 12 5]);
print(fig, '-dpng', '-r300', out_file)
fprintf('Saved %s\n', out_file)
