% HLMEIG    Eigenvalues and eigenvectors of Hessenberg-like matrices,
%           based on multishift iteration
%
%    D=HLMEIG(G,R,struc) 
%    Computes the eigenvalues of the Hessenberg-like
%    matrix represented with G and R (this is in fact the
%    QR-factorization of this matrix, with G containing the successive
%    Givens transformations.)
%    G --> a 2 times n-1 vector containing the cosine and sine of the
%      Givens-vector representation
%    R --> an upper triangular matrix
%    struc --> structure of the matrix, determines, if not specified 
%              the number of shifts k:
%              'rs' means a real symmetric matrix, k=1
%              'r' real not necessarily symmetric, k=2
%              'c' a complex matrix, k=1
%    D--> output contains the eigenvalues.
%
%   HLMEIG(G,R,struc,shiftk)
%   Same as above, but enforces shiftk shifts. 
%   Remark that the implemented shift is the Rayleigh shift strategy. In
%   case of struc='r', k=1, is not guaranteed to converge in case of
%   complex conjugate eigenvalues. (One should use the wilkinson shift,
%   which is unfortunately not implemented.)
%
%   HLMEIG(G,R,struc,shiftk,cutcrit)
%   Same as above, but with the standard deflation criterion changed to cutcrit.
%   'r','c' standard 10^(-15)
%   'rs' standard 10^(-8)
%
%   HLMEIG(G,R,struc,shiftk,cutcrit,redlev)
%   Same as above, but the standard criterion (10^(-3)) to reduce shifts, when
%   convergence occurs changed to redlev)
%
%   HLMEIG(G,R,struc,shiftk,cutcrit,redlev,defcrit)
%   Same as above, but changes the values to check for deflation:
%   'giv' --> Check the absolute value of the cosine in the Givens
%   representation.
%   'rel' --> Use a more relative criterion based on values of the
%   diagonal elements. 
%   'fnc' --> Full norm comparison, of the subblock, this compares
%   the complete norm of the subblock, most reliable, adds 4n to the complexity.
%   (This is the standard value.)
%
%   HLMEIG(G,R,struc,shiftk,cutcrit,redlev,defcrit,shifttype)
%   Same as above, but changes the shifttype if k=1. Note that also for
%   higher k, the routine sometimes shifts to smaller values of k, in
%   case of possible convergence.
%   Standard shifttype is the rayleigh shift type
%   'rl' --> Rayleigh shift
%   'wilk' --> Wilkinson shift
%
%   [D,Giter]=HLMEIG(G,R,struc,k,cutcrit,redlev,defcrit)
%   Can be used in any of the combinations above, outputs the number of
%   iterations in each step before deflation.
%
%
%    Software of the MaSe - Group
%    mase-at-cs.kuleuven.ac.be
%    Revision Date: 23/03/2007

