function [Y, NVArgs, givenY] = parseYAndConstructorNVArgs(factors, extraArgs)
% PARSEYANDCONSTRUCTORNVARGS - Separate Y/Response value from NV args for
% the anova object constructor
%   [Y, NVARGS, GIVENY] = PARSEYANDCONSTRUCTORNVARGS(FACTORS, EXTRAARGS) is
%   used to separate the arguments for the anova object constructor. For
%   the constructor, the following syntaxes are valid:
%       anova(data) - data is a double/single matrix
%       anova(factors, Y)
%       anova(tbl, Y)
%       anova(__, Name, Value, ...) - Supported for all above
%   FACTORS is the first argument given to the constructor, and can be
%   DATA, FACTORS, or TBL in the above signatures. EXTRAARGS is a cell
%   array of arguments preceding FACTORS. It can contain a combination of Y
%   and NV args in the above signature. Y and NVARGS are the result of
%   separating EXTRAARGS into individual pieces based on the possible valid
%   signatures. GIVENY is a logical scalar indicate if Y was given or not.

%   Copyright 2022 The MathWorks, Inc.
numArgs = numel(extraArgs);
if numArgs == 0
    % anova(data) - anova1 syntax
    if ~isfloat(factors)
        % data must be double/single
        error(message('MATLAB:minrhs'));
    else
        Y = [];
        NVArgs = {};
        givenY = false;
    end
else
    % Three syntaxes:
    % anova(data, Name, Value, ...)
    % anova(factors, Y, ...)
    % anova(tbl, Y, ...)
    if istable(factors)
        % anova(tbl, Y, ...)
        Y = extraArgs{1};
        NVArgs = extraArgs(2:end);
        givenY = true;
    elseif isfloat(factors)
        % anova(data, Name1, Val1, ...)
        % or
        % anova(factors, Y, Name1)
        if ischar(extraArgs{1})
            % Either
            % anova(data, Name1, ...)
            % or 
            % anova(factors, Y, ...), but with a bad type for Y
            % Try to determine which option to give a more informative
            % error (if needed)
            nvArgs = anova.getConstructorNVArgs();
            if isrow(extraArgs{1}) && any(startsWith(nvArgs, extraArgs{1}, 'IgnoreCase', true))
                Y = [];
                NVArgs = extraArgs;
                givenY = false;
            else
                Y = extraArgs{1};
                NVArgs = extraArgs(2:end);
                givenY = true;
            end
        else
            % anova(factors, Y)
            Y = extraArgs{1};
            NVArgs = extraArgs(2:end);
            givenY = true;
        end
    else
        % anova(factors, Y, ...)
        Y = extraArgs{1};
        NVArgs = extraArgs(2:end);
        givenY = true;
    end
end
end