function z = cumtrapz(x,y,dim)
%MATLAB Code Generation Library Function

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

eml_invariant(nargin > 0, ...
    'MATLAB:minrhs');
eml_invariant(isa(x,'float'), ...
    'Coder:toolbox:unsupportedClass','cumtrapz',class(x));
if nargin == 3
    z = trapwork(true,x,y,dim);
elseif nargin == 2
    if eml_is_const(size(y)) && isscalar(y) % cumtrapz(x,y) corresponds to cumtrapz(y,dim)
        z = trapwork(false,zeros(0,class(x)),x,y);
    else
        z = trapwork(true,x,y);
    end
else
    z = trapwork(false,zeros(0,class(x)),x);
end

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

function z = trapwork(givenx,x,y,dim)
coder.inline('always');
eml_invariant(isa(y,'float') || islogical(y), ...
    'Coder:toolbox:unsupportedClass','cumtrapz',class(y));
ONE = ones(coder.internal.indexIntClass);
if nargin < 4
    dim = coder.internal.nonSingletonDim(y);
else
    coder.internal.prefer_const(dim);
    coder.internal.assertValidDim(dim);
end
vlen = size(y,dim);
if givenx
    % In this case DIM must be a constant when not variable sizing.
    if nargin < 4
        eml_invariant(numel(x) == vlen, ...
            'Coder:MATLAB:cumtrapz_LengthXMismatchY');
    else
        eml_invariant(numel(x) == vlen, ...
            'Coder:MATLAB:cumtrapz_LengthXMismatchYDIM');
    end
    for i = ONE:coder.internal.indexMinus(vlen,1)
        x(i) = x(i+1) - x(i);
    end
end
zzero = coder.internal.scalarEg(x,y);
z = coder.nullcopy(eml_expand(zzero,size(y)));
if ~isempty(y)
    vstride = coder.internal.prodsize(y,'below',dim);
    npages = coder.internal.prodsize(y,'above',dim);
    ZERO = zeros(coder.internal.indexIntClass);
    iyz = ZERO;
    for i = 1:npages
        iystart = iyz;
        for j = 1:vstride
            iystart = coder.internal.indexPlus(iystart,1);
            s = zzero;
            ix = ZERO;
            iyz = iystart;
            ylast = y(iyz);
            z(iyz) = 0;
            for k = 2:vlen
                iyz = coder.internal.indexPlus(iyz,vstride);
                if isempty(x)
                    s = s + coder.internal.div(ylast+y(iyz),2);
                else
                    ix = coder.internal.indexPlus(ix,1);
                    s = s + x(ix)*coder.internal.div(ylast+y(iyz),2);
                end
                ylast = y(iyz);
                z(iyz) = s;
            end
        end
    end
end

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