function out = mean_safe(dat)
%  function out = mean_safe(dat)
%
%  Return the mean of the elements of dat.  Elements that are
%   NaN are ignored in the mean computation
%  If there are no elements that are not NaN, then return NaN
%
%  Computes mean down the matrix columns
%

if(size(dat,1) == 1)
  % Make this a column vector
  dat = dat';
end;

div = sum(~isnan(dat));
bad_samples = find(div == 0);
good_samples = find(div > 0);

%if(sum(div < 1) > 0)
%  error('mean_safe(): not enough valid values');
%end;

elems = find(isnan(dat));
dat(elems) = 0;

if(length(good_samples) > 0)
  out(good_samples) = sum(dat(:,good_samples)) ./ div(good_samples);
end;

out(bad_samples) = NaN;
