%  TransRight Transfers rotations from left to right through an upper
%            triangular matrix R 
%
%    [Grrot,Grind,Rr]=TransfRight(Grot,Gind,R)
%    Grot Gind R input where the rotations are located on the right of R
%    Grrot Grind Rrl output represents the same matrix, but the rotations
%    are now located on the left
%
%    Software written by Raf Vandebril
%    raf.vandebril-at-cs.kuleuven.be
%    Revision Date: September 1, 2010
%



function [Grrot,Gind,R]=TransfRight(Grot,Gind,R)
  
  % It is not required that the upper triangular matrix R is nonsingular.
  % Operations performed on the upper triangular R create possible
  % perturbations. Only these perturbations will be removed. This might
  % result in rotations equal to the identity in case R is singular, but
  % that this not cause any problems.
  
  % Create the variables
  Grrot=[];  

  % Check if the input is not empty
  if ~isempty(Gind)
  
    % Order the routines in the negative order of application on the matrix  
    [SG,I]=sort(Gind(:,3));
    Gind=Gind(I,:); % Reorder the index storage
    Grot=Grot(:,I); % Reorder the rotations themselves
    
   
    % Start the transferring procedure
    for i=size(Gind,1):-1:1
      % Apply on the upper triangular matrix
      G=[Grot(1,i) Grot(2,i) ; -Grot(2,i)' Grot(1,i)'];
      R([Gind(i,1),Gind(i,2)],:)=G*R([Gind(i,1),Gind(i,2)],:);
      
      % Reconstruct the rotation on the right
      [c,s,r]=Givens(R(Gind(i,2),Gind(i,2)),R(Gind(i,2),Gind(i,1)));
      G=[conj(c), s; -conj(s), c];
      R(:,[Gind(i,1),Gind(i,2)])=R(:,[Gind(i,1),Gind(i,2)])*G;
    
      % Assign the values to the new Glrot and Glind
      Grrot(1:2,i)=[c;-s];
    
      % Since the positions do not change, Glind is just equal to Gind
      % Hence instead of executing these commands we return Gind.
      %Grind(i,1)=Gind(i,1);
      %Grind(i,2)=Gind(i,2);
      %Grind(i,3)=Gind(i,3);
      
    end
  
    % ---> This is not done <--- In fact it is assumed.
    % Make the matrix R explicitly upper triangular again.
    % R=triu(R)

  end
  
