% Process 10min averages from daily nav_xxx.mat files produced by
% process_nav.m script

%% initialize

clear
close all

% matlab script path
path_prog = fullfile('c:\Users\Sergio\Documents\MATLAB\2016_CAPRICORN\check_ship_data');
cd(path_prog);                  % cd to matlab directory
restoredefaultpath              % reset matlab path
addpath(genpath(path_prog));	% add scripts to path
savepath; rehash;

mat_path = 'D:\Data\CAPRICORN_2016\Investigator\flux\SCS\nav\mat';

cd(mat_path);
files = dir('nav*.mat');
nav10 = NaN(length(files)*140,7);
fout = fullfile(mat_path,['CAPRICORN_2016_nav10.mat']);

%% average
for ii = 1:length(files)
    fname = files(ii).name;
    disp(['loading ',fname]);
    % input array nav is [jd,Ngnd,Egnd,Nsfc,Esfc,Ndft,Edft]
    load(fname);
    ddd = floor(nav(1,1));     % day of year
    jdref = ddd:10/1440:ddd+1; jdref = jdref(:); % 10-minute bin edges
    temp = interval_avg(nav(:,1),nav(:,2:end),jdref);
    idx = ii*144-143:ii*144; idx = idx(:);
    nav10(idx,:) = temp;
end;

%% compute spd/dir
Gdir10 = mod(atan2(nav10(:,3),nav10(:,2))+2*pi, 2*pi)*180/pi;
Gspd10 = sqrt(nav10(:,2).^2 + nav10(:,3).^2);

Sdir10 = mod(atan2(nav10(:,5),nav10(:,4))+2*pi, 2*pi)*180/pi;
Sspd10 = sqrt(nav10(:,4).^2 + nav10(:,5).^2);

Ddir10 = mod(atan2(nav10(:,7),nav10(:,6))+2*pi, 2*pi)*180/pi;
Dspd10 = sqrt(nav10(:,6).^2 + nav10(:,7).^2);

nav10 = [nav10,Gspd10,Gdir10,Sspd10,Sdir10,Dspd10,Ddir10]; % Nx13 array

%% save mat file & plot
disp('saving 10 min nav file')
save(fout,'nav10');

jd = nav10(:,1);
figure; plot(jd,Dspd10); grid; title('Current Speed');
figure; plot(jd,Ddir10); grid; ylim([0,360]); title('Current Direction');

