function t = renamevars(t, vars, newNames)
%RENAMEVARS Rename variables in a codistributed table or timetable
%   T1 = RENAMEVARS(T1,VARS,NEWNAMES)
%   T2 = RENAMEVARS(T1,VARS,NEWNAMES)
%   
%   
%   See also TABLE, CODISTRIBUTED, RENAMEVARS.
%   


%   Copyright 2019-2020 The MathWorks, Inc.

if nargout == 0
    error(message("MATLAB:table:renamevars:NoLHS"));
end
narginchk(3, 3);

if ~istable(t) && ~istimetable(t)
    error(message("parallel:array:UnsupportedFunction", upper(mfilename), underlyingType(t)));
end

% t must be codistributed, varSpec must not
distributedutil.CodistParser.verifyNonCodistributedInputs({t, vars, newNames});
vars = distributedutil.CodistParser.gatherIfCodistributed(vars);
newNames = distributedutil.CodistParser.gatherIfCodistributed(newNames);
% If t is not codistributed, run replicated.
if ~isa(t, "codistributed")
    t = renamevars(t, vars, newNames);
    return;
end

% We therefore ensure we are distributed in the first dimension before
% trying to process.
t = iEnsureRowDistribution(t);

t_lp = getLocalPart(t);
t_codistr = getCodistributor(t);

% Process the local part, making sure any errors are thrown collectively.
t_lp = distributedutil.syncOnError(@renamevars, t_lp, vars, newNames);

% Now build the output
t = codistributed.pDoBuildFromLocalPart(t_lp, t_codistr);

end

function t = iEnsureRowDistribution(t)
% Ensure that workers have complete rows of the table
codistr = getCodistributor(t);
if ~isa(codistr, "codistributor1d") || codistr.Dimension~=1
    t = redistribute(t, codistributor("1d",1));
end
end
