%  EigCRfdc Compute eigenvalues of compressed represented matrix,
%    with fixed direction changes
%
%
%    [ev]=EigCRfdc(Grot,Gind,R,lm,rm,dir)
%    - Starts from the QR-factorization of a matrix A=QR, where Q is
%    factored in rotations specified by Grot and Gind.
%    Important is that Grot and Gind represent a compressed unitary
%    matrix, constructed by n-1 rotations! 
%    - Ordering: the sequence of rotations needs to be ordered from
%    top to bottom, first the rotation acting on 1,2, then on 2,3,
%    ... (automatically done in the routine, but time consuming in
%    case they are already in good format).
%    - The output contains the eigenvalues of A.
%    - chdir determines after how many steps the direction of the
%    trailing rotation will change again, 0 means never change.
%    The starting direction of the rotation is identical to the
%    direction imposed by the trailing two rotations.
%
%    lm and rm define the direction of the final rotation.
%    lm is the number of iterations to be chosen on the left, after which
%    we switch to the right. 
%    rm steps are performed on the right, after which we switch to the
%    left.
%    sd defines the starting direction
%    dir=1 -> starts on the left (Hessenberg chasing)
%    dir=0 -> starts on the right (Hessenberg-like chasing)
%    E.G EigCRfdc(...,1,0,1), only hessenberg steps
%        EigCRfdc(...,1,0,0), only hessenberg steps (left not allowed
%        since it is 0)
%        EigCRfdc(...,0,1,0), only hessenberg-like steps
%        EigCRfdc(...,0,1,1), only hessenberg-like steps (right not
%        allowed since it is 0)
%
%    [ev,niter]=EigCRfdc(Grot,Gind,R,lm,rm,dir)
%    niter contains the number of iterations before deflation could
%    be applied.
%
%    Software written by Raf Vandebril
%    raf.vandebril-at-cs.kuleuven.be
%    Revision Date: September 17, 2010
%

