function scan(varargin)
% ------------------------------------------------------------------
% Function to perform initial scanning of log files. It does the following:
%
%   - If the index file to data entries in the log file does not exist
%     or is older than the log file, it is created or updated.
%
%   - Scan the log data description header to get the variable names
%     corresponding to the column numbers.
%
%   - While scanning, performs statistical calculations on each of the
%     variables for user information.
%
%   - Calculate the number of data log entries.
%
%
% SYNOPSIS:
%
%   scan()
%   scan(1)
%      
%      Do the steps dscribed above. If the index file does not need 
%      to be created or updated, then nothing is perfomed.
%
%   scan(0)
%
%      Reset the matlab path to its previous value, before entering the
%      `scan' environment, and exit.
%
%   scan(-1)
%
%      As `scan(0)', but also delete the index file.
%
%   scan(2)
%
%      As `scan(1)', but force the creation of the index file, and resets
%      all statistical settings.
%
%   scan(SMIN, SMAX)
%   scan(SMIN, SMAX, SLIM)
%   scan(SMIN, SMAX, SLIM, SIND)
%
%      As `scan(2)', but uses these additional arguments during
%      statistics updates. The global variables `S*' here have the
%      same meaning as global variables `P*' described in function
%      `statp'.
%
%   scan(what)
%
%      Used to scan content of log messages. Possible values of
%      string `what' are:
%
%         NOT IMPLEMENTED YET
%
%
% GLOBAL VARIABLES:
%
%   Affected global variables are `SMIN', `SMAX', `SLIM', `SIND',
%   `SSTAT' and `SSTATS'.
%
%   See function `statp' for a description of these variables.
%
% ------------------------------------------------------------------
%Time:<Last updated on 98/08/12 at 17:36:04 by jaccard@pc34.gfi.uib.no>
%File:</home1/jaccard/data1/codas3/gfi/matlab/matlab50/scan/scan.m>

scanglob;

% ------------------------------------------------------------------
% Build name of index file and check if it should be created
% ------------------------------------------------------------------

if (nargin > 0) & isstr(varargin{1}),
  error('Sorry, not implemented yet!');
end

% Below: scan only for data

INDFILE = newext('log', 'ind', LOGFILE);
if exist(INDFILE) ~= 0,
  mt = fmodtime(strvcat(LOGFILE, INDFILE), YEAR_BASE);
  if mt(1) > mt(2),
	 delete(INDFILE);
  end
end

matfile = newext('log', 'mat', LOGFILE);
if exist(matfile) ~= 0,
  mt = fmodtime(strvcat(LOGFILE, matfile), YEAR_BASE);
  if mt(1) > mt(2),
	 delete(matfile);
  end
end

% Process input parameters:
if nargin == 1,
  % Call without limits
  switch varargin{1}
	 case -1,
		scanpath(0);
		if exist(INDFILE) ~= 0,
		  delete(INDFILE);  
		end
		clear all
		return;
	 case 0,
		scanpath(0);
		clear all
		return;
	 case 2,
		if exist(INDFILE) ~= 0,
		  delete(INDFILE); % to force scanning
		end
		% Clear limits:
		SMIN = [];
		SMAX = [];
		SLIM = [];
		SIND = [];
  end
elseif nargin > 1,
  % Call with limits:
  if exist(INDFILE) ~= 0,
	 delete(INDFILE); % to force scanning
  end
  if exist(matfile) ~= 0,
	 delete(matfile);
  end
  
  SMIN = varargin{1};
  SMAX = varargin{2};
  if nargin > 2,
	 SLIM = varargin{3};
  end
  if nargin > 3,
	 SIND = varargin{4};
  end
end

% Default values are set once the header has been read

% ------------------------------------------------------------------
% Get the header with variable descriptions:
% ------------------------------------------------------------------

fplog = fopen(LOGFILE, 'r');
[hdr, VARNAMES, VARNUMS] = scan_hdr(fplog);
NVARS = length(VARNUMS);
fprintf('\n%s\n', hdr);
fclose(fplog);

if exist(INDFILE) ~= 0,
  % Also get data from previous scanning:
  if exist(matfile) ~= 0,
	 load(matfile);
	 fprintf(2, '%s', SSTATS);
  else
	 fprintf(2, '\n\n\t%s\n\t%s\n\n', ...
	 'No global variables from previous scan. You want', ...
	 'probably to run `scan'' with arguments.');
  end
  return;
