function varargout = stat_str(stat, varargin)
%  1.  NAME
%
%  stat_str - Built string with specified statistics
%
%  2.  SYNOPSIS
%
%  s = statstr(stat, lim, vars, hdr )
%
%  3.  DESCRIPTION
%
%  This Matlab function builds a formatted string containing the current
%  statistics.  When called with a return argument, the limit string is
%  not displayed but only returned.
%
%  4.  PARAMETERS
%
%     stat
%        Statistic array to display.
%
%     lim optional
%        ,Array of limits used for the specified statistics.
%
%     vars
%        Cell array of variable names in the statistics.
%
%     hdr
%        Header string to display on top of the statistics.
%
%  5.  SEE ALSO
%
%  flagdata(3m)stat(5m)statcalc(3m)statinit(3m)statlim(3m)stat_str(3m)statupd(3m)
%
%  6.  AUTHORS
%
%  Pierre Jaccard, Geophysical Institute, University of Bergen, 1999
%

%--- Defaults:
lim = [];
vars = [];
hdr = [];

%--- Arguments:
n = length(varargin);
if n > 0,
  lim = varargin{1};
end
if n > 1,
  vars = varargin{2};
end
if n > 2,
  hdr = varargin{3};
end

%--- Get number of variables:
nvars = size(stat,1);
if ~isempty(vars) & (length(vars) ~= nvars),
  vars = [];
end
if ~isempty(lim) & (size(lim,1) ~= nvars),
  lim = [];
end

%--- Print the header:
str = '';
if ~isempty(hdr),
  str = sprintf('%s%s', str, hdr);
end

%--- Print the limits:
if ~isempty(lim),
  [lim, s] = statlim(1, lim);
  str = sprintf('%s\n%s', str, s);
end

%-- Padding for variable names:
len = 0;
if ~isempty(vars),
  ii =1:nvars;
  for i=ii,
	 if length(vars{i}) > len,
		len = length(vars{i});
	 end
  end
end
pad = '';
ii = 1:(len-4);
for i=ii,
  pad = [ pad ' ' ];
end

%--- Print table header:
str = sprintf('%s\n %s%s', str, 'COL... NAME', pad);
str = sprintf('%s %s', str, 'MIN......... MAX......... IMIN.. IMAX..');
str = sprintf('%s %s\n', str, 'MEAN........ SDEV........ NPTS..');

%--- Print the statistics:
ii = 1:nvars;
for i=ii,
  str = sprintf('%s %6d', str, i);
  if ~isempty(vars),
	 str = sprintf('%s %s', str, vars{i});
	 jj = (length(vars{i})+1):len;
	 for j=jj,
		str = [ str ' ' ];
	 end
  else
	 str = [ str ' ????' ]; 
  end
  str = sprintf('%s %12.5f %12.5f %6d %6d %12.5f %12.5f %6d\n', str, ...
		stat(i,1), stat(i,2), stat(i,3), stat(i,4), ...
		stat(i,5), stat(i,6), stat(i,7));
end
str = sprintf('%s\n\n', str);

if nargout == 0,
  fprintf('%s', str);
else
  varargout{1} = str;
end
  
return;


