%% hotelfile_slocum_netcdf
% Generate a hotel-file from NetCDF files generated by a Slocum Glider
%%
% <latex>\index{Scripts!hotelfile\_slocum\_netcdf}</latex>
%
%%% Syntax
%   User Script:  hotelfile_slocum_netcdf
%
% * [depl_date] Optional deployment date. Leave empty for all files.
% * [glider] Glider name. If left empty the name will be extracted from the
%         NetCDF files. 
% * []
% * [hotelfile_date_glider.mat] Script generated hotel-file with unique
%         name constructed from the NetCDF file names. The user can,
%         optionally, force the name to a desired value.
%
%%% Description
% Generate a hotel-file from the NetCDF mission-files of a Webb Slocum
% glider that were generated by Webb-supplied software.
%
% The resulting hotel-file contains the subset of data from the NetCDF
% mission-files that may be used for a variety of purposes directly from
% within a RSI data mat-file. All of the vectors that are
% extracted from the mission-files are interpolated on to the RSI
% $\texttt{t\_fast}$ and $\texttt{t\_slow}$ time vectors. The mission data
% vectors are renamed using $\texttt{\_fast}$ and $\texttt{\_slow}$
% postfixes. A direct comparison of mission-file data and RSI recorded data
% is then possible.
%
%%% Examples
% The hotel-file can be generated by navigating to the directory directly
% above the directory containing the NetCDF files. This script is then
% executed.
%
%    >> hotelfile_slocum_netcdf
%
% The resulting-hotel file can then be used with $\texttt{odas\_p2mat}$. In
% this example, a RSI raw binary data file ending in $\texttt{16}$ is used.
%
%    >> odas_p2mat('*16', 'vehicle', 'slocum_glider', ...
%                  'hotel_file', 'hotelfile_08-18-2015_bob_mr_test.mat');
%
% If there is a time offset between the RSI data and the data supplied
% within in the mission-file, a time offset can be added to the RSI
% instrument time.
%
%    >> odas_p2mat('*16', 'vehicle', 'slocum_glider', ...
%                  'hotel_file', 'hotelfile_08-18-2015_bob_mr_test.mat', ...
%                  'time_offset', -5);
%
% This is a script that you must edit. The parameters for the directory
% holding the NetCDF files, the deployment date, the glider name and the
% output file name, are near the top of the function. The names 
% of the desired data in the mission-file, and the names that they will
% attain in your RSI data mat-file are tabulated just below the parameter
% names. 
%
% Using this script is entirely optional for a MicroRider mounted on a
% Slocum glider because the pressure record, pitch angle
% ($\texttt{-Incl\_Y}$) and the angle-of-attack ($\texttt{aoa}$) will be
% automatically used to determine the speed of profiling. That is all that
% is needed to convert your data into physical units. This function is
% necessary if you want to compare mission data, such as pressure, pitch
% and roll against the same data recorded by the MicroRider. Also, if you
% have an uncalibrated FP07 thermistor, then the CTD data in the
% mission-file can be used to calibrate the FP07 using in-situ data (see
% the function $\texttt{cal\_FP07\_in\_situ}$). 
%
%%% Credit
%
% # Anatoli Erofeev, Oregon State University. The code used in this script
% is inspired by the scripts and functions developed by Anatoli.
%

%==========================================================================
%===================  glider_dataproc_pass2_nc.m ==========================
% aerofeev@coas.oregonstate.edu, Anatoli Erofeev, 08-19-2015
%==========================================================================
%
% 2015-08-20, RGL, Obtained this script from Anatoli. We shoud modifiy it
%   to reduce the list of flight and science signals needed to meet the needs of RSI
%   and also make it work for both the Webb Research Slocum glider and also
%   the Kongsberg Sea-glider. Both gliders provide a netCDF file, but the
%   names of the fields of interest to RSI are different for Slocum and
%   Sea-gliders.
% 2015-08-20, RGL This script is based on read_NetCDF_OSU and has been
%   modified for the requirements of RSI.
% 2015-10-29, RGL Document changes. Added optinal outputfile name


