function [vars,A] = checkDataVariables(AIn,varsIn,eid,groupDataFlag)
%MATLAB Code Generation Library Function

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

% Note that this version always returns a numerical output for varsOut

coder.internal.prefer_const(varsIn,eid);
if nargin < 4
    groupDataFlag = 'Data';
else
    coder.internal.prefer_const(groupDataFlag);
end

validateattributes(varsIn,{'cell','logical','char','string','numeric'},{});

if isstring(varsIn)
    varsTmp = {char(varsIn)}; % Only string scalars are supported by codegen, so this is equivalent to cellstr(vars);
    % Note that missing strings are not supported by coder
else
    varsTmp = varsIn;
end
% Allow grouping on time variable of timetable
if strcmpi(groupDataFlag,'Group') && istimetable(AIn)
    % Check for time variable extrinsically to speed up code generation
    isTimeVar = coder.const(feval('strcmpi',AIn.Properties.DimensionNames{1},varsTmp));
    anyIsTimeVar = coder.const(feval('any',isTimeVar));
    if anyIsTimeVar
        A = timetable2table(AIn);
    else
        A = AIn;
    end
else
    A = AIn;
end

vars = validateVarsAndGetInd(varsTmp,A.Properties.VariableNames,eid,groupDataFlag);

% We do not sort data variables here. Sorting would be needed for
% non-grouping functions.
end

function varInd = validateVarsAndGetInd(vars,AVarNames,eid,groupDataFlag)
coder.internal.prefer_const(vars,AVarNames,eid,groupDataFlag);
if isempty(vars)
    varInd = zeros(1,0);
    return
end
if iscell(vars) || ischar(vars)
    [~, varInd] = coder.const(@feval,'ismember',vars,AVarNames);
    ISVALID = coder.const(feval('all',varInd ~= 0));
    coder.internal.assert(ISVALID, ['MATLAB:',eid,':',groupDataFlag,'VariablesTableSubscript']);
elseif isnumeric(vars)
    % Validate numeric vars
    % Using ISVALID0, ISVALID1, etc. to make sure that coder treats them as const
    varInd = vars(:);
    ISVALID0 = coder.const(feval('all', varInd > 0));
    FIXVARIND = coder.const(feval('fix', varInd)); % Calling fix extrinsically so it doesn't have to be constant folded
    ISVALID1 = ISVALID0 && coder.const(feval('all', varInd == FIXVARIND)); % All values of varInd are integers
    ISVALID2 = ISVALID1 && coder.const(feval('all', varInd <= numel(AVarNames)));
    coder.internal.assert(ISVALID2, ['MATLAB:',eid,':',groupDataFlag,'VariablesTableSubscript']);
else % vars is logical
    coder.internal.assert(numel(vars) <= numel(AVarNames), ['MATLAB:',eid,':',groupDataFlag,'VariablesTableSubscript']);
    varInd = coder.const(feval('find',vars));
end
end