function t = timetable2table(tt,varargin)
%TIMETABLE2TABLE Convert codistributed timetable to codistributed table.
%   T = TABLE2TIMETABLE(TT)
%   T = TABLE2TIMETABLE(TT,'ConvertRowTimes',TF)
%   
%   See also TIMETABLE2TABLE, codistributed.
%   


%   Copyright 2018-2022 The MathWorks, Inc.

if ~istimetable(tt)
    error(message('MATLAB:timetable2table:NonTimetable'));
end

pnames = {'ConvertRowTimes'};
dflts =  {            true };
convertRowTimes = matlab.internal.datatypes.parseArgs(pnames, dflts, varargin{:});

% Tables and timetables are always 1D distribution in first or second
% dimension.
codistr = getCodistributor(tt);
part = codistr.Partition;
dim = codistr.Dimension;
inSz = size(tt);
lp = getLocalPart(tt);
assert(isa(codistr, 'codistributor1d') && codistr.Dimension<=2, ...
       "Tabular distributed arrays should always be 1D distribution.");

if convertRowTimes
    outSz = inSz + [0 1];
else
    outSz = inSz;
end

if codistr.Dimension==1
    % Each worker has all columns, and the conversion is "slicewise" (i.e.
    % independent on each worker).
    outLP = timetable2table(lp, 'ConvertRowTimes', convertRowTimes);
    
else
    % Each worker has a few columns. If requested, the first worker with
    % data should add the time column and the rest should ignore it.
    firstWorker = find(part>0, 1, 'first');
    if isempty(firstWorker)
        firstWorker = 1;
    end
    if spmdIndex==firstWorker
        outLP = timetable2table(lp, 'ConvertRowTimes', convertRowTimes);
    else
        outLP = timetable2table(lp, 'ConvertRowTimes', false);
    end
    
    % Maybe adjust partitioning
    part(firstWorker) = part(firstWorker) + convertRowTimes;
    
end

outCodistr = codistributor1d(dim, part, outSz);
t = codistributed.pDoBuildFromLocalPart(outLP, outCodistr);

end
