%  UniSimCR Unitary Similarity transformation to Compressed Representation
%
%
%    [Grot,Gind,R]=UniSimCR(Grot,Gind,R,p)
%    Starts from the QR-factorization of a matrix A=QR, where Q is
%    factored in rotations specified by Grot and Gind.
%    The vector p is the position vector, specifying the QR-factorization
%    of the outcome B=U^H A U = Q_1 R_1 where the rotational factorizatio
%    of Q_1 is ordered according to p.
%    p is a binary vector: 1 means annihilate left
%                          0 means annihilate right
%
%
%    Software written by Raf Vandebril
%    raf.vandebril-at-cs.kuleuven.be
%    Revision Date: September 1, 2010
%


function [Grot,Gind,R]=UniSimCR(Grot,Gind,R,or)
  
  % Remark that the input format of Grot and Gind is quite important,
  % we assume that the output is not compressed, but uses exactly the
  % ordering as generated by PyramidQR.
  % No testing for identity rotations is included, faster reductions are
  % therefore possible in case more structure or knowledge related to the
  % rotations is available.
  
  % There are possibilities for doing this based on routines flfree and
  % frfree which found the leftmost or rightmost free rotations. Based on
  % these rotations one can then determine the next steps.
  % Using however the pyramid shape we no specifilly the position of each
  % rotation, enabling a simplification of the implementation.
    
  % Initialization 
    n=size(R,1);
    
  % The implementation here is based on the shift-through and the fusion
  % operations 
   
  
  %  These keep clear track of the rotation one has to start annihilating
  %  either on the left or on the right
  rm=size(Gind,1);
  rpos=rm;
  lm=1;
  lpos=1;
  
  % track the sequence on the right we are dealing with
  % track the sequence on the left we are dealing with
  % these are essential for correct starting points of the sequences
  sr=1;
  sl=1;
  
  
  for i=1:n-2
    % The counter i will indicate which sequence one is removing, 
    % The next counter will indicate the rotation  that will be removed. 
    % For instance remove rotation j from sequence i (either left or right)
    
    if (or(i)==1)
      % Annihilate the left rotations
      % for seq 1 remove n-2 rotations
      % for seq 2 remove n-3 rotations, 
      
      % To correctly perform the shift through operations we also need to
      % track the rotations on the right
      % These are the rotations involved in the most rigth descending sequence
      % rspos2 is the bottom sequence along which one we slide
      % rspos1 is the top sequence along which one we slide  
      rspos2=rpos;
      rspos1=rpos; 
      % The updating will start immediately after the first loop
      
      
      for j=1:n-i-1
        % The position of the rotations when annihilating them from the
        % left increases always by 1
        % the position subjected now is marked by lpos.
        
% $$$         % This extra assignment can be used to track if all
% $$$         % annihilations proceed correctly, it marks which rotation is
% $$$         % annihilated in part i of the loop         
% $$$         Gind(lpos,4)=i;
% $$$         Gind
% $$$         pause
% $$$         
% $$$         %------------- CHECK correctness---------------
% $$$         A=ConsMatLeft(Grot,Gind,R);
% $$$         eigA=eig(A);
        
        
        % The rotation marked for annihilation is found in position lpos
        Giv=[Grot(1,lpos) Grot(2,lpos); -conj(Grot(2,lpos)) conj(Grot(1,lpos))];
        
        % Application on the left, corresponds to simply setting the
        % rotation corresponding to G equal to the identity
        Grot(:,lpos)=[1;0];
         
        % Transfer the rotation through the upper triangular matrix
        % R(:,[Gind(lpos,1),Gind(lpos,2)])=R(:,[Gind(lpos,1),Gind(lpos,2)])*Giv;
        % Since in this implementation Gind(lpos,1)+1 equals
        % Gind(lpos,2), we simplify this statement a little
        % bit. Moreover, taking into consideration that R is upper
        % triangular we can cut a little in the number of operations to
        % be performed by removing the :, by a more restrictive range
        gra=Gind(lpos,1);
        R(1:gra+1,gra:gra+1)=R(1:gra+1,gra:gra+1)*Giv;
        %[c,s,r]=Givens(R(Gind(lpos,1),Gind(lpos,1)),R(Gind(lpos,2),Gind(lpos,1)));
        [c,s,r]=Givens(R(gra,gra),R(gra+1,gra));
        Giv=[c s; -conj(s) conj(c)]; % To perform on R
        G=[conj(c);-s]; % To continue working with equals Giv^H
        %R([Gind(lpos,1),Gind(lpos,2)],:)=Giv*R([Gind(lpos,1),Gind(lpos,2)],:);
        R(gra:gra+1,gra:n)=Giv*R(gra:gra+1,gra:n);
         
        
        
        
        % Apply the new unitary transformation on the right of the
        % sequence of rotations.
        % To remove this rotation shift-through operations need to be
        % performed, followed by a fusion.
        % The number of shift-through operations corresponds to j-1
        % 0 for the first rotation
        % 1 for the second rotation, ...
        
        for k=1:j-1
          % to take the correct rotations for shifting through, a new
          % index is needed.
          % see also the next part, this indexing is closely related
             
          % Perform the Shift-through operation
          [G,Grot(:,rspos1),Grot(:,rspos2)]=ST(Grot(:,rspos1),Grot(:,rspos2),G);
          
          % Inside this chasing loop we proceed along the direction of
          % the ascending sequences so always -1.
          rspos1=rspos1-1;
          rspos2=rspos2-1;
       
        end
         
         % The fusion takes place with the rotation in position rspos1,
         Grot(:,rspos1)=Fusion(Grot(:,rspos1),G);
  
         % Update these positions, but take into consideration that from
         % the previous loop some elements were subtracted, they need to
         % be added again.
         rspos2=rspos1+j-1;
         rspos1=rspos1-1-(sr-1);
        
