% Extract_CUGN_to_mat
%
% Updated 1/7/2026
% 
% Yui Takeshita
% MBARI

clear
close all

% CUGN .nc files live here (manually downloaded -- see README_CUGN.md)
ddir = 'C:\Users\bwerb\Documents\CUGNROMS\CUGN\data';
% .mat files are written back into the same folder
outdir = ddir;

% Only the 5 lines actually used downstream (Derive_empirical_parameters.m,
% write_CUGN_to_gliderviz_txt.m). CUGN_line_93.nc is deliberately excluded:
% it's an older line that doesn't carry a 'doxy' variable at all, so it
% can't go through the oxygen-dependent ESPER/CANYONB estimation steps.
fnames = {'CUGN_along.nc';'CUGN_line_56.nc';'CUGN_line_66.nc';...
    'CUGN_line_80.nc';'CUGN_line_90.nc'};

for f = 1:length(fnames)

    % nc filename
    nc = [ddir,filesep,fnames{f}];
    
    fprintf('\nExtracting %s...',fnames{f});
    
    % extract temp, salinity, oxygen. size should be 50 x n_profiles
    s.tc = ncread(nc,'temperature')';
        fprintf('temperature,');
    s.psal = ncread(nc,'salinity')';
        fprintf('salinity,');
    s.doxy = ncread(nc,'doxy')';
        fprintf('doxy,');
    
    % depth is a 50x1 integer array; this is an objectively mapped dataset.
    s.depth = double(ncread(nc,'depth')) * ones(1,size(s.doxy,2));
        fprintf('depth,');
    % extract lat, lon, time
    s.lat = ncread(nc,'lat');
        s.lat = s.lat(:)'; % make them rows
    s.lon = ncread(nc,'lon');
        s.lon = s.lon(:)';
    s.time = ncread(nc,'time');
        s.sdn = unixtime2matSDN(s.time(:))';    
        fprintf('gps done!\n');

    fprintf('Calculating density...');
    % calculate pressure
    s.pres = sw_pres(s.depth, ones(size(s.depth,1),1)*s.lat);
    % calculate potential density
    s.abs_sal = gsw_SA_from_SP(s.psal, s.pres, ones(size(s.depth,1),1)*s.lon, ones(size(s.depth,1),1)*s.lat);
    s.cons_t  = gsw_CT_from_t(s.abs_sal, s.tc, s.pres);
    s.pdens = gsw_rho(s.abs_sal, s.cons_t, zeros(size(s.pres))) - 1000; % in kg/L
    fprintf('Done!\n');

    % ==== commented out from previous version ==========
    % % find data from 2019
    % iprof = s.sdn > datenum(2019,1,0) & s.sdn < datenum(2020,1,0);
    % 
    % % extract only 2019 data
    % s.tc(:,~iprof)      = [];
    % s.psal(:,~iprof)    = [];
    % s.doxy(:,~iprof)    = [];
    % s.depth(:,~iprof)   = [];
    % s.pres(:,~iprof)    = [];
    % s.abs_sal(:,~iprof) = [];
    % s.cons_t(:,~iprof)  = [];
    % s.pdens(:,~iprof)   = [];
    % 
    % 
    % s.lat(~iprof)  = [];
    % s.lon(~iprof)  = [];
    % s.time(~iprof) = [];
    % s.sdn(~iprof)  = [];
    % ==========================

    fprintf('saving %s...',[fnames{f}(1:end-3),'.mat']);
    save(fullfile(outdir,[fnames{f}(1:end-3),'.mat']), 's');
    fprintf('Done!\n');

    clearvars -except ddir outdir fnames

end
    
    
    














