function [error] = readTsgDataNetCDF( hMainFig, filename)
% Function to read the TSG data. Should be a NetCDF file
% GOSUD data format
%
% Input
% -----
% hMainFig ............ Handle to the main user interface
% filename ............ Data filename
%
% Output
% ------
% error .............. 1: OK - -1 : an error occured
%
% The data are store using setappdata - Variable name : 'tsg_data'
%
% DAYD, DAYD_WS and DAYD_EXT in tsg structure use Matlab datenum, they 
% should be converted from julian days using 1950 reference in NetCDF file 
%
% $Id$

%% Check Netcdf library version
% -----------------------------
switch ( version('-release') )
  case { '11', '12', '13', '14', '2006a', '2006b', '2007a', '2007b', '2008a' }
    read_netcdf_toolbox;
  otherwise
    read_netcdf_native;
end

% Perform somme automatic tests
% -----------------------------
automaticQC( hMainFig )


%% Nested functions
% -----------------

% use Charles Dunham toolbox
% --------------------------
  function read_netcdf_toolbox
    
    % Get the data from the application GUI
    % -------------------------------------
    tsg = getappdata( hMainFig, 'tsg_data');
    
    % Display read file info on console
    % ---------------------------------
    fprintf('\nREAD_NETCDF_FILE\n'); tic;
    
    % Open netCDF file
    % ----------------
    nc = netcdf(filename,'read');
    if isempty(nc)
      msg_error = ['TSG_GOSUD file_lecture : Open file error : ' filename];
      warndlg( msg_error, 'NetCDF error dialog');
      sprintf('...cannot locate %s\n', filename);
      error = -1;
      return;
    end
    
    % Display more info about read file on console
    % --------------------------------------------
    fprintf('...reading %s : ', filename);
    
    % populate tsg.file structure
    % ---------------------------
    [tsg.file.pathstr, tsg.file.name, tsg.file.ext] = ...
      fileparts(filename);
    tsg.file.type = 'NETCDF';
    
    % get global attributes: meta data
    % --------------------------------
    global_att = att(nc);
    
    for i=1:length(global_att)
      
      % extract name and value from netcdf globals attributes
      % -----------------------------------------------------
      attribute = name(global_att{i});
      value     = global_att{i}(:);
      
      % assign globals attributes in base workspace
      % -------------------------------------------
      assignin('base', attribute, value);
      
      % populate tsg structure with globals attributes
      % ----------------------------------------------
      tsg.(attribute) = value;
    end
    
    % get variables describing TSG installation
    % -----------------------------------------
    variables = var(nc);
    
    for i=1:length(variables)
      
      % extract name and value from netcdf variables
      % --------------------------------------------
      variable = name(variables{i});
      %value    = variables{i}(:);
      nv       = nc{i};
      
      % use autonan mode, remplace fillValue with NaN
      % ---------------------------------------------
      nv = autonan(nv, true);
      
      % finally replace fillvalue with NaN when only fillvalue exist
      % ------------------------------------------------------------
      %   if ~isempty(fillval(nc{i}))
      %     value(value == fillval(nc{i})) = NaN;
      %   end
      
      % populate tsg structure with netcdf variables
      % --------------------------------------------
      tsg.(variable) = nv(:);
      
      % transforme julian days variables to Matlab datenum
      % --------------------------------------------------
      if strmatch('DAYD', variable)
        tsg.(variable) = julianToDatenum(tsg.(variable));
      end
      
      % save in tsg structure attribute conventions for DATE viariables
      % ---------------------------------------------------------------
      if strmatch('DATE', variable)
        tsg.conventions.(variable) = nv.conventions(:);
      end
      
      % assign netcdf variables in base workspace
      % -----------------------------------------
      assignin('base', variable, nv(:));
      
    end % end of variables loop
    
    % Keep somme information for the log file
    % ---------------------------------------
    tsg.report.tsgfile = filename;
    
    % Save the data in the application GUI
    % ------------------------------------
    setappdata( hMainFig, 'tsg_data', tsg );
    
    % Close the file
    % --------------
    close(nc);
    
    % Display time to read file on console
    % ------------------------------------
    t = toc; fprintf('...done (%5.2f sec).\n\n',t);
    
    % Everything OK
    % -------------
    error = 1;
    
  end % end of read_netcdf_toolbox

% use native toolbox +netcdf since R2008b
% ---------------------------------------
  function read_netcdf_native
    
    % Get the data from the application GUI
    % -------------------------------------
    tsg = getappdata( hMainFig, 'tsg_data');
    
    % Display read file info on console
    % ---------------------------------
    fprintf('\nREAD_NETCDF_FILE\n'); tic;
    
    % populate tsg.file structure
    % ---------------------------
    [tsg.file.pathstr, tsg.file.name, tsg.file.ext] = ...
      fileparts(filename);
    tsg.file.type = 'NETCDF';
    
    % Open netCDF file
    % ----------------
    nc = netcdf_native(filename);
    
    % loop over all variables and get associated value in tsg structure
    % -----------------------------------------------------------------
    for key = keys(nc.VARIABLES)
      var = char(key);
      tsg.(var) = nc.VARIABLES.(var).data__;
      
      % when variable is julian days from 1950 reference, transform to
      % Matlab datenum
      % --------------------------------------------------------------
      if strmatch('DAYD', var)
        tsg.(var) = julianToDatenum(tsg.(var));
      end
      
      % save in tsg structure attribute conventions for DATE variables
      % ---------------------------------------------------------------
      if strfind(var, 'DATE')
        if strcmp(nc.VARIABLES.(var).conventions, 'yyyymmddhhmmss')
          tsg.conventions.(var) = 'yyyymmddHHMMSS';
        elseif strcmp(nc.VARIABLES.(var).conventions, 'YYYYMMDDHHMISS')
          tsg.conventions.(var) = 'yyyymmddHHMMSS';
        else
          tsg.conventions.(var) = nc.VARIABLES.(var).conventions;
        end
      end
      
      % assign variable in base workspace
      % -------------------------------------------
      assignin('base', var , tsg.(var));
    end
    
    % loop over all global attributes and get associated value in
    % tsg structure
    % -----------------------------------------------------------------
    for key = keys(nc.ATTRIBUTES)
      att = char(key);
      tsg.(att) = nc.ATTRIBUTES.(att).data__;
      
      % assign globals attributes in base workspace
      % -------------------------------------------
      assignin('base', att , tsg.(att));
    end
    
    % Save the data in the application GUI
    % ------------------------------------
    setappdata( hMainFig, 'tsg_data', tsg );
    
    
    % Close the file
    % --------------
    %close(nc);
    
    % Display time to read file on console
    % ------------------------------------
    t = toc; fprintf('...done (%5.2f sec).\n\n',t);
    
    % Everything OK
    % -------------
    error = 1;
    
  end % end of read_netcdf_native

end % end of readTsgDataNetCDF
