% load ship winds, STRATUS 2015

% reads raw Cabo de Hornos wind files & computes 1-min avg true
% and relative winds.

% saves output to .mat file for entire cruise

% 5/26/15 BWB
windPath = '/Users/byronb/Raw_Data_Files.noindex/STRATUS_2015/Cabo_de_Hornos/SCS/Raw/04';
fnameRoot = 'WIND_STRATUS_201504';
jdref = 108 + (0:11*1440-1)/1440; % 24 hr ref timestamp for entire cruise
twspd = jdref*NaN; twdir = twspd; rwspd = twspd; rwdir = twspd;
N = 1;
for ii = 18:28  % daily loop
    fname = [fnameRoot,sprintf('%02i',ii),'.txt'];
    dfl = fullfile(windPath,fname);
    fin = fopen(dfl);
    temp = {};
    temp = textscan(fin,'%f/%f/%f %f:%f:%f %f %f %f %f %*[^\n]','delimiter',', ','headerlines',0,'emptyvalue',NaN);
    stx = cell2mat(temp)';
    % convert speeds to m/s
    stx(7,:) = stx(7,:)*0.5144;
    stx(9,:) = stx(9,:)*0.5144;
    % convert winds to sin/cos components
    twinc = stx(7,:).*cos(stx(8,:)*pi/180);
    twins = stx(7,:).*sin(stx(8,:)*pi/180);
    rwinc = stx(9,:).*cos(stx(10,:)*pi/180);
    rwins = stx(9,:).*sin(stx(10,:)*pi/180);
    % average over each minute
    jdmin = 90 + stx(2,:) + (stx(4,:)*60 + stx(5,:))/1440; % to the minute only
    last = jdmin(end);
    while(jdref(N)<=last && N<length(jdref))
        kk = find(jdmin==jdref(N));
        if isempty(kk);
            N=N+1;
            continue;
        end;
        twspd(N) = sqrt(mean(twinc(kk)).^2 + mean(twins(kk)).^2);
        twdir(N) = mod(atan2(mean(twins(kk)),mean(twinc(kk)))*180/pi + 360,360);
        rwspd(N) = sqrt(mean(rwinc(kk)).^2 + mean(rwins(kk)).^2);
        rwdir(N) = mod(atan2(mean(rwins(kk)),mean(rwinc(kk)))*180/pi + 360,360);
        N=N+1;
    end;
end;
% save to .mat file
winds = [jdref',twspd',twdir',rwspd',rwdir'];
savePath = '/Users/byronb/Raw_Data_Files.noindex/STRATUS_2015/Cabo_de_Hornos/SCS';
fsave = fullfile(savePath,'STRATUS_2015_scs_winds.mat');
save (fsave,'winds');
