function [p,n] = clean(p,factor)

% factor < 5; typical value factor = 0.50;


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

pi   = 1:l;
pm   = ones(1,l); 
done = 0;

dd_m = mean(abs(diff(diff(p))));
if (dd_m < 1.0e-6), dd_m = 1.0e-6;  end
tol = factor*dd_m;

while (done == 0),
 
  pddb = [0 abs(diff(diff(p(pm)))) > tol 0];

  pi_m = pi(pm);

  i_b0 = find(diff([0 pddb]) == 1);

  if (length(i_b0) > 0)
 
     i_b0(i_b0+2 > sum(pm)) = [];

     i_bb = find(pddb(i_b0+1) == 1 & pddb(i_b0+2) == 1);

     i_del = i_b0(i_bb) + 1;

     if (length(i_del) > 0),
         pm(pi_m(i_del)) = zeros(1,length(i_del));
     else
        done = 1;
     end
   else
     done = 1;
   end

   %tol = 2*tol;
 
end

i_bad = find(pm==0);

n = length(i_bad);
if (n > 0),

   pi(i_bad) = [];
   pp = p;
   pp(i_bad) = [];

   tab = [pi' pp'];

   p(i_bad) = table1(tab,i_bad);

end

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

return
