vars = {'file location','DateTime UTC','sdn','latitude','longitude','SN','DepID','DepProfile','Params','Max Depth', 'DepSummary'};
varTypes = {'string','datetime','double','double','double','double','string','double','string','double','string'};
try % if previous glidex exists load it. If not, make one from scratch
    load("C:\Users\bwerb\Documents\GliderIndex\Index\GliderIndex_v1.mat")
    DepLog = ReadDeploymentLog();
    glidexDepID = unique(Glidex.DepID); 
    depLogDepID = DepLog.("Deployment ID");
    
    % Find strings in DepLog.("Deployment ID") that are not in Glidex.DepID
    missions = setdiff(depLogDepID, glidexDepID);
catch
    % Initialize an empty table with the specified variable types and names
    Glidex = table('Size', [0, length(vars)], 'VariableTypes', varTypes, 'VariableNames', vars);
    Glidex.("DateTime UTC").TimeZone = 'UTC';
    DepLog = ReadDeploymentLog();
    missions = DepLog.("Deployment ID");
end



for i = 1:height(missions)
    mission = missions(i);
    try
        filepath = ['\\atlas.shore.mbari.org\ProjectLibrary' ...
            '\901805_Coastal_Biogeochemical_Sensing\Spray_Data' ...
            '\',char(missions(i)),'\QC\',char(missions(i)),'_QC.mat'];
        load(filepath,'s')
    catch
        disp('Could not find _QC file. Grabbing _Calibrated file.')
        try
            filepath = ['\\atlas.shore.mbari.org\ProjectLibrary' ...
                '\901805_Coastal_Biogeochemical_Sensing\Spray_Data' ...
                '\',char(missions(i)),'\QC\',char(missions(i)),'_calibrated.mat'];
            load(filepath,'s')
        catch
            disp(['Could not find file for ', mission])
            continue
        end
    end
    n = length(s.sdn);
    file = repmat(string(filepath),n,1);
    
    sdn = s.sdn';
    lat = s.lat';
    lon = s.lon';

    SN = GetGliderSN(s, mission, DepLog);
    DateTime = datetime(datevec(sdn),'TimeZone','UTC');
    DepID = repmat(mission,n,1);
    % Profile = s.snum(1,:)'; %s.snum isn't always ordered properly
    Profile = (1:n)'; % need a prof number
    Params = GetGliderParams(s);
    MaxDepth = round(max(abs(s.depth)))';
    DepSummary = GetGliderDepSummary(s, mission, DepLog);
    % add M1 flag
    startIndex = height(Glidex) + 1;
    endIndex = startIndex + n - 1;
    Glidex(startIndex:endIndex, :) = table(file, DateTime, sdn, lat, lon, SN, DepID, Profile, Params, MaxDepth, DepSummary, 'VariableNames', vars);
end
Glidex = sortrows(Glidex,'DateTime UTC','descend');
BadDates = Glidex.("DateTime UTC") > datetime('now','TimeZone','UTC');
Glidex(BadDates,:) = []; % remove bad datetimes
save("C:\Users\bwerb\Documents\GliderIndex\Index\GliderIndex_v1","Glidex",'-mat');