%  PyramidQR  Computes the QR-factorization with Q factored in rotations
%
%    [Grot, Gind,R]=PyramidQR(A)
%    Computes the QR-factorization of A, where the unitary matrix Q
%    is factored in rotations in pyramid shape.
%    See the file DataStructure for more information.
%
%    [Grot, Gind,R]=PyramidQR(A,tol)
%    Only the elements relatively larger than tol will be annihilated, tol is
%    optional and standard set to zero.
%
%    Software written by Raf Vandebril
%    raf.vandebril-at-cs.kuleuven.be
%    Revision Date: August 31, 2010
%



function [Grot,Gind,A]=PyramidQR(A,tol)
  
  % Initialization 
    n=size(A,1);
  
    % Initialization
    if ~exist('tol')
      tol=0;
    end

    
  % Compute the QR-factorization of the matrix $U$.
  cnt=1; % For storing the rotations
  cpos=1; % Counts the position of the rotation in the schemes
  
  
  % Previously there was a built in for not executing rotations, 
  % if a certain threshold was not passed.
  % We have decided to switch this off.
  
  for i=1:n-1
    for j=n-1:-1:i

      % If the difference is too small, do not compute the rotation.
      if (abs(A(j+1,i))/abs(A(j,i)) < tol)
        
        c=1;
        s=0;
        r=A(j,i);
        %XXXXXX
        
       else
      
      % Compute the rotation
      [c,s,r]=GivensR(A(j,i),A(j+1,i));
      G=[c,s; -s', c'];
      
      % Store the corresponding indices
      Grot(1:2,cnt)=[c';-s];
      Gind(cnt,1)=j;
      Gind(cnt,2)=j+1;
      Gind(cnt,3)=cpos;
      
      % Execute this on the matrix
      A(j:j+1,i:n)=G*A(j:j+1,i:n);
      
      cnt=cnt+1; % Always a new column for Grot and Gind
      cpos=cpos+1; % When annihilating a single column, always 1 position
                   % to the left
 
         
         
     end
    end
    cpos=2*i+1; % when starting with a new column to be annihilated,
                 % move an extra position to the right, see the graphical
                 % schemes for understanding this.
  end
  
  % The upper triangular factor returned equals A now.
