function [error] = readTsgDataTxt( hMainFig, filename)
% Function to read the TSG data. Should be a NetCDF file
%
% 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'
%
%
% Caution : replace the fill-value with NaN
% $Id$

% Get the data from the application GUI
% -------------------------------------
tsg = getappdata( hMainFig, 'tsg_data');

% Display read file info on console
% ---------------------------------
fprintf('\nREAD_ASCII_FILE\n'); tic;

% Open the file
% -------------
fid = fopen( filename, 'r' );

% Check file
% -----------
if fid == -1
  msg_error = ['TSG_GOSUD file_lecture : Open file error : ' filename];
  warndlg( msg_error, 'ASCII error dialog');
  sprintf('...cannot locate %s\n', filename);
  error = -1;
  return;
end

% Display more info about read file on console
% --------------------------------------------
fprintf('...reading %s : ', filename);

% Read the file
% -------------
tsgData = fscanf(fid, '%d/%d/%d %d:%d:%d %f %f %f %f %d %f %f', [13 Inf])';

% Every variable are put in a structure
% -------------------------------------
tsg.DAYD = datenum(tsgData(:,3), tsgData(:,2),tsgData(:,1), ...
                   tsgData(:,4),tsgData(:,5),tsgData(:,6));

% save original date
% ------------------
tsg.DATE                = datestr(  tsg.DAYD, 'yyyymmddHHMMSS' );
tsg.LATX                = tsgData(:,7);
tsg.LONX                = tsgData(:,8);
tsg.SSJT                = tsgData(:,9);
tsg.SSPS                = tsgData(:,10);
tsg.SSPS_QC             = tsgData(:,11);
tsg.SSPS_ADJUSTED       = tsgData(:,12);
tsg.SSPS_ADJUSTED_ERROR = tsgData(:,13);

tsg.SSJT_QC             = tsg.SSPS_QC;

% populate tsg.file structure
% ---------------------------
[tsg.file.pathstr, tsg.file.name, tsg.file.ext, tsg.file.versn] = ...
                                                         fileparts(filename);
%tsg.file.name = filename;
tsg.file.type = 'ASCII';

% Keep somme information for the log file
% ---------------------------------------
tsg.report.tsgfile = filename;

% Save the data in the application GUI
% ------------------------------------
setappdata( hMainFig, 'tsg_data', tsg );

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

% Close the file
% --------------
fclose( fid );

% Clear the Workspace
% -------------------
clear tsgdata

% Display time to read file on console
% ------------------------------------
t = toc; fprintf('...done (%6.2f sec).\n\n',t);

% Everything OK
% -------------
error = 1;
