%%
load('\\atlas.shore.mbari.org\ProjectLibrary\901805_Coastal_Biogeochemical_Sensing\Spray_Data\25520301\25520301sat.mat');
%% Build table T
nRows = length(s.sdn);

T = table( ...
    strings(nRows,1), ...           % Cruise
    strings(nRows,1), ...           % Platform
    strings(nRows,1), ...           % Layer
    NaN(nRows,1), ...               % unixTimestamp as datetime (or use double if raw Unix time)
    NaN(nRows,1), ...               % lat
    NaN(nRows,1), ...               % lon
    NaN(nRows,1), ...               % pHin
    NaN(nRows,1), ...               % pH25atm
    NaN(nRows,1), ...               % rodamine
    NaN(nRows,1), ...               % MLD
    'VariableNames', { ...
        'Cruise', 'Platform','Layer', 'unixTimestamp', ...
        'lat', 'lon', 'pHin', 'pH25atm', ...
        'rhodamine', 'MLD' ...
    });

%% Calculate MLD parameters for upcast. Need to improve this function with Shawnee!!
[idx_zref, idx_MLD, ML_mask] = GetMLD(s.depth,s.pdens,'jones','upcast');
pHin = s.pHin;
pH25atm = s.pH25atm;
pH25atm(pH25atm == -999) = NaN;

masked_pHin = pHin;
masked_pHin(~ML_mask) = NaN;

masked_pH25atm = pH25atm;
masked_pH25atm(~ML_mask) = NaN;

masked_depth = s.depth;
masked_depth(~ML_mask) = NaN;
%%
T.Cruise = repmat(string(s.depID),nRows,1);
T.Platform = repmat("Glider",nRows,1);
T.unixTimestamp = floor(s.sdn_(2,:)' - datenum(1970, 1, 1) * 86400); % datenum2unix
T.lat = s.lat_(2,:)'; % end dive lat
T.lon = s.lon_(2,:)'; % end dive lon
T.Layer = repmat("MLD",nRows,1); % Add surface layer
T.pHin = mean(masked_pHin,'omitmissing')';
T.pH25atm = mean(masked_pH25atm,'omitmissing')';
T.MLD = mean(masked_depth,'omitmissing')';
% rodamine = rodamine;
%% read existing table and find unique rows to append
fname = '\\atlas.shore.mbari.org\ProjectLibrary\901805_Coastal_Biogeochemical_Sensing\Lochness\LochnessMapProduct.txt';
T_old = readtable(fname);
iappend = ~ismember(T(:,"unixTimestamp"), T_old(:,"unixTimestamp"),'rows');
%% Append new rows
writetable(T(iappend,:),fname,"WriteMode","append")