function varargout = qr(A, varargin) %#codegen
%QR   Orthogonal triangular decomposition
%   Refer to the MATLAB QR reference page for more information.
%  
%   See also QR 

%   Copyright 2011-2014 The MathWorks, Inc.

    if nargout > 2 || ...                            % [~,~,E] = qr(...)
            nargin > 1 && ischar(varargin{1}) || ... % qr(A,'vector')
            nargin > 2 && ischar(varargin{2})        % qr(A,B,'vector')
        eml_invariant(false, 'fixed:fi:qrPivotingNotSupported');
    end
    
    if nargin > 1
        if isequal(varargin{1},0)       
            % qr(A,0)
            eml_invariant(false, 'fixed:fi:qrEconomyModeNotSupported');
        else
            % qr(A,B)
            eml_invariant(false, 'fixed:fi:qrLeastSquaresNotSupported');
        end
    end
    
    if ~isreal(A) || ~issigned(A)
        eml_invariant(false, 'fixed:fi:realAndSigned');

    end
    
    if ndims(A) > 2
        eml_invariant(false, 'fixed:fi:inputMustBe2D', 'qr');
    end
    
    eml_invariant(eml_is_const(size(A,1)), 'fixed:fi:firstDimensionMustNotBeVariableSized','qr');
    
    m=size(A,1);
     if m<=1
        wl = coder.const(get(A,'WordLength'));
        Q0 = fi(eye(m),numerictype(true,wl,wl-2));
        R0 = A;
    else
        wl=coder.const(ceil(log2(1.6468 * sqrt(m))) + get(A, 'WordLength'));
        niter=wl-1;
        [Q0,R0] = cordicqr(A, niter, wl);
    end

    if coder.const(eml_fimathislocal(Q0))
        Q = eml_fimathislocal(Q0,false);
    else
        Q = Q0;
    end

    if coder.const(eml_fimathislocal(R0))
        R = eml_fimathislocal(R0,false);
    else
        R = R0;
    end

    if nargout == 2
        varargout{1} = Q;
        varargout{2} = R;
    else
        varargout{1} = R;
    end

end
