function validateTableIndexBounds(A, aidx)
% validateTableIndexBounds validates that the indices in aidx are within the 
% bounds of table A, throw otherwise. Notice that table checks index
% 2 before index 1.

% Copyright 2018 The MathWorks, Inc.

% If using var-name specifier check names later
if ~iscell(aidx.subs)
    return
end

if numel(aidx.subs)~=2
    error(message('MATLAB:table:NDSubscript'));
end

% Var index must be numeric, logical or char (either ':' or a varname)
idx = aidx.subs{2};
if isnumeric(idx) || parallel.internal.indexing.isColonDescriptor(idx)
    if ~parallel.internal.indexing.isValidIndexVector(idx)
        error(message('MATLAB:badsubscript',getString(message('MATLAB:badsubscriptTextRange'))));
    elseif parallel.internal.indexing.getMaxIndex(idx) > width(A)
        error(message('MATLAB:table:VarIndexOutOfRange'));
    end
    
elseif islogical(idx)
    if numel(idx) > width(A)
        error(message('MATLAB:table:VarIndexOutOfRange'));
    end
    
elseif matlab.internal.datatypes.isText(idx)
    % OK - could be ':' or list of varnames
    
else
    error(message('MATLAB:table:InvalidVarSubscript'));
    
end

% Row index should be numeric, logical or char (':')
idx = aidx.subs{1};
if isnumeric(idx) || parallel.internal.indexing.isColonDescriptor(idx)
    if parallel.internal.indexing.getMaxIndex(idx) > height(A)
        error(message('MATLAB:table:RowIndexOutOfRange'));
    elseif ~parallel.internal.indexing.isValidIndexVector(idx)
        error(message('MATLAB:badsubscript',getString(message('MATLAB:badsubscriptTextRange'))));
    end
    
elseif islogical(idx)
    if numel(idx) > height(A)
        error(message('MATLAB:table:RowIndexOutOfRange'));
    end
    
elseif matlab.bigdata.internal.util.isColonSubscript(idx)
    % OK
    
else
    error(message('MATLAB:table:InvalidRowSubscript'));
    
end
end
