function s = statcalc(st, varargin)
%  1.  NAME
%
%  statcalc - Calculate statistics
%
%  2.  SYNOPSIS
%
%  calc = statcalc(stat, options )
%
%  3.  DESCRIPTION
%
%  This function calculates the statistics saved in the statistics array.
%  See stat(5m) for more information about statistics on unlimited
%  datasets.
%
%  4.  PARAMETERS
%
%     stat
%        Satitistics array (Mx7) with current updated statistics.
%
%  5.  OPTIONS
%
%     '-hdg',  hdg
%        Specifies that non-NaN elements in vector hdgof length M refer
%        to heading data,and should be calculated within 0 and 360.
%
%  6.  RETURNS
%
%     calc
%        Calculated statistics.
%
%  7.  SEE ALSO
%
%  flagdata(3m)stat(5m)statcalc(3m)statinit(3m)statlim(3m)stat_str(3m)statupd(3m)
%
%  8.  AUTHORS
%
%  Pierre Jaccard, Geophysical Institute, University of Bergen, 1999
%

%--- Defaults:
nvars = size(st,1);
hdg = ones(nvars,1) * NaN;

%--- Options:
i = 1;
while i<=length(varargin),
  if isstr(varargin{i}),
	 switch(varargin{i})
		case '-hdg',
		  hdg = varargin{i+1};
		  i = i+2;
		otherwise,
		  error([ 'Option ' varargin{i} ' not implemented' ]);
	 end
  end
end

%--- Indexes:
min_ = 1; max_ = 2; imin_ = 3; imax_ = 4; mn_ = 5; sd_ = 6; n_ = 7;

%--- Calculate statistics:
bad = find(st(:,n_) == 0);
if ~isempty(bad),
  st(bad, mn_) = ones(size(bad)) * NaN;
  st(bad, sd_) = ones(size(bad)) * NaN;
end

good = find(st(:, n_) > 0);
if ~isempty(good),
  st(good,mn_) = st(good,mn_) ./ st(good,n_);
  st(good,sd_) = sqrt( st(good,sd_) ./ st(good,n_) - ...
		st(good,mn_) .* st(good,mn_) );
end

%--- Check for heading data:
ihdg = find(~isnan(hdg));
if ~isempty(ihdg),
  st(ihdg,mn_) = mod(st(ihdg,mn_), 360);
  st(ihdg,sd_) = mod(st(ihdg,sd_), 360);
end

s = st;

return;


