function [genPolyDec, numBits] = commblkCheckPolynomial(genPoly)
%COMMBLKCHECKPOLYNOMIAL function for CRC generator and CRC
% syndrome detector blocks for Polynomial parameter checking.

%   Copyright 1996-2021 The MathWorks, Inc.

% Check the Generator Polynomial parameter
if ~( isvector(genPoly) && ~isempty(genPoly) )
    error(message('comm:commblkcrcgen:GenPolyNotVector'));
end

if min(genPoly) < 0
    error(message('comm:commblkcrcgen:InvalidGenPoly'));
elseif any(genPoly~=1 & genPoly~=0)  % Positive powers case
    % Check for repeated values
    if length(unique(genPoly)) ~= length(genPoly) 
        error(message('comm:commblkcrcgen:InvalidGenPoly'));
    end
    % Check for sorted descending order.  Sort on a column vector.
    if any(sort(genPoly(:),1,'descend') ~= genPoly(:))
        error(message('comm:commblkcrcgen:InvalidGenPoly'));
    end
    % Convert to binary vector representation
    len = max(genPoly)+1;
    tmp = zeros(1, len);
    tmp(len-genPoly) = 1;
    genPoly = tmp;
end

if ((genPoly(1) == 0) || (genPoly(end) == 0))
    error(message('comm:commblkcrcgen:InvalidGenPoly'));
end

% Check the Degree of polynomial
numBits = length(genPoly)-1;
if numBits > 32
    error(message('comm:commblkcrcgen:InvalidGenPolyDegree'));
end

% Convert to decimal value
if ( isscalar(genPoly) && (genPoly == 1) )
    genPolyDec = 0;     % numBits = 0
else
    truncGenPoly = genPoly(2:end);
    genPolyDec = bit2int(truncGenPoly(:),numBits); % without the leading implicit bit
end
