function [v, mask] = flag_bad(v, sig_max)
%  1.  NAME
%
%  flag_bad - Flag data as bad in a vector
%
%  2.  SYNOPSIS
%
%  [v, mask] = flag_bad(v, sig_max )
%
%  3.  DESCRIPTION
%
%  Calculate the mean value of the non-NaN in a vector, standard
%  deviation and residuals for each element. An element is considered as
%  bad if the absolute value of its residual is larger than a certain
%  threshold value. The latter is determined as a factor times the
%  standard deviation.
%
%  This function can be used to detect vector elements that are much more
%  different than the other ones.
%
%  4.  PARAMETERS
%
%     v  Data vector.
%
%     sig_max
%        Factor used to calculate the threshold value. A typical value is
%        2.5.
%
%  5.  RETURNS
%
%     v  Vector with bad elements replaced by NaN.
%
%     mask
%        Vector of ones or zeros,zeros specifying elements in v that have
%        been flagged as bad,or that were already set to NaN on input.
%
%  6.  AUTHORS
%
%  Pierre Jaccard, Geophysical Institute, University of Bergen, 1999
%

%--- Transform v in a row vector:
transpose = 0;
if size(v,1) < size(v,2),
	v = v';
	transpose = 1;
end

%--- Initialize the mask
good = ones(size(v));
prev = zeros(size(v));
ib = find(isnan(v));
good(ib) = 0;

%--- Loop until all data have been flagged:
while find((prev==good) == 0),
	
	%--- Get index of good data:
	ig = find(~isnan(v));
	rs = NaN * ones(size(v));
	
	%--- Calculate statistics:
	if length(ig)> 0,
		mn = mean(v(ig));
		st = std(v(ig));
		rs(ig) = v(ig) - mn;
	end
	
	%--- Update mask:
	prev = good;
	good = good & ( abs(rs) < st*sig_max );
	
	%--- Update the vector:
	ib = find(good == 0);
	v(ib) = NaN;
end
mask = good;

%--- Reshape the vector:
if transpose,
	v = v';
	mask = good';
end

return;







