function T = applyTableTemplate(T, tmpl)
% applyTableTemplate  use a table template to update a distributed table.

%   Copyright 2020 The MathWorks, Inc.

codistr = getCodistributor(T);
if codistr.Dimension==2
    % Variables are spread over workers. Work out which variables we have
    % and subset the template accordingly.
    myPart = codistr.globalIndices(2);
    myTmpl = subsref(tmpl, substruct('()', {':', myPart}));
else
    % Workers all have sections of all variables, so apply the template
    % equally everywhere.
    myTmpl = tmpl;
end

% Copy the properties block, ignoring RowNames/Times. This requires us to
% convert to a struct since you can't remove proprties from a class.
if istimetable(tmpl)
    fieldsToRemove = intersect( ...
        {'RowTimes', 'StartTime', 'SampleRate', 'TimeStep'}, ...
        fieldnames(myTmpl.Properties) );
else
    fieldsToRemove = {'RowNames'};
end
T.Local.Properties = rmfield(struct(myTmpl.Properties), fieldsToRemove);

% Set the metadata
T.Metadata.TableTemplate.set(tmpl);
    
end
