% FIGURE 2.2.2
      function [A,B,PIVOT,NPIVOT] = REDQ(A,M,N,B,ERRLIM)
%                              USE GIVENS ROTATIONS TO REDUCE A
%                              TO ROW ECHELON FORM
      I = 1;
      for L=1:N
%                              USE PIVOT A(I,L) TO KNOCK OUT ELEMENTS
%                              I+1 TO M IN COLUMN L.
         for J=I+1:M
            if (A(J,L) == 0.0)
               continue
            end
            DEN = sqrt(A(I,L)^2+A(J,L)^2);
            C = A(I,L)/DEN;
            S = A(J,L)/DEN;
%                              PREMULTIPLY A BY Qij^T
            for K=L:N
               BIK = C*A(I,K) + S*A(J,K);
               BJK =-S*A(I,K) + C*A(J,K);
               A(I,K) = BIK;
               A(J,K) = BJK;
            end
%                              PREMULTIPLY B BY Qij^T
            BI = C*B(I) + S*B(J);
            BJ =-S*B(I) + C*B(J);
            B(I) = BI;
            B(J) = BJ;
         end
%                              PIVOT A(I,L) IS NONZERO AFTER PROCESSING
%                              COLUMN L--MOVE DOWN TO NEXT ROW, I+1
         if (abs(A(I,L)) <= ERRLIM)
            A(I,L) = 0.0;
         end
         if (A(I,L) ~= 0.0)
            NPIVOT = I;
            PIVOT(NPIVOT) = L;
            I = I+1;
            if (I > M)
               return
            end
         end
      end
 
