%{
    process_seapath.m
    
    reads Investigator seapath 10 Hz attitude netCDF files and saves
    variables in hourly .mat format

    netCDF file name format: yyyymmdd-hhmmss-shipattitude-seapath_01.att
%}
clear

% 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;

att_path = 'D:\Data\CAPRICORN_2016\Investigator\flux\SCS\att';
mat_path = 'D:\Data\CAPRICORN_2016\Investigator\flux\SCS\att\mat';
mkdir(mat_path);
t0 = datenum(1899,12,31);  % zero time for netCDF timestamps
t00 = datenum(2015,12,31); % zero time for 2016 day-of-year values

cd(att_path);
files = dir('*shipattitude-seapath_01.att');

N = length(files);
jj = 1;

% read 4 files at a time and save to hourly mat format
while jj<N-1
    jd_sp = []; head = []; roll = []; pitch = []; heave = [];
    for ii = jj:min(jj+4,N)
        fname = files(ii).name;
        disp(['reading netCDF file ',fname])
        temp = ncread(fname,'time') + t0 - t00;
        jd_sp = [jd_sp;temp];
        temp = ncread(fname,'head');
        head = [head;temp];
        temp = ncread(fname,'roll');
        roll = [roll;temp];
        temp = ncread(fname,'pitch');
        pitch = [pitch;temp];
        temp = ncread(fname,'heave');
        heave = [heave;temp];
    end;
    
    zz = find(isfinite(jd_sp));
    jd_sp = jd_sp(zz); head = head(zz); roll = roll(zz);
    pitch = pitch(zz); heave = heave(zz);
    
    % interp to exact 10 Hz timestamp and save as hourly .mat files
    sthr = ceil(jd_sp(1)*24)/24;
    endhr = floor(jd_sp(end)*24)/24 - 1/24;
    for ii = sthr:1/24:endhr
        jdref = ii:1/864000:ii+1/24-1/864000; jdref = jdref(:);
        jd = sprintf('%03i',floor(jdref(1)));
        hr = sprintf('%02i',round(mod(jdref(1),1)*24));
        att = NaN(36000,5);
        att(:,1) = jdref;
        att(:,2) = interp1(jd_sp,head,jdref,'linear');
        att(:,3) = interp1(jd_sp,roll,jdref,'linear');
        att(:,4) = interp1(jd_sp,pitch,jdref,'linear');
        att(:,5) = interp1(jd_sp,heave,jdref,'linear');
        fout = fullfile(mat_path,['seapath_',jd,'_',hr,'.mat']);
        disp(['saving seapath file ',jd,' ',hr])
        save(fout,'att');
    end;
    clear jd_sp head roll pitch heave att
    jj = jj + 4;  % increment by 3 to repeat last file
end;

