%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%                            OUTPACE 2015                           %%%%
%%%%    Load_outpace_nav.m                                              %%%
%%%%        Description: This script takes the netcdf files found in    %%%
%%%%        DATABASE/NAV/L0, opens them, and writes out a .txt ascii    %%%
%%%%        that can be read by excel. The output is Time (UTC), Lon-   %%%
%%%%        gitude (degrees East, so 175 deg W is written 185 deg E,    %%%
%%%%        and Latitude (deg N, so 17 deg S is -17 deg)                %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Change to correct directory
pathL0 = '/mnt/OUTPACE/DATABASE/NAV/L0/'; % Not tested on satellite, but on
cd(pathL0);                             % personal laptop, MacbookPro w/
                                        % MATLAB 2014b, OSX 10.11.1
                                        
% In this file, we want, every minute, the UTC time, lon, and lat...
dirinfo = dir;
numfiles = length(dirinfo);

lon_nav = [];
lat_nav = [];
time_nav = [];
for j = 1:numfiles
    if length(dirinfo(j).name)>4 && dirinfo(j).name(end) == 'v' % filename ends w/ v for .nav
        
        templon = ncread(dirinfo(j).name,'long'); % This function is in MATLAB 2011a and greater
        templat = ncread(dirinfo(j).name,'lat'); %  If you have an older version, you'll have to
        temptime = ncread(dirinfo(j).name,'time');% use netcdf.open, netcdf.getVar, etc...
        
        % Convert into matlab time...
        temptime = datenum(1899,12,30,0,0,0) + temptime;
        
        lon_nav = [lon_nav templon'];
        lat_nav = [lat_nav templat'];
        time_nav = [time_nav temptime'];
        
    end
end

% Convert lon into deg E (so deg W aren't negative for plotting).
ii = find(lon_nav<0);
lon_nav(ii) = 360+lon_nav(ii);

% Selects data on the minute, every minute...
time_nav = time_nav(54:60:end);
lon_nav = lon_nav(54:60:end);
lat_nav = lat_nav(54:60:end);

% Opens and writes to a .txt file
fid = fopen('OUTPACE_nav.txt','w');
fprintf(fid,'TIME\tLON\tLAT\n');
for j = 1:length(time_nav)
    fprintf(fid,[datestr(time_nav(j)) '\t']);
    fprintf(fid,'%9.5f',lon_nav(j));
    fprintf(fid,'\t');
    fprintf(fid,'%9.5f',lat_nav(j));
    fprintf(fid,'\t');
    fprintf(fid,'\n');
end
fclose(fid);
