function [varargout] = table( varargin )
%TABLE Build a distributed table from distributed arrays
%   DT = TABLE(D1,D2,...) creates a distributed table DT from distributed
%   arrays D1, D2, ... . All arrays must be distributed and have the same
%   number of rows. The result is always distributed using a 1D distribution
%   scheme over the first dimension.
%   
%   DT = TABLE(..., 'VariableNames', {'name1', ..., 'name_M'}) creates a table
%   that has the specified variable names.  The names need not be valid MATLAB
%   identifiers, but must be unique.
%   
%   DT = TABLE(..., 'DimensionNames', {'dim1', 'dim2'}) creates a table
%   that has the specified dimension names.  The names need not be valid MATLAB
%   identifiers, but must be unique.
%   
%   See also TABLE, DISTRIBUTED.
%   


%   Copyright 2016-2020 The MathWorks, Inc.

numVars = matlab.bigdata.internal.util.countTableVarInputs(varargin);
inputs = varargin;

pnames   = {'VariableNames', 'RowNames', 'DimensionNames'};
dflts    = {             [],         [],               []};
priority = [              0,          0,                0];
[~, ~, ~, supplied] ...
    = matlab.internal.datatypes.parseArgsTabularConstructors(pnames, dflts, priority, ...
                                                             "MATLAB:table:StringParamNameNotSupported", ...
                                                             varargin{numVars+1:end});
if supplied.RowNames
    error(message("parallel:distributed:TableUnsupportedParam"));
end

% If NVP VariableNames is not specified, extract variable names from the
% input and add them as NVP to not lose that information inside the SPMD
% block. If the NVP VariableNames exists, the codistributed version checks
% if the syntax is correct.
if ~supplied.VariableNames
    varNames = arrayfun(@inputname, 1:numVars, "UniformOutput", false);
    empties = cellfun("isempty", varNames);
    if any(empties)
        varNames(empties) = matlab.internal.tabular.defaultVariableNames(find(empties));
    end
    % Make sure default names or names from inputname don't conflict
    varNames = matlab.lang.makeUniqueStrings(varNames, {}, namelengthmax);
    inputs = [inputs, {'VariableNames', varNames}];
end

varargout = cell(1, max(nargout, 1));
[varargout{:}] = distributedutil.distributedSpmdWrapper(@table, inputs{:});

end