% $$$          %--------- Correctness Check -------------------
% $$$          % Compare before and after the similarity operation
% $$$          disp('Temporary comparison of correctness: left')
% $$$          [eig(ConsMatLeft(Grot,Gind,R)),eigA]
% $$$          pause
                  
        
         % update lpos to annihilate the next rotation in the following step  
         lpos=lpos+1;  
        
      end
      
      % Increase the sequence number
      sl=sl+1;

      % Update the start of the next sequence
      lm=lm+n-sl+1;
      
      % We ended annihilating elements from sequence sl,
      % Reposition lpos so that the bottom element of the following
      % sequence is correctly identified
      lpos=lm;
      
            
      
    else % This means that or(i) equals 0
         % Annihilate the right rotations
      
       % To correctly perform the shift through operations we also need to
       % track the rotations on the left
       % These are the rotations involved in the most left ascending
       % lspos2 is the bottom sequence along which one we slide
       % lspos1 is the top sequence along which one we slide  
       lspos2=lpos;
       lspos1=lpos; 
       % The updating will start immediately after the first loop
      
         
       for j=1:n-i-1
         % The position of the rotations when annihilating them from the
         % right does not decrease by 1 since they are ordered in
         % ascending sequences hence several more rotations need to be
         % skipped
% $$$         rpos
         
% $$$          % This extra assignment can be used to track if all
% $$$          % annihilations proceed correctly, it marks which rotation is
% $$$          % annihilated in part i of the loop
% $$$          Gind(rpos,4)=i;
% $$$          Gind
% $$$          pause    
  
% $$$          %------------- CHECK correctness---------------
% $$$          A=ConsMatLeft(Grot,Gind,R);
% $$$          eigA=eig(A);
% $$$     
        
         
         % The rotation marked for annihilation is found in position rpos
         Giv=[Grot(1,rpos) Grot(2,rpos); -conj(Grot(2,rpos)) conj(Grot(1,rpos))];
         
         % Application on the left, corresponds to simply setting the
         % rotation corresponding to G equal to the identity
         Grot(:,rpos)=[1;0];
         
         % Apply the transformation G to the upper triangular matrix R,
         % and recover it on the right
         gra=Gind(rpos,1);
         %R([Gind(rpos,1),Gind(rpos,2)],:)=Giv*R([Gind(rpos,1),Gind(rpos,2)],:);
         R(gra:gra+1,gra:n)=Giv*R(gra:gra+1,gra:n);
         
         % Bring the rotation to the right
         %[c,s,r]=Givens(R(Gind(rpos,2),Gind(rpos,2)),R(Gind(rpos,2),Gind(rpos,1)));
         [c,s,r]=Givens(R(gra+1,gra+1),R(gra+1,gra));
         Giv=[conj(c), s; -conj(s), c];
         %R(:,[Gind(rpos,1),Gind(rpos,2)])=R(:,[Gind(rpos,1),Gind(rpos,2)])*Giv;
         R(1:gra+1,gra:gra+1)=R(1:gra+1,gra:gra+1)*Giv;
         G=[c;-s]; % Is the hermitian conjugate of Giv, to continue
                   % working with, this rotation need to be applied on the
                   % left of the unitary matrix.
    
        
         for k=1:j-1
           
           % to take the correct rotations for shifting through, a new
           % index is needed.
           % see also the next part, this indexing is closely related
           
           % Perform the Shift-through operation
           [Grot(:,lspos2),Grot(:,lspos1),G]=ST(G,Grot(:,lspos2),Grot(:,lspos1));
           
           % Inside the chasing we always have to skip an entire sequence
           % the lenght of the current sequence if k=1 equals n-sl
           % but then the next sequence has one position less
           % so for k=2 we get a lenght n-sl-k+1
           % but we also get down one position for performing the fusion!
           lspos2=lspos2+n-sl-k; % brief for lspos2+n-sl-k+1-1;
           lspos1=lspos2+1; 
       
         end
         
         % The fusion takes place with the rotation in position lspos1
         %disp('Fusion with')
         %lspos1
         Grot(:,lspos1)=Fusion(G,Grot(:,lspos1));
         
         % Update these positions, this is easy in this case, since it is
         % always simply lpos+j due to the ordering of the rotations in
         % ascending sequences
         lspos2=lpos+j-1;
         lspos1=lpos+j;
        
% $$$          %--------- Correctness Check -------------------
% $$$          % Compare before and after the similarity operation
% $$$          disp('Temporary comparison of correctness: right')
% $$$          [eig(ConsMatLeft(Grot,Gind,R)),eigA]
% $$$          pause
% $$$                   
         
         
         
         % Once we are annihilating an new sequence from the right,
         % depending on how many are already gone, we need extra steps.
         % j indicates that everytime the jump increases.
         % sr-1 is the fixed number of extra rotations that need to be
         % skipped, once on has passed some sequences on the right.
         rpos=rpos-j-(sr-1);
           
       end
         
       % Increase the identifier for sequences from the right
       sr=sr+1;

       % Identify the new starting position
       rm=rm-sr;
       rpos=rm;
    end  
  end
  
  
  % Everything is finished, but now we clean up the sequences of
  % rotations, by removing all rotations equal to the identity.
  i=1;
  while (i<=size(Gind,1))
    if(Grot(2,i)==0)
      Grot(:,i)=[];
      Gind(i,:)=[];
    else
      i=i+1;
    end
  end

  % Now we have to shift the orders of the rotations performed
  mp=min(Gind(:,3));
  Gind(:,3)=Gind(:,3)-mp+1;
  
