% load('\\atlas.shore.mbari.org\ProjectLibrary\901805_Coastal_Biogeochemical_Sensing\Spray_Data\24A03401\QC\24A03401_QC.mat');
load('\\atlas.shore.mbari.org\ProjectLibrary\901805_Coastal_Biogeochemical_Sensing\Spray_Data\24A03401\sat_files\24A03401_sat.mat'); % using sat data because I get pres on up and downcast
%% Time at a depth, z, for profile, p, = s.sdn_(1,p) + s.secs(zi,p), where zi is the index for depth z, and s.sdn_(1,p) is the time of dive start. 
% s.sdn_(2,p) is time of dive end
dt_divestart = datetime(datevec(s.sdn_(1,:)),"TimeZone","UTC");
accusonde_depth_on = 250; % accusonde turns on/off at 250 db
n = length(eng.divenum_ec);
Descent_250db_time = NaT(n,1,TimeZone="UTC");
Ascent_250db_time = NaT(n,1,TimeZone="UTC");
Descentdepth = NaN(n,1);
Ascentdepth = NaN(n,1);
zmax250 = eng.zmax > accusonde_depth_on;

for p = 1:n
    descentidx = eng.pitch(:,p) < 0;
    [z_descent,zi_descent] = min(abs(eng.pres(descentidx,p) - accusonde_depth_on),[],'omitmissing');
    [z_ascent,zi_ascent] = min(abs(eng.pres(~descentidx,p) - accusonde_depth_on),[],'omitmissing');

    descsecs = eng.secs(descentidx,p);
    Descent_250db_time(p) = dt_divestart(p) + seconds(descsecs(zi_descent));
    ascsecs = eng.secs(~descentidx,p);
    Ascent_250db_time(p) = dt_divestart(p) + seconds(ascsecs(zi_ascent));

    Desdepth = eng.pres(descentidx,p);
    Descentdepth(p) = Desdepth(zi_descent);

    Ascdepth = eng.pres(~descentidx,p);
    Ascentdepth(p) = Ascdepth(zi_ascent);
end


tbl = table(eng.divenum_ec,s.lat',s.lon',Descentdepth,Descent_250db_time,Ascentdepth,Ascent_250db_time,eng.zmax,'VariableNames',{'Dive_Number','Latitude','Longitude','Descent_Depth','Descent_250db_time','Ascent_Depth','Ascent_250db_time','Max_Dive_Depth'});
writetable(tbl,'AccusondeValidation.csv');


%%
plot(eng.secs,eng.pres)