function vars = pagefunRedistributeInputsIfNeeded(vars, outCodistr)
% Helper to redistribute all inputs using the codistributor outCodistr, if 
% they aren't already. Replicated inputs can be left alone unless they have 
% multiple pages in the distribution dimension

%   Copyright 2020 The MathWorks, Inc.

for ii=1:numel(vars)
    szInDistDim = size(vars{ii},outCodistr.Dimension);
    if iscodistributed(vars{ii})
        % If the input has size 1 in the distribution dimension then we
        % need to replicate it across workers. If not, just redistribute
        % it.
        if szInDistDim == 1
            % Convert to replicated.
            vars{ii} = gather(vars{ii});
        else
            % Output codistributor is not complete, so just check the dist
            % dim and partition
            thisCodistr = getCodistributor(vars{ii});
            if ~isa(thisCodistr, "codistributor1d") ...
                    || ~isequal(thisCodistr.Dimension, outCodistr.Dimension) ...
                    || ~isequal(thisCodistr.Partition, outCodistr.Partition)
                vars{ii} = redistribute(vars{ii}, outCodistr);
            else
                % This input is already distributed correctly.
            end
        end
        
    elseif szInDistDim > 1
        % Replicated but with multiple pages. Make distributed.
        vars{ii} = codistributed(vars{ii}, outCodistr);
        
    else
        % This input is already replicated correctly
        
    end
end
end % iRedistributeAll