%  TransLeft Transfers rotations from right to left through an upper
%            triangular matrix R 
%
%    [Glrot,Glind,Rl]=TransfLeft(Grot,Gind,R)
%    Grot Gind R input where the rotations are located on the right of R
%    Glrot Glind Rl 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 [Glrot,Gind,R]=TransfLeft(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.

  % 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
      
    % Create the variables
    Glrot=[];
    
    % Start the transferring procedure
    for i=1:size(Gind,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)])=R(:,[Gind(i,1),Gind(i,2)])*G;
      
      % Reconstruct the rotation on the left
      [c,s,r]=Givens(R(Gind(i,1),Gind(i,1)),R(Gind(i,2),Gind(i,1)));
      G=[c s; -s' c'];
      R([Gind(i,1),Gind(i,2)],:)=G*R([Gind(i,1),Gind(i,2)],:);
      
      % Assign the values to the new Glrot and Glind
      Glrot(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.
      %Glind(i,1)=Gind(i,1);
      %Glind(i,2)=Gind(i,2);
      %Glind(i,3)=Gind(i,3);
      
    end
    
    % ---> This is not done <--- In fact it is assumed.
    % Make R explicitly upper triangular again.
    % R=triu(R);
  
  end
    