function [eigcomp,Giter]=HLMEIG(Go,Ro,struc,shiftk,cutcrit,redlev,defcrit,shifttype)
 
  % In order to suppress unnecessary copying of variables, we use globals
  global G R; % Has the Givens vector representation of the active block
  global swaplevel;
  global Rfull Gfull;
  global Giter;
   
  % Stores general problem variables
  global iprobl
  global ibegin
  global iend
  global iiter
  global niter
  
  % This is necessary in order to use the G,R variables, globally,
  % in the following subroutines
  G=Go;
  R=Ro;
  clear Go Ro;
  
  % Check if the number of iterations are desired
  if (nargout==2)
    cntiter=true;
    global niter; % In order to find the problems
  else
    cntiter=false;
  end
  
  
  % Check if the structure is properly defined
  if (exist('struc')~=1)
    disp('PLEASE SELECT THE STRUCTURE OF THE MATRIX');
    disp('"rs" means a real symmetric matrix');
    disp('"r" real not necessarily symmetric');
    disp('"c" a complex matrix');
    return
  end
  
  
  % Assign the individual parameters for the specific problem
  switch struc
   case 'rs'
    kor=1;
    cutoff=10^(-8);
   case 'r'
    kor=2;
    cutoff=10^(-15);
   case 'c'
    kor=1;
    cutoff=10^(-15);
   otherwise
    disp('PLEASE SELECT THE STRUCTURE OF THE MATRIX');
    disp('"rs" means a real symmetric matrix');
    disp('"r" real not necessarily symmetric');
    disp('"c" a complex matrix');
    return
  end
  
  
  % Overwrite some of the variables, in case they were not determined
  if (exist('shiftk')==1)
    kor=shiftk;
  end
   
  if (exist('shifttype')~=1)
    shifttype='rl';
  end
  
  if (exist('cutcrit')==1)
    cutoff=cutcrit;
  end
  
  if (exist('redlev')==1)
    treshhold=redlev;
  else
    treshhold=10^(-3);
  end
  
  if (exist('defcrit')~=1)
    defcrit='fnc';
  end
  
  
  % Start the initialization procedure. 
  % Initialize some variables.
  n=size(R,1);
 
  % store the original representation
  Rfull=R;
  Gfull=G;
  ibegin=1; % Contains the beginning of submatrices
  iend=n;   % Contains the end of submatrices
  iprobl=1; % Indicates the active problem being solved
  eigcomp=zeros(n,1); % contains the eigenvalues
  ieig=0; % Counts the eigenvalues
  iiter=0; % Counts the subproblems


  % Start the iterative procedure untill all eigenvalues, are computed
  % from the original problem
  % iprobl, denotes the problem which is currently being solved

  while iprobl > 0

    % extract the specific subproblem
    i1=ibegin(iprobl);
    i2=iend(iprobl);

    R=Rfull(i1:i2,i1:i2);
    G=Gfull(:,i1:i2-1);
    n=i2-i1+1;

    % These matrices are coming from previous steps, in order
    % to achieve the fastest convergence we will see if it is necessary
    % to swap the matrix around
    [G,R,k]=CSSWAPNEW(G,R,kor,treshhold,struc,defcrit);
    
    
    % when the problem is small enough, solve it directly
    if n <= 2
        if n == 1
            eigcomp(ieig+1)=R(1,1);
            ieig=ieig+1;
        else
            % reconstruct the dense matrix
            CM=R;
            Giv=[G(1,1),-conj(G(2,1));G(2,1),conj(G(1,1))];
            CM(1:2,:)=Giv*CM(1:2,:);
            eigcomp(ieig+1:ieig+2)=eig(CM);
            ieig=ieig+2;
        end
        iprobl = iprobl-1;
    else
      
      % size of the subproblem is larger than 2
        converged=false;
	niter=0;         

        while (~converged) 
          
          if (cntiter)
            niter=niter+1;
          end
          
          shiftok=true;       
          
          % Compute the shifts and
          % perform the first k steps of the implicit QR-method,
          % without the shift
          if ((struc=='r') & (kor==2))
            sigma=CRS_real(k);
            [ChGiv]=MQRWSch_real(sigma);  
          else
            sigma=CRS(k,shifttype);
            [ChGiv]=MQRWSch(sigma); 
          end
          R=triu(R);
          
          % Perform first deflation
          [i1,i2,converged]=DEFLATE1(n,defcrit,cutoff,cntiter,i1,i2,k);
          %DEFLATE1;
           
          
          % If not deflated yet, continue
          if (~converged) & (shiftok)
            % Perform the implicit Chasing technique
            MQRCHch(ChGiv);
            R=triu(R);

            % check if deflation is possible
             [i1,i2,converged]=DEFLATE(n,defcrit,cutoff,cntiter,i1,i2);
            %DEFLATE;
            
          end
        end
    end
  end
  
%--------------------------------------------------------------------
% Convergence speed up swap.
% This routine checks if it is possible to swap the matrix around to
% speed up the convergence

function [G,R,k]=CSSWAPNEW(G,R,k,forcek,struc,defcrit)

  treshhold=10^(-3); % Only if it is smaller than 10^(-3), there is a
                     % swapping
  n=size(G,2)+1;
  
  % We adapt the value of k, k needs to be smaller than n/2, in case of a
  % three by three this means that k is maximal 1
  
  if (struc=='r')
    % This value needs to hold for real matrices
    k=min(n-1,k);
  else
    k=min(floor(n/2),k);
  end
  
                    
  % Compute the subdiagonal elements, checked for deflation
  if (defcrit=='giv')
    v=abs(G(2,:));
  else
    d=diag(R)';
    v=(abs(G(2,:).*d(1:n-1)))./(abs(G(1,:)).*(abs(d(1:n-1))+abs(d(2:n))));
  end;
  
  % Only for three by three matrices we will swap, otherwise
  % the eigenvalues are directly computed
  if (n>=3)
    
    % Compute the minimum valu in the absolute value of G
    [mn,indx]=min(v);
  
    if (indx<=k) & (mn<treshhold)
       
      % This means that the smallest element is located on the top left
      % position, and smaller than the value of treshhold, hence we want to swap
      [G,R]=SWAP(G,R); 
      
      % If k =2 and the other subdiagonal elements is smaller we reduce
      % the shift to k=1, THIS IS ONLY WORKING FOR THE REAL SYMMETRIC CASE
      if (v(1)<forcek)
        k=1;
      end
    else
      if (v(n-1)<forcek)
        k=1;
      end
    end
  end
  
