% process_raw_heading.m
%{
reads raw ship heading files and interpolates to exact 10 Hz timestamp 
over entire cruise

input: dfl is path to folder containing raw heading files with name
  convention as follows:
    SGBrownPortGYRO-$HEHDT_yyyymmdd-nnnnnn.Raw
    SGBrownStbdGYRO-$HEHDT_yyyymmdd-nnnnnn.Raw
%}

%% path and file names
close all
clear
dfl = '/Users/byronb/Raw_Data_Files.noindex/WHOTS_2015/Hiialakai/SCS/Ship_Archive/WHOTS-SCS-15/NAV';
fnames_port = dir(fullfile(dfl,['SGBrownPortGYRO*.Raw']));
fnames_stbd = dir(fullfile(dfl,['SGBrownStbdGYRO*.Raw']));

%% loop through port gyro files
N = length(fnames_port);
for jj = 1:N
    hedp = NaN(7,0);
    flist = fopen(fullfile(dfl,fnames_port(jj).name));
    temp = {};    % empty arrays for textscan
    % read file
    while feof(flist)==0,	% read entire file into cell array
        % temp will be 1x7 cell array
        temp =textscan(flist,'%2f/%2f/%4f %f:%f:%f %*6c %f %*[^\n]','delimiter', ',','emptyvalue',NaN);
        if ~isempty(temp{1,1})
            for ii=1:7
                temp{1,ii}(length(temp{1,7}))=[];  % kill last row
            end;
            hedp = [hedp cell2mat(temp)'];  % 7 col array
        end;
    end;
    fclose(flist);
    hedp = hedp';
    ddd = md2yd(hedp(100,3), hedp(100,1), hedp(100,2));
    jd_hed = md2yd_vn(hedp(:,3), hedp(:,1), hedp(:,2)) + hedp(:,4)/24 + hedp(:,5)/1440 + hedp(:,6)/86400;
    zz = find(floor(jd_hed)==ddd);
    hedp = hedp(zz,7); jd_hed = jd_hed(zz);
    clear zz temp
    hed2 = downsample(hedp,6);
    jd_hed2 = downsample(jd_hed,6);
    jd_ref = ddd:1/864000:ddd+1; jd_ref = jd_ref(1:end-1);
    hed = interp1(jd_hed2,hed2,jd_ref,'linear','extrap');
    clear hedp jd_hed hed2 jd_hed2
    kk = 1;
    for ii=0:23
        M = NaN(36000,2);
        sfile = fullfile(dfl,['LRGport_',sprintf('%03i',ddd),'_',sprintf('%02i',ii),'.txt']);
        M(:,1) = jd_ref(kk:kk+35999);
        M(:,2) = hed(kk:kk+35999);
        save(sfile,'M','-ascii','-tabs');
        kk = kk+36000;
    end;
    clear hed jd_ref
end;



