function removeBackgroundMag()
%   Function: removeBackgroundMag
%   Author: Daniel O'Hara
%   Date: 12/6/2015
%   Description: Remove background magnetic data from measurements. Using
%   magnetic field estimates from the IGRF 2012 model, for the date
%   12/2/15.

    load('codePaths.mat')
    load([path_data,'\Mag_Nav_Data_Cleaned.mat']) % Load combined data.
    load([path_geomag_data,'\BackgroundMag_10_ll.mat']) % Load background 
                                                        %   field data.
    load([path_geomag_data,'\BackgroundMag_10_xy.mat'])
    load([path_geomag_data,'\BackgroundMag_10_DI.mat'])
    load([path_geomag_data,'\BackgroundMag_10_F.mat'])
    
    % Reshape background data to grid format (enters as linear array).
    tmp = magLLData;
    lats = reshape(newLat,gridSize10m);
    lons = reshape(newLon,gridSize10m);
    lats = lats(:,1);
    lons = lons(1,:);
    ff = reshape(newF,gridSize10m);
    dec = reshape(newDec,gridSize10m);
    inc = reshape(newInc,gridSize10m);

    % If the file of removed background data already exists, open it to
    % append more to it. Otherwise, create a new file.
    if exist([path_data,'\Mag_Nav_Data_NoBackground.mat'],'file')
        load([path_data,'\Mag_Nav_Data_NoBackground.mat'])
        tt = magLLData_noB;
        magLLData_noB = tt;
        clear tt
        tmp(tmp(:,6)<=magLLData_noB(end,6),:) = [];
    else
        magLLData_noB = [];
        magLLData_noB_Titles = magLLDataTitles;
    end

    s = size(tmp);
    newTmp = zeros(s(1,1),20);
    
    % Collect background magnetic field at each point (to the closest
    % position) and remove it from the raw.
    for i = 1:s(1,1)
        disp(sprintf('Processing %d / %d',i,s(1,1)))
        try
        row = tmp(i,:);
        tlat = abs(lats-row(8));
        tlon = abs(lons-row(9));
        [ti,~] = find(tlat==min(tlat),1);
        [~,tj] = find(tlon==min(tlon),1);
        row(1,14) = ff(ti,tj);
        row(1,15) = dec(ti,tj);
        row(1,16) = inc(ti,tj);
        row(1,19) = row(1,18)-row(1,14);
        newTmp(i,:) = row;
        catch er
            disp('here')
        end
    end

    % Save results.
    magLLData_noB = [magLLData_noB;newTmp];
    save([path_data,'\Mag_Nav_Data_NoBackground.mat'],'magLLData_noB','magLLData_noB_Titles','-v7')
end