function zz=despike(x,z)
% This m-function file reads raw XBT data and despikes it.
% Input consists of raw XBT data, and output as follows :
%
%        Column 1        Column 2
%        (Depth)       (Temperature)
%     _______________________________
%           5              t1
%          10              t2 ...
%
% Gradient criteria comes from dt/dp.
% Gradients large than GC will be flagged and removed.
%
% Daniel Torres, WHOI, 5/94

%%%%%%% USER DEFINABLE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

GC = .5;		% Gradient criteria for flagging spikes

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Create 3 column data from 2 for compatibility
x(:,3)=x(:,2);
x(:,2)=x(:,1);

% Cutoff data at 830 meters.
%ix=find(x(:,2)<831)+1;    % For funny data set
ix=find(x(:,2)<z);

% Calculate derivative of temperature with respect to pressure.
xx=deriv(x(ix,:));

% Find indices points which meet the gradient criteria of .5.

iflag=9999999.9;
count=0;
stats=[count length(x)];

while iflag - length(xx) > .4
   iflag=length(xx);
   ix=find(abs(xx(:,4))< GC);
   xx=xx(ix,1:3);
   xx=deriv(xx);
   count=count+1;
   stats=[stats;[count iflag]];
end

%  This next section interpolates de-spiked XBT pressure and 
%  temperature data onto a five meter grid. The algorithm consists of
%  finding the 2 points closest to each multiple of 5 on the pressure
%  scale and interpolating to get a point at the 5 meter intervals. The 
%  values are weighted according to their proximity to the grid point.

for inc=5:5:z
    fmx=find(xx(:,2)<inc);
    fmn=find(xx(:,2)>inc);
    if length(fmx)<1
       fmx=find(xx(:,2)<inc+5);
       if length(fmx)>=1
          pp=xx(min(fmx),3);
          zz=[zz;[inc pp]];
       end
    elseif length(fmn)<1
       fmn=find(xx(:,2)>inc-5);
       if length(fmn)>=1
          pp=xx(max(fmn),3);
          zz=[zz;[inc pp]];
       end
    else
       imax=max(fmx);
       imin=min(fmn);
       pp=((xx(imax,3).*(xx(imin,2)-inc))+(xx(imin,3).* ...
       (inc-xx(imax,2))))./(xx(imin,2)-xx(imax,2));
       zz=[zz;[inc pp]];
    end
end