% PATH to location of the resulting hotel file / location of current
% NCF files.
datdir = fullfile( pwd );
ncfdir = fullfile( pwd, 'PASS0' );

% Hotel-file name. Leave empty to use default name generated by this script.
datfile = '';

% NCF files from the specified deployment will be queried for data.
% Set this variable if files with multile different deployment dates
% are found within the same folder.  When left empty, the deployment
% date is extracted from available file names.
depl_date  = '';

% Glider should match the name used when naming NCF files.  If left
% empty, the name will be obtained from files found within the NCF
% file directory.  Only set this variable if you have files from
% gliders with multiple different names stored within the same folder.
glider     = '';

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% END of user variables declarations.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Clear result data - if already defined the script will fail.
clear result;

% Find some NCF files to acquire the file names.
ncfilelist = dir([ncfdir filesep '*.nc']);
parts      = strsplit(ncfilelist(1).name, '.');

% Report error if NCF files not found within specified folder.
if isempty(parts) || length(parts) < 2,
    error('No valid NCF files found at: %s', ncfdir);
end

% When variables left empty, fill values from data extracted
% from the names of available files.
if isempty(depl_date), depl_date = parts{1}; end
if isempty(glider),    glider    = parts{2}; end

% Construct NetCDF input data file names
inputfiles = {
    fullfile( ncfdir, [depl_date '.' glider '.dbd.nc'] )
    fullfile( ncfdir, [depl_date '.' glider '.sbd.nc'] )
    fullfile( ncfdir, [depl_date '.' glider '.ebd.nc'] )
    fullfile( ncfdir, [depl_date '.' glider '.dbd.sci.nc'] )
    fullfile( ncfdir, [depl_date '.' glider '.tbd.nc'] )
};


% Flight information is stored seperatly from scientific data. The
% hotel file does not care but they could be recorded against a
% different time domain so they are processed seperately - albeit
% with the exact same algorithm.
% Note that the time variable is required and must be specified first.
var_data = {
%   Slocum variable name    ODAS_P2MAT required name
    'm_present_time'        'time'
    'm_speed'               'H_speed'
    'm_pressure'            'depth'
    'm_pitch'               'pitch'
    'm_roll'                'roll'
    'm_depth_rate'          'V_speed'
    'sci_m_present_time'    'time'
    'sci_water_pressure'    'P_CTD'
    'sci_water_cond'        'C_CTD'
    'sci_water_temp'        'T_CTD'
};

%%%% Algorithm Overview
%
% For each variable found in column 1 of "var_data", do the following:
% - Scan each NETCDF file for a matching variable.  Load the first match.
% - If column 2 name is "time", save as "time" - otherwise as "data".
% - If we have found both "time" and "data", save as fields within a
%     structure.  This structure is named using column 2 of "var_data" and
%     is placed within the results structure. The results structure will be
%     saved as the hotel file at the end of the script.
%
% To work correctly, the first row must have a second column with name
% "time".  This time vector is applied to subsequent rows.  Additional rows
% with a second column named "time" effectively reset the time domain for
% the following rows.

for sensor = var_data'
    data = [];
    for file = inputfiles'
        try
            data = ncread(file{1}, sensor{1});
            break;
        catch; end
    end
    if strcmpi(sensor{2}, 'time')
        time = data;
    elseif ~isempty(data) && ~isempty(time)
        result.(sensor{2}).data = data;
        result.(sensor{2}).time = time;
    end
end

if ~exist('result', 'var')
    error('Hotel file data not found.');
end

% Modify pressure / depth values so they are in units of dBar
for f = {'P', 'depth', 'P_CTD'}
    if isfield(result,f{1})
        result.(f{1}).data = result.(f{1}).data * 10;
    end
end


if isempty(datfile)
    datfile = fullfile( datdir, ['hotelfile_' depl_date '_' glider '.mat'] );
else
    datfile = fullfile( datdir, [datfile '.mat'] );
end
save(datfile, '-struct', 'result');
