function [pc, pm]  = cleaner(p, factor, order);
% CLEANER - interpolates over spikes in data series
%
% function [pc, pm]  = cleaner(p, factor, order);
%
% p is the input vector, factor is a positive 
% real number (try 2) that is the tolerance of 
% the mean absolute value of the second difference, 
% tested in runs of 3, and order is an integer number 
% that tells roughly how many  offset but smooth data 
% points to interpolate over (1 for spikes and more for 
% longer glitches).  pc is the cleaned vector and 
% pm is a mask that shows which points were 
% linearly interpolated.  Calls glitch.m 
% 
% stolen from Eric Firing Jan 18 1996

%	$Revision: 1.3 $
%	$Date: 2008/01/19 19:43:41 $
%	$Id: cleaner.m,v 1.3 2008/01/19 19:43:41 duncombe Exp duncombe $
% 

[nr, nc] = size(p);
np = max(nr, nc);
if np == nr,
   is_col = 1;
   p = p(:)';
else
   is_col = 0;
end

pm = ~isnan(p);
pi = 1:np;

for ii = 1:order
   for jj = 1:ii
      irange = jj:ii:np;
      pm(irange) = glitch(p(irange), factor, pm(irange));
   end
end

pc = p;


i_bad = find(~pm);

if (~isempty(i_bad)),

   %pc(i_bad) = table1([pi(pm).' p(pm).'], i_bad);
   pc(i_bad) = interp1(pi(pm),p(pm),i_bad);%JH edit. table1 isn't used in
   %Matlab anymore.  This appears to produce the same result.
   
end

if is_col == 1,
   pc = pc(:);
end

return



