function varargout = rmean(a,n)
%  1.  NAME
%
%  rmean - Calculate running mean values from a vector
%
%  2.  SYNOPSIS
%
%  [b, good] = rmean a(n )
%
%  3.  DESCRIPTION
%
%  Calculates the mean value for each set of n consecutive elements in a
%  , moving along the elements of a. Vector a may have NaN values.
%  Calling with n less than one, the function will return the input array
%  with NaN values removed and the mask to these values.
%
%  4.  PARAMETERS
%
%     a  Vector of length N.
%
%     n  Number of subsequent elements to take into account for
%        calculating mean values.
%
%  5.  RETURNS
%
%     b  Vector of length (N-2). Element b(i) is the mean value of the
%        elements of a,starting from a(i).
%
%     good optional
%        Indexes to the elements of a that were used.
%
%  6.  AUTHORS
%
%  Pierre Jaccard, Geophysical Institute, University of Bergen, 1999
%

%--- Get index to good values:
good = find(~isnan(a));
aa = a(good);

%--- Get a row vector:
if size(aa,1) == 1,
	aa = aa';
end

if n > 2,
  %--- Build indexes to calculate mean values:
  ii = 1:n;
  nn = length(aa) - n;
  mm = size(i,1);
  jj = repmat(ii, nn, mm);
  kk = 1:nn;
  kk = kk-1;
  kk = kk';
  nn = size(kk,2);
  mm = n;
  kk = repmat(kk, nn, mm);
  jj = jj+kk;
  
  %--- Calculate mean values:
  b = [];
  ii = 1:size(jj,1);
  for i=ii,
    b(i) = mean(aa(jj(i,:)));
  end
else
  b = aa;
end
  
if nargout > 0,
	varargout{1} = b;
end
if nargout > 1,
	varargout{2} = good;
end
	
return;

