function [factorInds, factors] = validateFactorsAndConvertToIdx(factors, allFactors, analysisName)
%VALIDATEFACTORSANDCONVERTTOIDX - Verify a set of factor names and convert
%them to a set of indices
%   [FACTORINDS, FACTORS] = VALIDATEFACTORSANDCONVERTTOIDX(FACTORS, ALLFACTORS)
%   takes in a set of names of factors FACTORS and a cellstr of all known
%   factor names ALLFACTORS. It verifies that FACTORS is a subset of
%   ALLFACTORS, and returns, in FACTORINDS, the indices of where FACTORS is 
%   in ALLFACTORS. It also returns the original FACTORS converted to a
%   cellstr.

%   Copyright 2022-2023 The MathWorks, Inc.
if nargin < 3
    analysisName = 'anova';
end

factors = convertStringsToChars(factors);
if ~isempty(factors)
    if ~(ischar(factors) || iscellstr(factors))
        error(message('stats:hypothesis:anova:BadFactorsType'));
    end
    if ischar(factors)
        factors = cellstr(factors);
    end
    anova.validation.verifyFactorNamesInTable(factors, allFactors);
else
    if (numel(allFactors) > 1)
        % factors is required for 2+-way ANOVA
        error(message(['stats:hypothesis:' lower(analysisName) ':FactorsRequired']));
    else
        factors = allFactors;
    end
end

% Convert from named factor to indices of allFactors
[~, factorInds] = ismember(factors, allFactors);
end