function [multcompArgs, factorInds] = prepareMultcompareArgs(factorNames, factors, nvArgs)
% PREPAREMULTCOMPAREARGS - Prepare arguments for anova object methods that
% rely on multcompare
%   [MULTCOMPAREARGS, FACTORINDS] = PREPAREMULTCOMPAREARGS(FACTORNAMES, FACTORS, NVARGS)
%   takes in FACTORNAMES, a cellstr of the names of all possible factors, FACTORS, 
%   the names of given facotrs, and NVARGS, a cell array (potentially
%   empty) of NV arguments to be given to the multcompare function.
%   MULTCOMPAREARGS is a cell array of NV args to be given to multcompare.
%   It is populated by the values in NVARGS, which are also validated.
%   FACTORINDS is a vector of indices corresponding to where FACTORS appear
%   in FACTORNAMES.

%   Copyright 2022 The MathWorks, Inc.
factorInds = anova.validation.validateFactorsAndConvertToIdx(factors, factorNames);
multcompArgs = {'Dimension', factorInds};

args = {'Alpha', 'Approximate', 'ControlGroup', 'CriticalValueType'};
defs = {.05, numel(factorNames) > 2, 1, 'tukey-kramer'};
[alpha, approx, controlGrp, cvType] = internal.stats.parseArgs(args, defs, nvArgs{:});
multcompArgs = [multcompArgs, {'Alpha', alpha, 'CriticalValueType', cvType}];

% Validate each NV arg
anova.validation.validateAlpha(alpha, 'plotComparisons')
if isfloat(approx)
    approx = logical(approx);
end
validateattributes(approx, {'logical'}, {'scalar'}, 'plotComparisons', 'Approximate')
validateattributes(controlGrp, {'double', 'single'}, {'scalar', 'integer', 'real', 'positive', 'nonnan', 'nonsparse', 'finite'}, ...
    'plotComparisons', 'ControlGroup')
cvType = validatestring(cvType, {'lsd','dunnett', 'tukey-kramer', 'hsd', 'dunn-sidak', 'bonferroni', 'scheffe'},...
    'plotComparisons', 'CriticalValueType');

% Only add dunnet args if dunnet is given
if strcmpi(cvType, 'dunnett')
    multcompArgs = [multcompArgs, {'ControlGroup', controlGrp, 'Approximate', approx}];
end
end