function [wastable,x,y,options] = prepareTreeInit(x,y,options,type)
% Perform pre-growing options, including carrying out an initial pass where
% TDigests are created

%   Copyright 2017-2019 The MathWorks, Inc

if ~istall(x)
    error(message('stats:tall:classreg:PredictorsNotTall'));
end

% Disentangle response and weights from the predictors in the table
wastable = gather(isaUnderlying(x,'table'));
if wastable
    sidx = substruct('.', 'Properties');
    prop = subsref(x,sidx);
    vnames = prop.VariableNames;
    
    [x,y,vnames,options.responsename] = internal.stats.bigdata.getVariableFromTable(x,y,vnames,options.responsename);
    [x,options.weights,vnames] = internal.stats.bigdata.getVariableFromTable(x,options.weights,vnames,options.weights);

    % Subset the remaining columns if requested
    if isempty(options.predictornames)
        options.predictornames = vnames;
    else
        [ok,loc] = ismember(options.predictornames, vnames);
        if ~all(ok)
            error(message('stats:classreg:learning:internal:utils:InvalidArg','PredictorName'))
        end
        options.predictornames = vnames(loc);
        sidx = substruct('()', {':',loc});
        x = subsref(x,sidx);
    end
end

% Now that variables are separated from table, validate them
if ~istall(y)
    error(message('stats:tall:classreg:ResponseNotTall'));
end

if type=='r'
    % add check for y
    y = tall.validateType(y,upper(mfilename),{'numeric'},2);
end

if istall(options.weights)
    [x,y,options.weights] = validateSameTallSize(x,y,options.weights);
elseif ~isempty(options.weights)
    error(message('stats:tall:classreg:WeightsNotTall'));
else
    [x,y] = validateSameTallSize(x,y);
end
end