% CMEMS Chl-a data - GlobColour
% Sources:
% https://resources.marine.copernicus.eu/product-detail/OCEANCOLOUR_GLO_CHL_L4_REP_OBSERVATIONS_009_082/DATA-ACCESS
% https://resources.marine.copernicus.eu/product-detail/OCEANCOLOUR_GLO_OPTICS_L4_REP_OBSERVATIONS_009_081/DATA-ACCESS
%
% Original code Jessie Turner January 2022
% Updated to plot a time series of L4 chl from daily interpolated product
% Updated March 2022 to get a long-term mean over time of daily chl (map)
%
% October 2023 (v3)
% Uses corrected Chl-a, in dataset "daily_chl_CMEMS_WAP_v3.mat"

% % Get just one .nc file to load in lat, lon.
folder = '/Users/jsturner/satellite_data/WAP_CMEMS/';
file2 = [folder 'dataset-oc-glo-bio-multi-l4-chl_interpolated_4km_daily-rep_1641578578410.nc'];

disp(' ');
disp('Loading daily chl data from large .mat file...');
load('daily_chl_CMEMS_WAP_v3.mat'); % This is a LARGE file!
disp('Loaded');

% get lat lon
chl0 = ncread(file2,'CHL');
lon0 = ncread(file2,'lon');
lat0 = ncread(file2,'lat');
lon_chl = repmat(lon0,1,size(chl0,2));
lat_chl = repmat(lat0,1,size(chl0,1))';
clearvars *0;

% Calculate how many points are available spatially through time series
% Trim to only analyze pixels that have >30% of the record.
time_len = size(chl,3); % number of timesteps (>8000 days)
perc_cov = sum(isfinite(chl),3)./time_len;chl_data = reshape(chl,[(size(perc_cov,1).*size(perc_cov,2)),time_len]);
chl_data((perc_cov <= 0.3),:) = nan;
perc_cov_data = reshape(perc_cov,(size(perc_cov,1).*size(perc_cov,2)),1);
perc_cov_data(perc_cov <= 0.3) = nan;
chl_trimmed = reshape(chl_data,[size(perc_cov,1),size(perc_cov,2),time_len]);
perc_cov_trimmed = reshape(perc_cov_data,[size(perc_cov,1),size(perc_cov,2)]);

% Get long-term mean
chl_mean = nanmean(chl_trimmed,3);

%%%% Save data
save('Mean_Chl_20231026.mat','chl_mean','lon_chl','lat_chl');

