function [error] = readAsciiData( hMainFig, filename, type)
% Function to read Bucket data in ASCII format. 
%
% Input
% -----
% hMainFig ........... Handel to the main user interface
% filename ........... Data filename
% type ............... Can read 3 types of data : WS, EXT, TSG
%
% Output
% ------
% error .............. 1: OK - -1 : an error occured

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

% Get the fieldnames of tsg structure
% -----------------------------------
tsgNames     = fieldnames(tsg);
nbFieldNames = length( tsgNames );

% 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 header till the header line has been read
% --------------------------------------------------
OK = 0;
while ~OK
  
  % Read every line
  % ---------------
  line = fgetl( fid );
  c = textscan( line, '%s');
  
  switch char( c{1}(1) )

    case '%HEADER'

      % Read the header then quit the while loop
      % ----------------------------------------
      header = c{1}(2:end);
      nHeader = length( header );
      OK = 1;

    otherwise

      % Get the paramete Name (Delete '%')
      % ----------------------------------
      Para = char( strtok(c{1}(1), '%') );
      
      % Read the parameter value
      % ------------------------
      ind = strmatch( Para, tsgNames);
      if ~isempty( ind )
        tsg.(Para) = char( c{1}(2) );
      end
      
  end
end

% Read the data in a cell
% -----------------------
cellData = textscan( fid, '%f' );

% Convert the data to double
% --------------------------
nCol  = nHeader;
mLine = length( cellData{:} )/nCol;
data = NaN * ones( mLine, nCol );
ind = 0;
for i = 1:mLine
  for j = 1:nCol
    ind = ind + 1;
    data(i,j) = cellData{1}(ind);
  end
end

clear cellData

% Date (y m d h m s) in the first 6 elements in data
% --------------------------------------------------
switch type
  
  case 'WS'
          
    keep = 1;
    if ~isempty( tsg.DAYD_WS )
      button = questdlg('Do you want to add the present file ?',...
                        'Water sample already loaded ','Yes', 'No', 'No'); 
        
      switch button
        case 'Yes'
          keep = 1;
        case 'No'
          keep = 0;
          tsg.DAYD_WS = [];
      end
    end
    
    tsg.DAYD_WS  = [tsg.DAYD_WS;  ...
      datenum(data(:,1), data(:,2),data(:,3),data(:,4),data(:,5),data(:,6))];
    tsg.report.wsfile   = filename;

  case 'EXT'
          
    keep = 1;
    if ~isempty( tsg.DAYD_EXT )
      button = questdlg('Do you want to add the present file ?',...
                        'External Water sample already loaded ', 'Yes', 'No', 'No');
      switch button
        case 'Yes'
          keep = 1;
        case 'No'
          keep = 0;
          tsg.DAYD_EXT = [];
      end
    end
    tsg.DAYD_EXT = [tsg.DAYD_EXT; ...
      datenum(data(:,1), data(:,2),data(:,3),data(:,4),data(:,5),data(:,6))];
    tsg.report.extfile  = filename;

  case 'TSG'
    keep = 0;
    tsg.DAYD    = ...
      datenum(data(:,1), data(:,2),data(:,3),data(:,4),data(:,5),data(:,6));
    tsg.report.tsgfile = filename;

  otherwise
    msg('function ''readTsgDataAscii'' - Bad TYPE', 'Modal' );
end
      
% Loop over the header. Skip the 6 first elements
% -----------------------------------------------
for i = 7 : nHeader
  
  % Test if we concatenate the data
  % -------------------------------
  if keep

    % QC should be converted in int8
    % ------------------------------
    if ~isempty( strfind(char(header(i)), '_QC'))
      tsg.(char(header(i))) = [tsg.(char(header(i))); int8( data(:,i) )];
    else
      tsg.(char(header(i))) = [tsg.(char(header(i))); data(:,i)];
    end
    
  else
    
    % QC should be converted in int8
    % ------------------------------
    if ~isempty( strfind(char(header(i)), '_QC'))
      tsg.(char(header(i))) = int8( data(:,i) );
    else
      tsg.(char(header(i))) = data(:,i);
    end
  end
  
end

if strcmp( type ,'TSG' )
  
  % populate tsg.file structure
  % ---------------------------
  [tsg.file.pathstr, tsg.file.name, tsg.file.ext, tsg.file.versn] = ...
                                                           fileparts(filename);
  
  % Perform somme automatic tests
  % -----------------------------
  automaticQC( hMainFig );

  tsg.file.type = 'ASCII';

end

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

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

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

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

end