function [lbw,ubw] = bandwidth(x,flag)
%MATLAB Code Generation Library Function

%   Copyright 2013-2017 The MathWorks, Inc.
%#codegen

coder.inline('always');
narginchk(1,2);
eml_invariant(ismatrix(x),'MATLAB:bandwidth:inputMustBe2D');
eml_invariant(isfloat(x), ...
    'Coder:toolbox:unsupportedClass',mfilename,class(x));
if nargin == 1
    UPPERONLY = false;
    LOWERONLY = nargout <= 1;
else
    coder.internal.prefer_const(flag);
    eml_invariant(nargout <= 1,'MATLAB:maxlhs');
    UPPERONLY = strcmpi(flag,'upper');
    LOWERONLY = strcmpi(flag,'lower');
    eml_invariant(UPPERONLY || LOWERONLY, ...
        'MATLAB:bandwidth:unknownArgument');
end
if UPPERONLY
    lbw = double(upper_bandwidth(x));
else
    lbw = double(lower_bandwidth(x));
    if ~LOWERONLY
        ubw = double(upper_bandwidth(x));
    end
end

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

function w = lower_bandwidth(x)
m = coder.internal.indexInt(size(x,1));
n = coder.internal.indexInt(size(x,2));
mm1 = m - 1;
w = coder.internal.indexInt(0);
if ~isempty(x)
    for j = 1:n
        for i = m:-1:j+1+w
            if ~(x(i,j) == 0)
                k = i - j;
                if k > w
                    w = k;
                end
                if ~coder.target('HDL')
                    if w >= mm1
                        % It's not possible to find a larger bandwidth from
                        % any of the other columns so return.
                        return
                    else
                        break
                    end
                end
            end
        end
    end
end

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

function w = upper_bandwidth(x)
m = coder.internal.indexInt(size(x,1));
n = coder.internal.indexInt(size(x,2));
nm1 = n - 1;
w = coder.internal.indexInt(0);
if ~isempty(x)
    for j = n:-1:2
        for i = 1:eml_min(m,j-1-w)
            if ~(x(i,j) == 0)
                k = j - i;
                if k > w
                    w = k;
                end
                if ~coder.target('HDL')
                    if w >= nm1
                        % It's not possible to find a larger bandwidth from
                        % any of the other columns so return.
                        return
                    else
                        break
                    end
                end
            end
        end
    end
end

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