function combineMN2()
%   Function: combineMN2
%   Author: Daniel O'Hara
%   Date: 12/6/2015
%   Description: Function to combine raw magnetic and navigation data by
%   matching the two to the nearest second.

    load('codePaths.mat')
    load([path_data,'\MGN_Data.mat'])   % Raw magnetic & navigation .mat 
                                        %   files

    magDates = allMagData(:,6); % Collect dates.
    navDates = allNavData(:,6);

    % If the combined data already exists, open the .mat to append any new
    % data. Otherwise, create a new .mat file.
    if exist([path_data,'\Mag_Nav_Data.mat'],'file')
        load([path_data,'\Mag_Nav_Data.mat'])
        tmp = magLLData;
        magNavData = allNavData;
        magNavData((navDates(:,1) >= tmp(end,6))==0,:) = [];
    else
        magLLData = [];
        magLLDataTitles = {'Year','Day','Hour','Minute','Second','Serial Date','Time Difference','Latitude','Longitude',...
            'X','Y','Cumulative Length','Heading','Background Field Str','Background Field Dec.','Background Field Inc.',...
            'Ship Correction','Raw Field Str','No Background Field Str','No Background-Ship Field Str'};
            % Date fields used through entire processing.
        magNavData = allNavData;
        magNavData((navDates(:,1) >= magDates(1,1))==0,:) = [];
    end

    sMN = size(magNavData);
    if sMN(1,1) < 2
        sMN(1,1) = 0;
    end
    tt = zeros(sMN(1,1),20).*NaN;
    
    % Combine data to nearest second.
    for i = 1:sMN(1,1)
        disp(sprintf('Processing Mag %d / %d',i,sMN(1,1)))
        mm = abs(magDates-magNavData(i,6));
        [index,~] = find(mm == min(mm),1);
        [x,y] = ll2utm(magNavData(i,10:11)); % Convert lat,lon to x,y
        % Collect distance between samples.
        if i > 1
            cumL = sqrt((tt(i-1,10)-x).^2+(tt(i-1,11)-y).^2);
        else
            cumL = 0;
        end
        tt(i,:) = [allMagData(index,1:7),magNavData(i,10:11),x,y,cumL,magNavData(i,8),NaN,NaN,NaN,NaN,allMagData(index,8),NaN,NaN];
    end
    magLLData = [magLLData;tt];

    % Collect time differences.
    dif = diff(magLLData(:,6),1,1);
    dif = [0;dif];
    magLLData(:,7) = dif;

    % Save results.
    save([path_data,'\Mag_Nav_Data.mat'],'magLLData','magLLDataTitles','-v7')
end