function [kc,kg] = kckg(v,p)
%KCKG  Wavenumbers selected by a given velocity
%   [KC,KG] = KCKG(V) gives the capillary and gravity wavenumbers selected
%   by a given velocity V (in m/s). Zeros are returned if V is lower than
%   the critical velocity.
%
%   [KC,KG] = KCKG(V,P) also specifies the parameter P for the dispersion
%   relation. If the water depth (p.h0) is infinite, the second order
%   polynomial is solved. If the water depth is finite, an approximate
%   numerical solution is found using FZERO.
%
%   See also WAVE_PARAMETER, OMEGA, KFROMW

%   F. Moisy, moisy_at_fast.u-psud.fr
%   Revision: 1.21,  Date: 2010/04/28

% 2007/10/25: v1.00
% 2008/07/02: v1.10, finite depth added
% 2010/04/20: v1.20, use wave_parameter
% 2010/04/28: v1.21, cosmetics

error(nargchk(1,2,nargin));

if nargin==1
    p=[];
end

p = wave_parameter(p);   % fills the default values in p

kc = zeros(1,numel(v));  % pre-allocate
kg = kc;

if isinf(p.h0)
    X = v.^2 * p.rho / p.gamma;
    D = X.^2 - 4*p.rho*p.g/p.gamma;

    for i=1:numel(v)
        if D(i)>0
            kc(i) = (X(i) + sqrt(D(i)))/2;
            kg(i) = (X(i) - sqrt(D(i)))/2;
        end
    end
else
    %first find the approximate solution for deep water:
    [kcinf,kginf]=kckg(v,wave_parameter(p,'h0',inf));

    %second, search for numerical zero, starting from the deep-water
    %solution:
    for i=1:numel(v)
        %if mod(i,100), v(i), end
        if kcinf(i)>0
            kc(i) = fzero(@(k) cminusu(k,v(i),p), kcinf(i));
        end
        if kginf(i)>0
            kg(i) = fzero(@(k) cminusu(k,v(i),p), kginf(i));
        end
    end
end

% subfunction "C minus U" from which zero is searched
% (C is the phase velocity and U the stream velocity)
    function diff=cminusu(k,u,p)
        [w,c]=omega(k,p);  %#ok
        diff=c-u;
    end

end