function [V,D,W] = eigHermitianGeneralized(A,B,VECTOR)
%MATLAB Code Generation Private Function

%   Solve the generalized Hermitian eigenvalue problem using the 'CHOL'
%   algorithm, falling back to the 'QZ' algorithm, if necessary.

%   Copyright 2005-2020 The MathWorks, Inc.
%#codegen

coder.internal.prefer_const(VECTOR);
n = coder.internal.indexInt(size(A,1));
infoZERO = zeros('like',coder.internal.lapack.info_t);
if nargout >= 2
    if VECTOR
        [info,D,V] = coder.internal.lapack.xsyhegvd(A,B);
    else
        [info,dt,V] = coder.internal.lapack.xsyhegvd(A,B);
        D = zeros(n,'like',dt);
        if info <= infoZERO
            for k = 1:n
                D(k,k) = dt(k);
            end
        end
    end
    if info <= infoZERO
        if nargout >= 3
            W = V;
        end
    else % fall back to QZ algorithm
        if nargout >= 3
            [info,alpha1,beta1,V,W] = coder.internal.lapack.xggev(A,B);
        else
            [info,alpha1,beta1,V] = coder.internal.lapack.xggev(A,B);
        end
        D = makeD(alpha1,beta1,VECTOR);
    end
else
    if VECTOR
        [info,V] = coder.internal.lapack.xsyhegvd(A,B);
    else
        [info,vt] = coder.internal.lapack.xsyhegvd(A,B);
        V = zeros(n,'like',vt);
        if info <= infoZERO
            for k = 1:n
                V(k,k) = vt(k);
            end
        end
    end
    if info > infoZERO % fall back to QZ algorithm
        [info,alpha1,beta1] = coder.internal.lapack.xggev(A,B);
        V = makeD(alpha1,beta1,VECTOR);
    end
end
if info ~= 0
    if ~coder.setwarningflag
        coder.internal.warning('MATLAB:eig:NoConvergence');
    end
end

%--------------------------------------------------------------------------

function D = makeD(alpha1,beta1,VECTOR)
coder.inline('never');
coder.internal.prefer_const(VECTOR);
if VECTOR
    D = alpha1./beta1;
else
    n = numel(alpha1);
    D = zeros(n,'like',alpha1);
    for k = 1:n
        D(k,k) = alpha1(k)/beta1(k);
    end
end

%--------------------------------------------------------------------------
