function [varName, varIdx] = lookupTableVars(subscript, allVarNames)
% Resolve a table variable subscript into variable names and indices

%   Copyright 2016-2021 The MathWorks, Inc.

% Subscript type conversions - resolve certain types up-front.
if islogical(subscript)
    % Also convert logical to numeric up front
    subscript = find(subscript);
elseif isstring(subscript)
    % Treat string as cellstr to fit in with ismember etc.
    subscript = cellstr(subscript);
elseif isa(subscript, 'matlab.internal.ColonDescriptor')
    % Expand colon vectors
    subscript = subscript(:);
end

if isnumeric(subscript)
    if max(subscript(:)) > numel(allVarNames)
        error(message('MATLAB:table:VarIndexOutOfRange'));
    end
    % Note that we are implicitly relying on the indexing into VariableNames to
    % perform validation of 'subscript' to check for negative / zero
    % / NaN etc. values. But see g1368852 - table allows t.(0) and
    % t.(-1)...
    varName = allVarNames(subscript);
elseif iscellstr(subscript) %#ok<ISCLSTR> strings already converted to cellstr
    varName = subscript;
elseif matlab.bigdata.internal.util.isColonSubscript(subscript)
    varName = allVarNames;
elseif isa(subscript, "pattern")
    varName = allVarNames(matches(allVarNames, subscript));
else
    if ~ischar(subscript)
        error(message('MATLAB:table:InvalidVarSubscript'));
    end
    varName = {subscript};
end

% Ensure we've got varNames as a row
varName = reshape(varName, 1, []);

% Find missing names
[tf, varIdx] = ismember(varName, allVarNames);
if ~all(tf)
    missingNames = varName(~tf);
    error(message('MATLAB:table:UnrecognizedVarName', missingNames{1}));
end
end
