function varargout = mode(X, varargin)
%MODE   Mode, or most frequent value in a sample.
%   M = MODE(X)
%   [M,F] = MODE(X)
%   [...] = MODE(X,DIM)
%   Limitations:
%   Codistributed table and timetable inputs are not supported.
%   The third output is not supported for codistributed data.
%   
%   Example:
%   spmd
%       % Random integers normally distributed around 0
%       y = fix(codistributed.randn(10000,10));
%       % Shift the center to 1..10
%       y = bsxfun(@plus, y, 1:10);
%       % Mode for each column is now 1:10
%       m = mode(y)
%   end
%   
%   See also MODE, MEDIAN, CODISTRIBUTED, CODISTRIBUTED/MEAN.


%   Copyright 2014-2022 The MathWorks, Inc.

% 3rd output would be a distributed cell of distributed vectors which we
% can't support right now. Throw a reasonable error.
if nargout>2
    error(message("parallel:distributed:ModeThirdOutput"));
end

% We don't yet support tabular maths for MODE
if istabular(X)
    error(message("parallel:distributed:TabularMathUnsupported", "MODE"))
end

% Make sure only 1st input is distributed
if nargin>1
    [varargin{:}] = gather(varargin{:});
end

% try...catch prevents error being reported by internal
try
    [varargout{1:nargout}] = parallel.internal.flowthrough.mode(X, varargin{:});
catch ME
    throw(ME);
end
