function [imaj, clean_data]=var_clean(imjr,window,data)

%    [imaj, clean_data]=var_clean(imjr,npoints,data)
%
%    Determine vector of outliers in data suing a variable
%    edit criteria.
%
%    imjr            edit criteria; outliers have res > imjr*IQR
%    window          number of points in sliding window 
%    data            data vector (or 3-D matrix) to be cleaned

%    imaj            outlier index vector
%    clean_data      data vector (or 3-D matrix) with outliers removed

%    Rosanne Nikolaidis, 23-November-2001

ndata = length(data);
np = floor(window/2);

%compute scaled deviation in window
if ndata <= window
  md_data = median(data); 
  iqr_data = iqr(data);
  for p = 1:ndata
     dev(p,:) = abs(data(p,:) - md_data)./iqr_data;
  end
end
if ndata > window
 for p = 1:ndata
   if p <= np 
      md_data = median(data(1:np,1:3)); 
      iqr_data = iqr(data(1:np,1:3)); 
   elseif p >= (ndata-np)
      md_data = median(data((ndata-np):ndata,1:3)); 
      iqr_data = iqr(data((ndata-np):ndata,1:3)); 
   else 
      md_data = median(data((p-np):(p+np),1:3)); 
      iqr_data = iqr(data((p-np):(p+np),1:3)); 
   end
   dev(p,:) = abs(data(p,:) - md_data)./iqr_data;
 end
end
imaj = find(dev(:,1)>imjr | dev(:,2)>imjr | dev(:,3)>imjr);
clean_data = data; clean_data(imaj,:) = [];
