function [xbt]  = xbt_extrap_surface(varargin)
% xbt_extrap_surface - Extrapolate the temp at a given depth to the surface
%
% USAGE: xbt = xbt_extrap_surface(xbt,depth)
% 
% INPUT: 
%   xbt: standard xbt structure array which minimally contains te and de
%   fields.
%   depth: depth in meters from which to extrapolate. 
%
% OUTPUT: xbt: The common xbt structure
%
% DESCRIPTION: Replace all values of temperature (xbt.te) shallower than
% depth with values of temperature at (or nearest to) depth.
%
% AUTHOR: Derrick Snowden
%         NOAA/AOML/PhOD
%         
% DEPENDENCIES:
%
% EXAMPLES:
% >> xbtout = extrap_xbt_surface(xbt, 3.5); 
%   Choose the depth nearest to 3.5m and replace all values of xbt.te at 
%   depths < 3.5m with the value of xbt.te at xbt.de = 3.5 
%

error(nargchk(2,2,nargin));
xbt = varargin{1};
if ~isfield(xbt,'de') | ~isfield(xbt,'te')
    error('XBT structure does not have de, te fields.')
end

% Calculate the index of the depth nearest to the given depth
target_dpth = varargin{2};
for idx_xbt = 1:length(xbt)
    xbt(idx_xbt) = extrapolate(xbt(idx_xbt),target_dpth);
end
    
return % End main routine

function x_out = extrapolate(xbt,target_depth)
% extrapolate: Subfunction to perform extrapolation on one profile
    
x_out = xbt;
[junk,idx] = min(abs(xbt.de-target_depth));

if idx==1
    return
else
    x_out.te(1:idx-1) = xbt.te(idx);
end
return



