%   Script: getNavData
%   Author: Daniel O'Hara
%   Date: 12/6/2015
%   Description: Script to collect any new raw navigation data from the data
%   server and save the formatted version onto local.

load('codePaths.mat')
folderPath = path_cnav; %local directory.
dataPath = '\\192.168.3.19\mgl1521\raw\serial'; %server directory. 

navDataFileHeader = 'MGL-cnav3050.'; %File name header.

navDataFiles = ls([dataPath,'\',navDataFileHeader,'*']); %Collect all data 
                                                         %  file titles.

navDataTitles = {'Year','Day','Hour','Minute','Second','Heading (True N)','Speed Over Ground','Latitude DD','Longitude DD'};
     % Formatted data fields.

nVS = size(navDataFiles); %Loop through files, collecting and saving new data. 
                        %   (Currently, ignore newest file since it is still 
                        %   being updated).

for i = 1:nVS(1,1)-1
    ext = navDataFiles(i,11:end);
    if ~exist([folderPath,'\','Nav_',ext,'_Data.mat'],'file')
        disp(sprintf('Processing %s',navDataFiles(i,:)))
        navData = [];
        fid = fopen([dataPath,'\',navDataFiles(i,:)]);
        tline = fgetl(fid);
        oldLine = NaN;
        while ischar(tline)
            if strcmp(oldLine,tline) == 1
                disp('hit')
            end
            disp(tline)
            tt = strsplit(tline,'\t');
            dt = strsplit(tt{1,2},':');
            row = [str2num(dt{1,1}),str2num(dt{1,2}),str2num(dt{1,3}),str2num(dt{1,4}),str2num(dt{1,5})];
            try
            ll = strsplit(tt{1,3},',');
            lat = ll{1,3};
            lon = ll{1,5};
            latDD = str2num(lat(1:2))+str2num(lat(3:end))/60;
            lonDD = str2num(lon(1:3))+str2num(lon(4:end))/60;
            tline = fgetl(fid);
            cS = strsplit(tline,',');
            row = [row,str2num(cS{1,2}),str2num(cS{1,5}),latDD,lonDD];
            catch er
                row = [row, NaN,NaN,NaN,NaN];
            end
            navData = [navData;row];
            oldLine = tline;
            tline = fgetl(fid);
        end
        save([folderPath,'\','Nav_',ext,'_Data.mat'],'navData','navDataTitles');
    end
end