function [yf,ff]=runave(f,y,n,p,w,nt)
%
% function [yf,ff]=runave(f,y,n,[p],[w],[nt]);
%
%  where f is the time variable (or frequency)
%        y is a matrix 
%        n is the length of the window in number of pts
%        p  = 0 means do not plot (default)
%           = 1 means plot
%        w  = 0 for default running ave
%           = 1 for window ave 
%       nt  = 0 ignore "f" or time variable
%           = 1 process the time as well
%
% This routine calulates either running averages or a 
% a specified window average assuming time variable is equally spaced
%

% get size of matrix
[nr,nc]=size(y);

% set default method to RUNNING average if not specified
if nargin<5;
  w=0;
  nt=1;
end;

if w==0;
  for j=1:nc;
%   note that we fill the first values with less than full window
    for i=1:length(y);
      yf(i,j)=maxnnan(y(i-min(i-1,floor(n/2)+1):min(i+floor(n/2),length(y)),j));
      if nt==1;ff(i)=maxnnan(f(i-min(i-1,floor(n/2)+1):min(i+floor(n/2),length(y))));end;
    end;
%  
  end;

% average one value per window
elseif w==1;
  for j=1:nc;
    k=0;
    for i=1:n:length(y)-n;
      k=k+1;
      yf(k,j)=maxnnan(y(i:i+n-1,j));
      if nt==0;ff(k)=maxnnan(f(i:i+n-1));end;
    end;
% note: the following line produces a beep when uncommented
%    disp(sprintf('\a'))
    disp(['column ',num2str(j),' done.']);
  end;
end;

% set plotting option to "no plot" if not specified by user
if nargin<4;
  p=0;
end;

% plot if asked for
if p==1;
  if nt==1;
    plot(f,y,'r','linewidth',2);hold on;
    plot(ff,yf,'y','linewidth',2);
  else;
    plot(y,'r','linewidth',2);hold on;
    plot(yf,'y','linewidth',2);
  end;
  legend('orig red','filt yel');
end; 