function [error] = readAsciiSample( hMainFig, filename, type )
% [error] = readAsciiSample( hMainFig, filename, type )
% Function to read Bucket data in ASCII format. 
%
% Input
% -----
% hMainFig ........... Handel to the main user interface
% filename ........... Data filename
% type ............... type of data : btl, ext
%
% Output
% ------
% error .............. 1: OK - -1 : an error occured
%
% $Id$

error = 1;

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

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

% Get NO_CONTROL code value
% -------------------------
NO_CONTROL = get(tsg.qc.hash, 'NO_CONTROL', 'code');

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

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

% 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 parameter 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

% Build the format depending on the header parameters
% 1 - Decimate the HEADER - The 7th first parameters are always
%     %HEADER YEAR MNTH DAYX hh mm ss
% 2 - The 6 Date and time parameters are read in %d
% -------------------------------------------------------------
format = '%d %d %d %d %d %d';
for i = 7 : nHeader
  if isempty( strfind(char(header(i)),  'TYPE'))    && ...
     isempty( strfind( char(header(i)), 'BOTTLE') ) && ...
     isempty( strfind( char(header(i)), 'ANALDATE') );
    format = [format ' %f'];
  else
    format = [format ' %s'];
  end
end

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

% Convert cell to a structure
% ---------------------------
s = cell2struct(cellData, header, 2);

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

clear cellData

% Test if at least one variable (SSPS or SSTP) exists. If one is missing
% create the array filled with NaN
% ----------------------------------------------------------------------
if isempty(strmatch('SSTP_EXT',header)) && isempty(strmatch('SSPS_EXT',header))
  error = -1;
  return;
end
if isempty(strmatch('SSTP_EXT',header)) && ~isempty(strmatch('SSPS_EXT',header))
  s.SSTP_EXT = NaN * ones( size( s.SSPS_EXT ) );
  header = [header; 'SSTP_EXT'];
end
if isempty(strmatch('SSPS_EXT',header)) && ~isempty(strmatch('SSTP_EXT',header))
  s.SSPS_EXT = NaN * ones( size( s.SSTP_EXT ) );
  header = [header; 'SSPS_EXT'];
end
   
% Test if the fiels _TYPE, _QC; _ANALDATE (for SSPS) exists for the variables
% If they don't create them
% ---------------------------------------------------------------------------
PARA = {'SSPS_EXT'; 'SSTP_EXT' };
for i = 1:2
  para = PARA{i};

  if isempty( strmatch([para '_TYPE'], header))
    label = 'UNKN';
    s.([para '_TYPE']) = label( ones(length(s.(para)),1), :);
    header = [header; [para '_TYPE']];
  end

  if isempty( strmatch([para '_QC'], header))
    s.([para '_QC']) = NO_CONTROL * int8(ones( size( s.(para) )));
    header = [header; [para '_QC']];
  end

  if isempty(strmatch([para '_ANALDATE'], header)) && strcmp(para, 'SSPS_EXT')
    label = '19500101000000';
    s.([para '_ANALDATE']) = label( ones(length(s.(para)),1), :);
    header = [header; [para '_ANALDATE']];
  end
  
  if isempty(strmatch([para '_BOTTLE'], header)) && strcmp(para, 'SSPS_EXT')
    label = '0';
    s.([para '_BOTTLE']) = label( ones(length(s.(para)),1), :);
    header = [header; [para '_BOTTLE']];
  end

end

% Date (y m d h m s) in the first 6 elements in data
% --------------------------------------------------
yy = double( s.(char(header(1))) );
mm = double( s.(char(header(2))) );
dd = double( s.(char(header(3))) );
hh = double( s.(char(header(4))) );
mi = double( s.(char(header(5))) );
ss = double( s.(char(header(6))) );

s.DAYD_EXT = datenum(yy, mm, dd, hh, mi, ss);
s.DATE_EXT = datestr( s.DAYD_EXT, 'yyyymmddHHMMSS' );

% Transfer the 's' structure to the 'tsg' structure
% -------------------------------------------------
error = concatSample( hMainFig, s );

if error
   tsg.report.([ lower(type) 'file']) = filename;
end

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

end
