function asCat = checkAsCat(isCat,asCat,nvars,haveDataset,VarNames)
%checkAsCat Decide which variables are categorical.

% Inputs:
%   isCat is a boolean vector of variables whos type must be categorical
%   asCat is indices of variables specified to be treated as categorical
%   nvars is the number of variables
%   haveDataset indicates we have a dataset or table
%   VarNames is the set of variable names

%   Copyright 2016 The MathWorks, Inc.

% Decide which variables are categorical
[isVarIndices,isInt] = internal.stats.isIntegerVals(asCat,1,nvars);
if isVarIndices && isvector(asCat) % var indices
    where = asCat;
    asCat = false(nvars,1);
    asCat(where) = true;
elseif isInt && isvector(asCat)
    error(message('stats:classreg:regr:FitObject:BadAsCategoricalIndices'));
elseif internal.stats.isStrings(asCat) % variable names
    [tf,where] = ismember(asCat,VarNames);
    if ~all(tf)
        error(message('stats:classreg:regr:FitObject:BadAsCategoricalNames'));
    end
    asCat = false(nvars,1);
    asCat(where) = true;
elseif islogical(asCat) && isvector(asCat)
    if (haveDataset && length(asCat)~=nvars) || ...
            (~haveDataset && length(asCat)~=nvars-1)
        error(message('stats:classreg:regr:FitObject:BadAsCategoricalLength'));
    end
    if ~haveDataset
        asCat = [asCat(:)',false]; % include response as well
    end
else
    error(message('stats:classreg:regr:FitObject:BadAsCategoricalType'));
end
asCat = asCat(:)';
asCat = (isCat | asCat);
end