function out = sum(x, varargin)
%SUM Sum of elements.
%
%   See also sum.

% Copyright 2016-2018 The MathWorks, Inc.

% We need a specific overload for SUM to handle duration.
FCN_NAME = upper(mfilename);
x = tall.validateType(x, mfilename, {'numeric', 'logical', 'duration', 'char'}, 1);
tall.checkNotTall(FCN_NAME, 1, varargin{:});
% Use the in-memory version to check the arguments
tall.validateSyntax(@sum,[{x},varargin],'DefaultType','double');

[args, flags] = splitArgsAndFlags(varargin{:});

% Flags have already been validated, but we need the precisionFlagCell here
% for computing the output type.
[nanFlagCell, precisionFlagCell] = x.Adaptor.interpretReductionFlags(FCN_NAME, flags);
flags = [nanFlagCell, precisionFlagCell];

reduceFlags = flags;
reduceFlags(any(strcmpi('omitnan',flags))) = {'includenan'};
[out, dimUsed] = aggregateInDim(@sum, x, args, flags, reduceFlags);

out.Adaptor = matlab.bigdata.internal.adaptors.getAdaptorForType(...
    computeSumResultType(x.Adaptor.Class, precisionFlagCell));

if ~isempty(dimUsed)
    out.Adaptor = computeReducedSize(out.Adaptor, x.Adaptor, dimUsed, false);
end

end
