clear all
close all
addpath(genpath('/Users/Mau/Documents/MATLABhelp_new'));

% PURPOSE: Estimate Sound Speed from overnight CPF deployment (Tue-Wed, 16-17/11/2021),
% just before CPF went missinng at the canyon mouth (Thu 11/18 AM). 
% by Magdalena Carranza

mission='ParagonTests/MICRORIDER/2021-11-16/'; % Overnight Mission, south Monterey Bay, 19 profiles.
% NOTE: *.mat files saved locally have CT, SA, RHO and w_ctd. Also renaming
% forlder to reflect only deployment DATE (no time).

maxp=100; % max depth for plotting

% data_root=['/Volumes/CPF/CPF003/Data/matfiles/'];
data_root=['/Users/Mau/Documents/MBARIprojects/CPF/CPF003/Data/matfiles/'];
% dir_plots=['/Volumes/CPF/CPF003/Data/data_processing/plots/'];
dir_plots=['/Users/Mau/Documents/MBARIprojects/CPF/CPFPROCESSING/plots/'];
dirs.mat=[data_root,mission];

WMO='CPF003';

%% Create directory to save plots (if it doesn't exist already)
% subdir=path_data(64:end); % if path_data='/Users/Mau/Documents/..'
% subdir=path_data(26:end);
% path_plots=['/Users/Mau/Documents/MBARIprojects/w_ctd/cpf/plots/',subdir];

path_plots=[dir_plots,mission];
if isfolder(path_plots)==0 & numel(dir(path_plots))<=2 % will create directory only if it is empty!
    mkdir(path_plots)
end

%%  List files for a given mission/folder

files=dir([dirs.mat,'*.mat']);
np=length(files); % number of profiles

%% Process each profile from a given mission/folder

SOUND=nan(100,np);
DEPTH=nan(100,np);

for p=1:np
    
filename=files(p).name;
mat_file=[files(p).folder,'/',filename];
load(mat_file);

cast_num = regexp(mat_file,'\d+(?=\.mat)','once','match');

% display(msg_file)

% Calculate Sound Speed
sound = gsw_sound_speed(HR.SA,HR.CT,HR.P);

SOUND(1:length(sound),p)=sound;
DEPTH(1:length(sound),p)=HR.DEPTH;

% Addin Sound Speed to HR structure in mat files.
HR.soundspeed=sound; % in m/s
save_str=[dirs.mat, WMO,'.', cast_num,'.mat'];
save(save_str,'HR');

end

%% ------------ Plot ALL profile data (from a mission) --------------------

% Plot Sound Speed profile
figure(1)

plot(SOUND,DEPTH,'-o'); axis ij
xlim(range(SOUND))
ylim([0 maxp])
xlabel('Sound Speed [m/s]');

hold on;
mSound=nanmean(SOUND,2);
mDepth=nanmean(DEPTH,2);
plot(nanmean(SOUND,2),nanmean(DEPTH,2),'k') ; axis ij % mean profile for sound speed

title(mission)

print_setup(20,30)
print([path_plots,'SoundSpeed_HR_allprofiles_2021Nov_16-17.jpg'],'-djpeg');

%% Save mean Sound Speed profile in ascii

S=[mDepth mSound];
S(isnan(S(:,1)),:)=[];

save('SoundSpeed_CPF003_2021Nov_16-17.txt','S','-ascii','-tabs');
type('SoundSpeed_CPF003_2021Nov_16-17.txt')

