function [k,e] = ellipke(m,tol)
%MATLAB Code Generation Library Function

%   Copyright 1984-2014 The MathWorks, Inc.
%#codegen

eml_invariant(nargin > 0,'MATLAB:minrhs');
eml_invariant(isfloat(m), ...
    'Coder:toolbox:unsupportedClass','ellipke',class(m));
if nargin < 2
    tol = eps(class(m));
end
eml_invariant(isfloat(tol), ...
    'Coder:toolbox:unsupportedClass','ellipke',class(tol));
eml_invariant(isreal(m) && isreal(tol), ...
    'Coder:toolbox:ellipke_4');
eml_invariant(eml_is_const(size(tol)) && isscalar(tol) && isfloat(tol), ...
    'Coder:toolbox:ellipke_5');
if isempty(m)
    k = m;
    e = m;
    return
end
check_m_range(m);
[k,e] = coder.internal.applyScalarFunction(mfilename,zeros('like',m), ...
    @scalar_ellipke,m,cast(tol,'like',m));

%--------------------------------------------------------------------------

function check_m_range(m)
for j = 1:numel(m)
    if m(j) < 0 || m(j) > 1
        coder.internal.error('MATLAB:ellipke:MOutOfRange');
    end
end

%--------------------------------------------------------------------------

function [k,e] = scalar_ellipke(m,tol)
ONE = ones('like',m);
ZERO = zeros('like',m);
TWO = cast(2,'like',m);
k = coder.nullcopy(m);
e = coder.nullcopy(m);
if m == 1
    k = coder.internal.inf('like',m);
    e = ONE;
elseif ~(m >= 0 && m <= 1)
    k(1) = coder.internal.nan('like',m);
    e(1) = coder.internal.nan('like',m);
else
    a0 = ONE;
    b0 = sqrt(ONE - m);
    s0 = m;
    i1 = ZERO; w1 = ONE; a1 = ONE;
    while w1 > tol
        a1 = eml_rdivide(a0 + b0,TWO);
        b1 = sqrt(a0*b0);
        c1 = eml_rdivide(a0 - b0,TWO);
        i1 = i1 + ONE;
        w1 = pow2(i1)*c1*c1;
        s0 = s0 + w1;
        a0 = a1;
        b0 = b1;
    end
    k = eml_rdivide(cast(pi,'like',m),TWO*a1);
    e = k*(ONE - eml_rdivide(s0,TWO));
end