%--------------------------------------------------------------------

% IN this routine we will swap the matrix from a QR to a RQ factorization

function [Gn,R]=SWAP(G,R)
  
  
  n=size(R,1);
   
   
  if (n==1)
    R=R;
    Gn=G;
  else
    
   
   for i=1:n-1
   
     Giv=[G(1,i),-conj(G(2,i));G(2,i),conj(G(1,i))];
     R(i:i+1,:)=Giv*R(i:i+1,:);
     [c,s,r] = Givensnch(R(i+1,i+1),R(i+1,i));
     Giv=[conj(c),s; -conj(s),c];   
     Gn(:,n-i)=[conj(c);conj(s)];
     R(:,i:i+1)=R(:,i:i+1)*Giv;
   end
  
   R=fliplr(fliplr(R).');
   
  end
  


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

% CRS    Compute Rayleigh shift: SUBROUTINE OF HLMEIG
%
%    sigma = CRS(R), gives the rayleigh eigenvalues of the matrix R, 
%    its lower right subblock. The routine uses a global G, which
%    contains, the Givens transformations applied on R.

function sigma=CRS(k,shifttype)
  
  global G R;
    if ((shifttype=='wl') & (k==1))
      % We enforce k==2, because we need the eigenvalues of the lower
      % right 2x2 block
      %disp('Wilkinson shift')
      wilkshift=true;
      k=2;
    else
      wilkshift=false;
    end
    
      
      
  
    % The size of the block is determined by the size of the input
    % rectangular matrix
    n=size(R,1);
    
    HR=R(:,n-k+1:n);
    
    % The upper part R is the part from the QR factorization, perform the
    % necessary Givens transformations to compute the effective lower right
    % block of the matrix.
    for i=1:n-1
      Giv=[G(1,i),-conj(G(2,i));G(2,i),conj(G(1,i))];
      HR(i:i+1,:)=Giv*HR(i:i+1,:);
    end
    sigmah=eig(HR(n-k+1:n,:));    
  
    
    
    if (wilkshift)
      % We have now the eigenvalues of the lower right 2 times 2 block, 
      % We choose now the eigenvalue closest to the lower right element.
      % This can of course be complex
      if (abs(HR(n,2))-abs(sigmah(1))) < (abs(HR(n,2))-abs(sigmah(2))) 
        sigma=sigmah(1);
      else
        sigma=sigmah(2);
      end
    else
      sigma=sigmah;
    end
  





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

% CRS    Compute Rayleigh shift: SUBROUTINE OF HLMEIG
%
%    sigma = CRS(R), gives the rayleigh eigenvalues of the matrix R, 
%    its lower right subblock. The routine uses a global G, which
%    contains, the Givens transformations applied on R.

function sigma=CRS_real(k,pos)
  
  global G R;
  
  % The size of the block is determined by the size of the input
  % rectangular matrix
  n=size(R,1);
  
  HR=R(:,n-k+1:n);
  
      
  % The upper part R is the part from the QR factorization, perform the
  % necessary Givens transformations to compute the effective lower right
  % block of the matrix.
  for i=1:n-1
    Giv=[G(1,i),-conj(G(2,i));G(2,i),conj(G(1,i))];
    HR(i:i+1,:)=Giv*HR(i:i+1,:);
  end
  
  if (k==1)
    sigma=eig(HR(n-k+1:n,:));
  else
    % Because we want computations to be restricted to the real case
    % we need to return the determinant and the trace of the lower
    % $2\times 2$ block
    sigma(1)=trace(HR(n-k+1:n,:));
    sigma(2)=det(HR(n-k+1:n,:));
  end
  
    
    
  





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

% MQRWS    Perform Multishift QR without Shift:
%          SUBROUTINE OF HLEIG
%
%    ChGiv = MQRWS(k,sigma), outputs the disturbing Givens
%    transformations, needed for the chasing procedure in the original
%    matrix. Input has globals R and G, and the number of multishifts,
%    and the shifts themselves.

function [ChGiv]=MQRWSch(sigma)
  
  % Define some global variables
  global G R;
  
  % initialize the sizes
  n=size(R,1);
  k=length(sigma);

  % Hfirst will contain the remaining first vector, sucht that we can
  % compute the Chasing Givens.
  Hf=zeros(n,1); % Hf stands for H his first column
  Hf(1)=1.0;
  
  for j=1:k
    
    % Compute the first column, necessary for the Chasing Givens
    Hftmp=Hf*sigma(j);
    for i=j:-1:1
      Giv=[conj(G(1,i)),conj(G(2,i));-G(2,i),G(1,i)];
      Hftmp(i:i+1)=Giv*Hftmp(i:i+1);
    end
    Hf(1:j+1)=R(1:j+1,1:j)*Hf(1:j)-Hftmp(1:j+1);
    
    % Perform the steps without shift 
    for i=n-1:-1:1
      Giv=[conj(G(1,i)),conj(G(2,i));-G(2,i),G(1,i)];
      R(:,i:i+1)=R(:,i:i+1)*Giv';
      [c,s,r] = Givensnch(R(i,i),R(i+1,i));
      G(1,i)=conj(c); G(2,i)=conj(s);
      Giv=[c,s;-conj(s),conj(c)];
      R(i:i+1,:)=Giv*R(i:i+1,:);
    end
  end
  
  
  % Now we have the Givens-R representation of the matrix in question.
  % Let us initialize the Givens transformations for the Chasing.
  r=Hf(k+1);
  for i=k:-1:1
    [c,s,r] = Givensnch(Hf(i),r);
    
    % Save the Hermitian conjugate Givens
    ChGiv(1,i)=c;
    ChGiv(2,i)=-conj(s);
  end



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

% MQRWS    Perform Multishift QR without Shift:
%          SUBROUTINE OF HLEIG
%
%    ChGiv = MQRWS(k,sigma), outputs the disturbing Givens
%    transformations, needed for the chasing procedure in the original
%    matrix. Input has globals R and G, and the number of multishifts,
%    and the shifts themselves.

function [ChGiv]=MQRWSch_real(sigma)
  
  % Define some global variables
  global G R;
  
  % initialize the sizes
  n=size(R,1);
  k=length(sigma);

  % Hfirst will contain the remaining first vector, sucht that we can
  % compute the Chasing Givens.
  Hf=zeros(n,1); % Hf stands for H his first column
  Hf(1)=1.0;
  
  if (k==1)
    % Compute the first column, necessary for the Chasing Givens
    Hftmp=Hf*sigma(1);
    Giv=[conj(G(1,1)),conj(G(2,1));-G(2,1),G(1,1)];
    Hftmp(1:1+1)=Giv*Hftmp(1:1+1);
    Hf(1:1+1)=R(1:2,1)-Hftmp(1:2);
    
    % Perform a step of the QR-method without shift 
    for i=n-1:-1:1
      Giv=[conj(G(1,i)),conj(G(2,i));-G(2,i),G(1,i)];
      R(:,i:i+1)=R(:,i:i+1)*Giv';
      [c,s,r] = Givensnch(R(i,i),R(i+1,i));
      G(1,i)=conj(c); G(2,i)=conj(s);
      Giv=[c,s;-conj(s),conj(c)];
      R(i:i+1,:)=Giv*R(i:i+1,:);
    end
  
  else 
    % Now we have to compute the chasing more cleverly
    % sigma1 is the trace
    % sigma2 is the determinant
    %Hf1=R^2 R^1 e_1
    %Hf2=Q^2^H Q^1^H det(..)
    %Hf3=R^2 Q^1^H trace(..)
    
    % Compute the first column, necessary for the Chasing Givens
    Hf3=Hf*R(1,1)*sigma(1);
    
    Giv=[conj(G(1,1)),conj(G(2,1));-G(2,1),G(1,1)];  
    Hf2=Hf*sigma(2);
    Hf2(1:2)=Giv*Hf2(1:2);
        
    Hf1=R(1,1)*Hf;
    
    
    % Perform the steps without shift 
    for i=n-1:-1:1
      Giv=[conj(G(1,i)),conj(G(2,i));-G(2,i),G(1,i)];
      R(:,i:i+1)=R(:,i:i+1)*Giv';
      [c,s,r] = Givensnch(R(i,i),R(i+1,i));
      G(1,i)=conj(c); G(2,i)=conj(s);
      Giv=[c,s;-conj(s),conj(c)];
      R(i:i+1,:)=Giv*R(i:i+1,:);
    end
    
    
    % Now the givens are from Q^{(2)} and the R= R^{(2)}
    Giv=[conj(G(1,1)),conj(G(2,1));-G(2,1),G(1,1)];
    Hf3(1:2)=Giv*Hf3(1:2);
    
    % Apply two Givnes on the Hf2
    for i=2:-1:1
      Giv=[conj(G(1,i)),conj(G(2,i));-G(2,i),G(1,i)];
      Hf2(i:i+1)=Giv*Hf2(i:i+1);
    end
    
    Hf1=R(1,1)*Hf1;
    Hf=Hf1+Hf2-Hf3;
    
    % Perform the steps without shift 
    for i=n-1:-1:1
      Giv=[conj(G(1,i)),conj(G(2,i));-G(2,i),G(1,i)];
      R(:,i:i+1)=R(:,i:i+1)*Giv';
      [c,s,r] = Givensnch(R(i,i),R(i+1,i));
      G(1,i)=conj(c); G(2,i)=conj(s);
      Giv=[c,s;-conj(s),conj(c)];
      R(i:i+1,:)=Giv*R(i:i+1,:);
    end
  end
  
  % Now we have the Givens-R representation of the matrix in question.
  % Let us initialize the Givens transformations for the Chasing.
    r=Hf(k+1);
  
  for i=k:-1:1
    [c,s,r] = Givensnch(Hf(i),r);
    
    % Save the Hermitian conjugate Givens
    ChGiv(1,i)=c;
    ChGiv(2,i)=-conj(s);
  end



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

% GIVENSN Compute a Givens transformation matrix
%
%    [c,s,r] = GIVENS(x,y) returns the cosine and sine of the complex
%    Givens rotation matrix and the resulting norm r.
%    
%        | c       s       |                  | x |     | r |
%    G = |                 |   such that  G * |   |  =  |   |
%        |-conj(s) conj(c) |                  | y |     | 0 |
% 
%    where c, s are complex, and c^2 + |s|^2 = 1. 


function [c,s,r] = Givensnch(x,y);

   if (y == 0),
      c = 1; s = 0; r = x;
   else
      if (abs(x) >= abs(y))
         %disp('Case 1')
         t = y/x; r = sqrt(1 + abs(t)^2);
         c = 1/r;
         s = t'*c;
         r = x*r;
      else
         %disp('Case 2')
         t = x/y; r = sqrt(1 + abs(t)^2 );
         s = 1/r;
         c = t'*s;
         r = y*r;
      end
   end

   
   %% Unfortunately this Algorithm can output negative values of r,
   %% This is not consistent with our computations, we will identify the
   %% Givens transformations uniquely by outputting only positive real r
   %% In order to turn slightly the Givens transformation we will
   %% multiply the result with abs(x)
   
   if (x~=0)
     % First we turn the matrix, such that c is real
     %theta=conj(c)/abs(c);
     
     % Or we assume the r to be real
     theta=conj(sign(r));
     c=c*theta;
     s=s*theta;
     r=theta*r;
     
     
   end
   

    




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

% DEFLATE1    Perform Multishift QR without Shift:
%            SUBROUTINE OF HLMEIG
%
%       DEFLATE, only uses globals. This function checks for deflation,
%       and stores this into new matrices.
%
%       This deflate 1 checks if there is convergence in the first k
%       entries, where k corresponds to the shift
%       if there is convergence we swap the matrix and continue with the
%       iteration
function [i1,i2,converged]=DEFLATE1(n,defcrit,cutoff,cntiter,i1,i2,k) 
  global Rfull Gfull R G ibegin iend iprobl iiter niter Giter;
  
  % check if deflation is possible
  converged=false;
  i = 1;
  pend=n;

  % Compute the subdiagonal elements, checked for deflation
  if (defcrit=='giv')
    v=abs(G(2,:));
  else
    d=diag(R)';
    v=(abs(G(2,:).*d(1:n-1)))./(abs(G(1,:)).*(abs(d(1:n-1))+abs(d(2:n))));
  end;

  while (~converged) & (i<n) & (n>2*k+1)    
    if abs(v(i)) <= cutoff
      found = true;
      i1=ibegin(iprobl);
      i2=iend(iprobl);
      
      Rfull(i1:i2,i1:i2)=R;
      Gfull(:,i1:i2-1)=G;
      n=i2-i1+1;
      converged=true;
      
      iend(iprobl)=i+i1-1;
      iprobl=iprobl+1;
      ibegin(iprobl)=i+i1;
      iend(iprobl)=pend+i1-1;

      Gfull(1,i+i1-1)=1;
      Gfull(2,i+i1-1)=0;
   
      % Because the Givens matrices are scaled with roots of unity, 
      % we have to incorporate this scaling. Hence we update the 
      % last column of the remaining matrix. This corresponds to
      % performing a similarity trnasformation, with a diagonal, removing
      % the scalling from the left, but then we need to apply it on the right
      Rfull(:,i+i1-1)=G(1,i)*Rfull(:,i+i1-1);

      % Because the Givens matrices are scaled with roots of unity, 
      % we have to incorporate this scaling. Hence we update the first
      % row of the separated block with the conjugate Givens.
      Rfull(i+i1,:)=conj(G(1,i))*Rfull(i+i1,:);
    
      iiter=iiter+1;
      if (cntiter)
        Giter(iiter)=niter;
      end
      
    end
    i=i+1;
  end
	


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

% MQRCH    Perform Multishift QR Chasing part
%          SUBROUTINE OF HLEIG
%
%    sigma = CRS(R), gives the rayleigh eigenvalues of the matrix R, 
%    its lower right subblock. The routine uses a global G, which
%    contains, the Givens transformations applied on R.

function MQRCHch(ChGiv)
  
  % Define some global variables
  global G R LOOP;
  
  % initialize the sizes
  n=size(R,1);
  k=size(ChGiv,2);

           


  % In order to perform the implicit Algorithm, we need to store two
  % sequences of Givens transformations, one sequence coming from the
  % Chasing and a second sequence (1 Givens less) for updating the
  % representation..

  % Perform the Givens transformations on the columns
  for i=k:-1:1
    Giv=[conj(ChGiv(1,i)),conj(ChGiv(2,i));-ChGiv(2,i),ChGiv(1,i)];
    R(:,i:i+1)=R(:,i:i+1)*Giv;
  
    [c,s,r] = Givensnch(R(i,i),R(i+1,i));
    
    % perform the transformation on R
    Giv=[c,s;-conj(s),conj(c)];
    R(i:i+1,:)=Giv*R(i:i+1,:);
    
    % Store the inner Givens transformations
    % This is the conjugate from the Givens transformation performed
    InGiv(1,i)=conj(c);
    InGiv(2,i)=conj(s);
  end


  % Counter for the representation Givens
  TempGiv=InGiv;

  for i=1:k-1 
    % Let us perform the updates, to remove one of the inner Givens
    % transformations
    
    % Perform the shift through
    % The top G2, should be stored for the new representation
    % The right one--> Is the new Inner Givens, this is stored temp
    % The left one--> Updating for proceding InGiv
    [InGiv(:,i+1),G(:,i),TempGiv(:,i)]=ST(G(:,i),InGiv(:,i+1),InGiv(:,i));
  end


  % After this step we have to fuse two givens transformations
  G(:,k)=Fusion(G(:,k),InGiv(:,k));
  
  % Reassign the TempGiv to InGiv
  InGiv=TempGiv;
  
  % Let us now perform the chasing sequence this is a loop
  endnear=0;
  
  for i=1:n-1
    % Here we have to distinguish..
    % if a certain value for j+i gets exceeded we do not need to perform
    % shift throughs anymore, but we have to include the last Givens into
    % the Representation via fusion
    if (i+k+1>n)
      % First apply the fusion, and then reduce the number of problem
      % creating Givens transformations
      
      % The last Givens transformation of ChGiv, needs to be combined
      % with the last Givens transformation of the representation, so
      % called fusion of Givens transformations
      G(:,n-1)=Fusion(ChGiv(:,k),G(:,n-1));
  
      % Reduce the number of Disturbing Givens transformations
      k=k-1;
      
      % To indicate that we first have to apply a fusion
      endnear=1;
    end


    % First we will perform the shift throughs through the representation
    % This is in fact a changing from a v to a wedge pattern,
    % this procedure is also used in the next loop
    for j=k:-1:1
      [G(:,j+i),G(:,j+i-1),ChGiv(:,j)]=ST(ChGiv(:,j),G(:,j+i),G(:,j+i-1));
    end


    % If end is near, we have to fuse first a Givens from InGiv and one
    % from ChGiv
    if ((endnear==1) & (k~=0))
      % Remove the first Givens transformation from InGiv and absorb it
      % into the last one of Chgiv
      ChGiv(:,k)=Fusion(ChGiv(:,k),InGiv(:,k));
    end
    
    
    
    % NOw we have to perform another swapping to Chase the ChGiv through
    % the representation in order to obtain a changed position for the
    % ChGiv and the InGiv
    for j=k-1:-1:1 
      [InGiv(:,j),ChGiv(:,j),G3]=ST(ChGiv(:,j),ChGiv(:,j+1),InGiv(:,j));
      
      % Now we need to apply this transformed Givens ChGiv onto the matrix
      % R to create the desired bulges
      Giv=[G3(1),-conj(G3(2));G3(2),conj(G3(1))];
      R(j+i+1:j+i+2,:)=Giv*R(j+i+1:j+i+2,:);
    end
    
    
    if (i~=(n-1))
      % The last disturbing transformation
      Giv=[ChGiv(1,1),-conj(ChGiv(2,1));ChGiv(2,1),conj(ChGiv(1,1))];
      R(i+1:i+2,:)=Giv*R(i+1:i+2,:);
    end
    
    % Now we have to remove these bulges by Givens transformations acting
    % on the columns and moreover we have to perform the similarity
    % transformation Hence we create a new bulge.
    
    for j=k:-1:1
      % Let us compute the two Givens transformations to remove the bulges
      % and perform them onto the matrix R
      [c,s,r] = Givensnch(R(j+i+1,j+i+1),R(j+i+1,j+i));
      
      % PAY ATTENTION HERE WITH THE GIVENS, DUE TO THE FACT THAT THE
      % OPERATION IS DETERMINED TO BE PERFORMED ON THE RIGHT, THE
      % POSITION OF THE CONJUGATES ETC, CHANGES SLIGHTLY. THIS IS NOT
      % IDENTICAL TO THE STANDARD ROW CASE
      % Reassign these values to ChGiv
      ChGiv(:,j)=[conj(c);conj(s)];
      ChGiv(:,j)=[c;conj(s)];
   

      % Perform this transformation onto the columns
      Giv=[c,s;-conj(s),conj(c)];
      Giv=[conj(c),s;-conj(s),c];
      R(:,j+i:j+i+1)=R(:,j+i:j+i+1)*Giv;
            
    end
    
  end
            



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

%-------------------------------------------------------------------
  function G=Fusion(G1,G2)
  
  % Based on two Givens transformations G1 and G2, we fuse these two
  % matrices together
    
    
  G(1,1)=G1(1)*G2(1)-conj(G1(2))*G2(2);
  G(2,1)=G1(2)*G2(1)+conj(G1(1))*G2(2);

  
  %-------------------------------------------------------------------
  function [G1,G2,G3]=ST(G1,G2,G3)

    global G1o G2o G3o G;
    global niter LOOP;
    tt=0;
    G1o=G1;
    G2o=G2;
    G3o=G3;
  


  % This function performs the shift throug-lemma
  % It changes slightly the order of the Given Givens trnasformations
    
  % This is a rigid implementation, based on the $QR$-decomposition
  % of the involved orthogonal matrix, constructed by the
  % Givens transformations
 
  % Due to the non uniqueness of the shift through lemma in case of
  % matrices almost identical to the identity we will now build in a
  % stopping criterion
  th=10^(-10); % threshold for removing the value
  
  if (abs(G1(2))<th)
      tt=1;
  end
  
  
  if (abs(G2(2))<th)
      tt=1;
  end
      
    
  if (abs(G3(2))<th)
    tt=1;
  end
  
  % TEMPORARY
  go1=G1;
  go2=G2;
  go3=G3;
  
    
  % Construct the orthogonal matrix, by creating the Full Givens
  % transformation matrices
    Giv1=[G1(1),-conj(G1(2)),0;G1(2),conj(G1(1)),0;0,0,1];
    Giv2=[1,0,0;0,G2(1),-conj(G2(2));0,G2(2),conj(G2(1))];
    Giv3=[G3(1),-conj(G3(2)),0;G3(2),conj(G3(1)),0;0,0,1];
    
  % Make the multiplications
    O=Giv1*Giv2*Giv3;
    Oorig=O;
   
    
  % Compute the new factorization
  
    transposed = false;
    if norm(O(2:3,1)) < norm(O(1,2:3))
    	transposed = true;
	O=O';
	Oorig=Oorig';
    end
  
    [c,s,r] = Givensnch(O(2,1),O(3,1));
    Giv1=[1,0,0;0,c,s;0,-conj(s),conj(c)];
    O=Giv1*O;
    G1(1)=conj(c);
    G1(2)=conj(s); 
    
    % compute the second Givens based on the vector having highest norm
    sw = false;
    kk=1;
    vv=O(1:2,1);
    maxnorm=norm(vv);
    for k=2:3
	if norm(O(1:2,k)) > maxnorm
		sw=true;
		vv=O(1:2,2);
	end
    end
		
      
    [c,s,r] = Givensnch(vv(1),vv(2));
    if sw
    	% Compute the Givens transformation first
        Giv2=[-conj(s),conj(c),0;-c,-s,0;0,0,1];
	Ohelp=Giv2*O;
        ss=conj(sign(Ohelp(1,1)));
        % Based on the value of Ohelp, we change the transformation 
        % sligthly
        s=s*conj(ss);
        c=c*conj(ss);
        Giv2=[-conj(s),conj(c),0;-c,-s,0;0,0,1];
        G2(1)=-s;
	G2(2)=c;
	O=Giv2*O;
    else
    	Giv2=[c,s,0;-conj(s),conj(c),0;0,0,1];
    	O=Giv2*O;
    	G2(1)=conj(c);
    	G2(2)=conj(s);
    end
    
    [c,s,r] = Givensnch(O(2,2),O(3,2));
    Giv3=[1,0,0;0,c,s;0,-conj(s),conj(c)];
    O=Giv3*O;
    G3(1)=conj(c);
    G3(2)=conj(s); 
    
    if transposed
    % star the Givens
      Gh=G1;
      G1(1)=conj(G3(1));
      G1(2)=-G3(2);
      G3(1)=conj(Gh(1));
      G3(2)=-Gh(2);
      Gh=G2;
      G2(1)=conj(Gh(1));
      G2(2)=-Gh(2);
    end

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

% DEFLATE    Perform Multishift QR without Shift:
%            SUBROUTINE OF HLMEIG
%
%       DEFLATE, only uses globals. This function checks for deflation,
%       and stores this into new matrices.

function [i1,i2,converged]=DEFLATE(n,defcrit,cutoff,cntiter,i1,i2) 
  global Rfull Gfull R G ibegin iend iprobl iiter niter Giter;
  
  % check if deflation is possible
  converged=false;
  i = 1;
  pend=n;

  % The value v for checking if off-diagonal subblocks have converged
  % is not correct enough, we apply the technique discussed in the
  % phd-thesis of Raf on Page 180
  
  
  
  
  % Compute the subdiagonal elements, checked for deflation
  if (defcrit=='giv')
    v=abs(G(2,:));
  elseif (defcrit=='rel')
    d=diag(R)';
    v=(abs(G(2,:).*d(1:n-1)))./(abs(G(1,:)).*(abs(d(1:n-1))+abs(d(2:n))));
  else
    % let us complete the exact frobenius norm of the subblocks
    nrmtmp=0;
    nrm=0;
    v=0;
    for it=1:n-1
      nrmtmp=abs(G(2,it)*sqrt(nrmtmp^2+d(it)^2));
      nrm(it)=nrmtmp;
    end
    
    % let us derive now a relative criterion
    %nrm
    v=nrm./sqrt(abs(d(1:n-1))+abs(d(2:n)));
    %size(d(1:n-1))
    %size(nrm)
    %pause
  
  end;

  
  
  while (~converged) & (i<n)
   
    %v(i)
    if v(i) <= cutoff
      %disp('Deflated')
      found = true;
      i1=ibegin(iprobl);
      i2=iend(iprobl);
      
      Rfull(i1:i2,i1:i2)=R;
      Gfull(:,i1:i2-1)=G;
      n=i2-i1+1;
      converged=true;
      
      iend(iprobl)=i+i1-1;
      iprobl=iprobl+1;
      
      ibegin(iprobl)=i+i1;
      iend(iprobl)=pend+i1-1;
      
      Gfull(1,i+i1-1)=1;
      Gfull(2,i+i1-1)=0;
      
      % Because the Givens matrices are scaled with roots of unity, 
      % we have to incorporate this scaling. Hence we update the 
      % last column of the remaining matrix. This corresponds to
      % performing a similarity trnasformation, with a diagonal, removing
      % the scalling from the left, but then we need to apply it on the right
      Rfull(:,i+i1-1)=G(1,i)*Rfull(:,i+i1-1);

      % Because the Givens matrices are scaled with roots of unity, 
      % we have to incorporate this scaling. Hence we update the first
      % row of the separated block with the conjugate Givens.
      Rfull(i+i1,:)=conj(G(1,i))*Rfull(i+i1,:);
    
      iiter=iiter+1;
      if (cntiter)
        Giter(iiter)=niter;
      end
      
    end
    i=i+1;
  end
  

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


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


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


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