function [ev,diter]=EigCRfdc(Grot,Gind,R,lm,rm,dir)


  % Initialization
  n=size(R,1);
  ev=[];
  
  % For QR-algorithms some parameters need to be set
  cutsize=4; % If the block is smaller than cutsize it is no further used
      % in the iteration procedure
  maxiter=20; % The maximumnumber of iterations before we take an arbitrary
      % shift to proceed.

  % Two criterions for checking deflation are possible
  % either check the relative criterion involving elements from the
  % upper triangular R, or base the deflation simply on the
  % rotations
  tol=10^(-16); % relative deflation tolerance
  giv_tol=10^(-14); % tolerance for rotations
  cutting_crit=10^(-16); % tolerance for zero subdiagonals
  deflation_type='g'; % deflation based on Givens transformations
  % deflation_type='r'; % relative deflation taking values in R in 
                        % consideration
                        % -> not implemented   
                        
 % The different subproblems are identified with two integers p, q,
 % where p denotes the startindex of the subblock and q denotes
 % the endindex of the subblock. 
 p=1; q=n;
 
 % To store were deflation has ocured we have a vector of lenght n-1
 % which is a boolean corresponding with each subdiagonal element.
 deflag(1:n-1)=1; 
 
 % To store the total number of iterations before deflation at a
 % specific spot ocured we maintain another vector keeping the total
 % number of iterations for setting the corresponding diagonal
 % element to zero
 diter(1:n)=0;
 % diter(n) counts the iterations exceeding the maxiter
 

 % Assign the variables before starting
 % defcrit=cutting_crit;
 numiter=0;

    
 % The QR-iteration procedure here assumes the rotations are ordered
 % in Grot and Gind, so that the top rotation is the first in the
 % list --> If not, uncomment the next lines to provide this ordering
 [SG,I]=sort(Gind(:,1)); % the first column corresponds to the
                         % first row the rotation acts on
 Gind=Gind(I,:); % Rorder the index storage
 Grot=Grot(:,I); % Rorder the rotations themselves

 % The starting direction for the last annihilation equals dir
 % dir=1, means Hessenberg step
 % dir=0, means Hessenberg like step
 % Assign the necessary values for correct counting
 lcnt=0; % Counter for the left number of final rotations
 rcnt=0; % Counter for the right number of final rotations
 % To start correctly the following test is needed
 if (dir==0) 
   lcnt=lm; % Set to the max, so we start immediately on the right
 end
 
    
 % Start iterating untill all blocks are smaller then cutsize
 while (q-p+1 > cutsize)
 
   % This is to determine the annihilation on the right or on the left
   % We start annihilating on sd
   if (lcnt<lm)
     % annihilation on the left (hessenberg)
     dir=1;
     lcnt=lcnt+1;
   elseif (rcnt<rm)
     % annihilation on the right (hessenberg-like)
     dir=0;
     rcnt=rcnt+1;
   elseif (lm==0) 
     % Still continues on the right (this is to overcome problems when
     % one only wants to execute Hessenberg-like steps)
     dir=0;
   else
     % restart annihilation on the left (hessenberg)
     rcnt=0;
     dir=1;
     lcnt=1;
   end
   
   %disp('annihilation steps')
   %fprintf('%d ',dir)
   %pause
   
   % To track down convergence, and iteration count
   converged=false;
   numiter=numiter+1;
   
   % Perform a QR-step
   qrstep
      
   % Check deflation after the qr-step, if yes:
   % boolean converged is set true
   deflate
        
   if (converged)
     % Before arranging everything for the next iterate, we insist on
     % putting the Rotation to the identity matrix
     % Possible is that Grot(2)=epsilon, but Grot(1) equals alpha, with
     % |alpha|=1, update the matrix R, to overcome this problem
     if ~(abs(Grot(1,idef)-1) < giv_tol)
       % This means that Grot is not within the tolerance close to 1
       % Both diagonal elements will be removed
       % For the top alpha (first diagonal element), check if idef equals
       % 1
       % The element in position (idef+1,idef) equals zero
       if (idef==1)
         % We can apply alpha on either column or row, we take column
         % (uses less operations)
         R(1,1)=Grot(1,idef)*R(1,1);
       elseif (Gind(idef-1,3) < Gind(idef,3))
         % The previous rotation is positioned left, apply hence on the
         % row ranging from idef to q
         R(idef,idef:q)=Grot(1,idef)*R(idef,idef:q);           
       else
         % The previous rotation is positioned right, apply hence on
         % the column
         R(p:idef,idef)=Grot(1,idef)*R(p:idef,idef);
       end
       
       % For the bottom alpha (second diag elem.), check if idef equals
       % n-1
       if (idef==(n-1))
         % The rotation is positioned in the trailing sequence,
         % Application on the row is cheapest (column is also possible)
         R(n,n)=conj(Grot(1,idef))*R(n,n);
       elseif (Gind(idef,3) < Gind(idef+1,3))
         % Positioned left, w.r.t. next rotation, hence apply on the colum
         R(p:idef+1,idef+1)=conj(Grot(1,idef))*R(p:idef+1,idef+1);
       else
         % Positioned right, w.r.t. next rotation, hence apply on the
         % row
         R(idef+1,idef+1:q)=conj(Grot(1,idef))*R(idef+1,idef+1:q);  
       end
       % Set the rotations equal to the identity
       Grot(:,idef)=[1;0];
     end
       
     % Set all the values for the next iteration step
     deflag(idef)=0;
     diter(idef)=numiter;
     
     
     % Change the values of p and q, to continue the procedure
     findpq
     % defcrit=cutting_crit;
     
     % Start counting again from zero.
     numiter=0;
     
     % This step is not really necessary, but the implementation
     % shifts the orders sometimes slightly to the right, here
     % once there is convergence, we put them nicely back to the front
     mp=min(Gind(:,3));
     Gind(:,3)=Gind(:,3)-mp+1;
       
% $$$      % Set directions once more
% $$$      % When the final from position 1 is too small, this if can create
% $$$      % problems, hence an extra while is put around it
% $$$      if (q-p+1>cutsize)
% $$$        if (Gind(q-2,3) < Gind(q-1,3)) 
% $$$          dir=1; % Hessenberg form, annihilate left
% $$$        else
% $$$          dir=0; % Hessenberg-like form, annihilate right
% $$$        end
% $$$      end
   end
end


% Compute now all the eigenvalues of the blocks of size at most cutsize
retrieveeigenvalues

  
 
   
