function [ di wi ti ] = depth_of_parameter( varargin )

% depth__parameter finds the depth at which param_in.value equals
% param_target.
%
% The routine assumes that you have run yoyo_classifier, and expects the
% outputs of that function as inputs here.
%
% Input arguments:
% (param_in, param_target, depth, time, yoyo_number, whichway, delta_time, start_depth)
%  
%   param_in = parameter structure with .value and .time to be analyzed
%   param_target = parameter value for which one wishes to the know the depth
%   depth, time, yoyo_number, and whichway are outputs of yoyo_classifier
%   delta_time = optional shift in time
%

% Get arguments
param_in = varargin{1};
param_target = double(varargin{2});

depth = double(varargin{3});
time = double(varargin{4});
yoyo_number = (varargin{5});
whichway = double(varargin{6});

if nargin == 7
    delta_time = varargin{7};
else
    delta_time = 0;
end;

%  Make sure parameter time is single valued!  Amazing I have to check for this...
ok = [1 find(diff(param_in.time) > 0)+1];

%  Interpolate parameter to depth time base
param = interp1(param_in.time(ok), double(param_in.value(ok)), time+delta_time);

max_n = yoyo_number(length(yoyo_number));

% Generic search for shallowest depth at which parameter has desired value
param_target = 6000;
param_frac = 0.1;
for i = 1:max_n
    j_sub = find((abs(param - param_target) < param_target*param_frac) & (yoyo_number == i));
    ni(i) = length(j_sub);
    
    p = polyfit(param(j_sub)-param_target, depth(j_sub), 1);
    
    di(i) = p(2);
    wi(i) = mean(whichway(j_sub));
    ii(i) = i;
end;

hold off;
plot(ii(wi > 0.5), di(wi > 0.5), '.r');
hold on;
plot(ii(wi < -0.5), di(wi < -0.5), '.b');
plot(ii, di, 'g');
hold off;
