function [dataVarsOut,dvSets] = checkMultDataVariables(T,dataVars,varNamesT,numMethodInput)
%MATLAB Code Generation Library Function

% checkMultDataVariables Validate and figure out sets of mulitple data 
% variable inputs for when the method can accept more than one input.

%   Copyright 2021-2022 The MathWorks, Inc.
%#codegen

coder.internal.prefer_const(dataVars,varNamesT,numMethodInput);
ONE = coder.internal.indexInt(1);

% Each element of dvValues contains the all the variables for one input to
% the method.  It needs to be stored as a cell since we do scalar expansion
dvValues = cell(1,numMethodInput);
coder.unroll();
for ii = ONE:numMethodInput
    dvValues{1,ii} = checkDataVariables(T, dataVars{ii}, 'groupsummary', 'Data');
end
dvValues = coder.const(dvValues);
totalNumDVSets = coder.const(feval('cellfun','prodofsize',dvValues));

% Make sure that all cell elements of dataVars have the same number of
% inputs or are scalars
uniqueNumDVSets = coder.const(feval('unique',totalNumDVSets));
coder.internal.errorIf(numel(uniqueNumDVSets) > 2 || ...
    (numel(uniqueNumDVSets) == 2 && uniqueNumDVSets(1) ~= 1), ...
    'MATLAB:groupsummary:DataVariablesCellNumElements');
numDVSets = max(uniqueNumDVSets);

% Determine the sets of method inputs and store the sets as rows of matrix
% Using a temporary cell array because that can be declared then filled and
% still be constant (unlike a matrix, which is not guaranteed to be
% constant under those conditions)
tmp = cell(size(dvValues));
coder.unroll()
for ii = 1:numMethodInput
    if isscalar(dvValues{1,ii})
        tmp{1,ii} = repmat(dvValues{1,ii},numDVSets,1);
    else
        tmp{1,ii} = dvValues{1,ii};
    end
end
AllDvSets = [tmp{:,:}];

% Uniqueify the sets of method inputs 
uniqueDvSets = coder.const(feval('unique',AllDvSets,'rows','stable'));
numUniqueDVSets = size(uniqueDvSets,1);

% Concatenate the variable names for each set of method inputs
dataVarsOut = cell(1,numUniqueDVSets);
coder.unroll();
for ii = 1:numUniqueDVSets
    tmpDataVar = cell(1,numMethodInput);
    tmpDataVar{1} = varNamesT{uniqueDvSets(ii,1)};
    coder.unroll();
    for jj = 2:numel(tmpDataVar)
        tmpDataVar{jj} = ['_',varNamesT{uniqueDvSets(ii,jj)}];
    end
    dataVarsOut{1,ii} = [tmpDataVar{:}];
end

% Transpose dvSets since groupsummary wants the sets of method inputs
% stored as columns.
dvSets = uniqueDvSets';
dataVarsOut = coder.const(dataVarsOut); % Required to make dataVarsOut be detected as const by calling functions
