function [pc, pm]  = cleaner(p, factor, order);
% function [pc, pm]  = cleaner(p, factor, order);
%
%inputs:
%    p       column or row vector, typically a time or space series
%    factor  scalar; threshold is factor times the mean absolute value
%            of the second differences. A good starting value is 2.
%    order   scalar; roughly the length of "runs" of concurrent good data
%            a good starting value is 3 
%  outputs:
%    pm       mask: updated with zeros at newly located glitches.
%    pc       cleaned "p"

   

[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);

end

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

return

