function xnew=boxfilt2(x,n)
%function xnew=boxfilt2(x,n)
%                     box car filter of length n
%                     The difference with boxfilt is that in the vicinity of 
%                       bad points, everything gets NaN
%                     the time base is maintained, and the points
%                     at the beginning and end are returned as their 
%                     original values.

lg=length(x(:));
filt=ones(1:n)/n;
xg=conv(denanize(x(:),1e35),filt);
nbeg=ceil((n+1)/2);
xg=xg(nbeg:nbeg-1+lg);
xg(1:nbeg-1)=ones(1,nbeg-1)*xg(nbeg);
xg(lg-nbeg+2:lg)=ones(1,nbeg-1)*xg(lg-nbeg+1);
xnew=xg;
bad=find(xnew>1e32);

xnew(bad)=ones(bad)*nan;

[imax,jmax]=size(x);
if (imax>1)&(jmax>1)
   xnew=remat(xnew,x);
   for i=0:floor(n/2)-1;
	xnew(1+i,:)=x(1+i,:);
	xnew(imax-i,:)=x(imax-i,:);
   end
end


