function y = convergent(x)
%CONVERGENT MATLAB Code Generation function for rounding towards nearest integer 
%
%   CONVERGENT(A) returns the result of rounding A towards nearest integer -
%   ties round to nearest even integer.

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

eml_allow_mx_inputs; 

if eml_ambiguous_types
    y = coder.ignoreConst(zeros(size(x)));
    return;
end

eml_invariant(isa(x,'numeric'), 'fixed:fi:InvalidInputNotNumeric');
            
y = x;

if isempty(x) || isinteger(x)
elseif isreal(x)
    for k = 1:numel(x)
        y(k) = scalar_convergent(x(k));
    end
else
    for k = 1:numel(x)
        y(k) = complex(scalar_convergent(real(x(k))),scalar_convergent(imag(x(k))));
    end
end

function v = scalar_convergent(u)

f = floor(u);

d = u -f;

if d == .5
    if (f/2 - floor(f/2)) == 0
        v = f;
    else
        v = f+1;
    end
else
    v = nearest(u);
end