end

% ------------------------------------------------------------------
% Initializations:
% ------------------------------------------------------------------

fplog = fopen(LOGFILE, 'r');
fpind = fopen(INDFILE, 'w');

% ------------------------------------------------------------------
% Default values:
% ------------------------------------------------------------------

if isempty(SLIM),
  SLIM = ones(1, NVARS);
end
if isempty(SMIN) | isempty(SMAX),
  SMIN = ones(1, NVARS) * (-Inf);
  SMAX = ones(1, NVARS) * Inf;
  SLIM = zeros(1, NVARS);
end
if isempty(SIND),
  SIND = 1:NVARS;
end

nmin = min([ length(SMIN) length(SMAX) length(SLIM) length(SIND) NVARS ]);
SMIN = SMIN(1:nmin);
SMAX = SMAX(1:nmin);
SLIM = SLIM(1:nmin);
SIND = SIND(1:nmin);

% ------------------------------------------------------------------
% Scan the log file:
% ------------------------------------------------------------------

% Determine indexes to variables needing heading conversions:
icnv_hdg = staticnv('-hdg');

% Initializations:
SSTAT = statinit(NVARS);
ph = zeros(1,length(icnv_hdg));
pn = 0;
pd = ones(1, NVARS) * Inf;
d  = ones(1, NVARS) * Inf;
finished = 0;
n = 0;
i = 0;
NDATA = 0;

while ~feof(fplog) & ~finished,
  
  pd = d;
  pn = n;
  
  % Get next log data:
  [d, pos, n]=next_log(fplog, 'data', [NLINES, n]);
  
  % Check reading status:
  if n < 0,
	 d = pd;
	 pn = n;
	 finished = 1;
  elseif NVARS ~= length(d),
	 error('Number of data does not correspond to header information.');
  else
  
	 % Check information:
	 i = i + n - pn;
	 if (NLINES > 0) & (i >= NLINES),
		i = 0;
		fprintf(2, 'scan - line number: %d\n', n);
	 end

	 % Update index file:
	 fprintf(fpind, '%010d\n', pos); 
	 
	 % Convert headibg to [0, 360):
	 if length(icnv_hdg) > 0,
		d(icnv_hdg) = mod(d(icnv_hdg), 360);
	 end

	 % Check for statistics updates:
	 good = limflag(d', VARNUMS, SMIN, SMAX, SLIM, SIND);
	 bad = find(good ~= 0);
	 if length(bad) > 0,
		d(bad) = NaN;
	 end
	 	 
	 %DEBUG:
	 %fprintf('\n scan:debug:1');
	 %fprintf(' %10.5f', d);
	 %fprintf('\n');
	 
	 % Convert heading relative to previous one:
	 if length(icnv_hdg) > 0,
		d(icnv_hdg) = next_hdg(ph, d(icnv_hdg));
		% Save only good heading data:
		good = find(~isnan( d(icnv_hdg)));
		ph(good) = d(icnv_hdg(good));
	 end

	 %DEBUG:
	 %fprintf('\n scan:debug:2');
	 %fprintf(' %10.5f', d);
	 %fprintf('\n');
	 
	 % Update statistics:
	 NDATA = NDATA + 1;
	 SSTAT = statupd(d', SSTAT, NDATA, '-hdg', icnv_hdg);
	 
  end
  
end

% ------------------------------------------------------------------
% Calculate the statistics:
% ------------------------------------------------------------------

SSTAT = statcalc(SSTAT);

% Convert back heading values to [0, 360):
if length(icnv_hdg) > 0,
  SSTAT(icnv_hdg, [1 2 5]) = mod(SSTAT(icnv_hdg, [1 2 5]), 360);
end

% ------------------------------------------------------------------
% Create the stat string:
% ------------------------------------------------------------------

SSTATS = statstr('S', sprintf('\n RESULTS FROM SCAN:\n\n'));
fprintf('\n%s\n', SSTATS);

% ------------------------------------------------------------------
% Close the files:
% ------------------------------------------------------------------

fclose(fplog);
fclose(fpind);

% ------------------------------------------------------------------
% Save some variables to avoid new scanning:
% ------------------------------------------------------------------

matfile = newext('log', 'mat', LOGFILE);
save(matfile, 'NDATA', 'SSTAT', 'SSTATS');
		
return;
  
