% SR Swap the representation of the semiseparable matrix
%        
%    [G,d]=SR(G,d)
%    Given a sequence of Givens transformations and a diagonal
%    the function will give the representation of the matrix in 
%    the other direction.
%    building direction will change from
%
%      |
%      |      to  a representation   <-----
%      V
%
%    or in the other directions.
%     
%
%    cosine and sine of the givens have to be stored in the following 
%    way
%     
%     G= | c(1)  c(2)  c(3) .. .. .. c(n-1) |
%        | s(1)  s(2)  s(3) .. .. .. s(n-1) |
%      
%     d= [d(1) d(2) .. ..  d(n)]
%
%
%
% 
%        Software of the MaSe - Group
%        mase-at-cs.kuleuven.ac.be
%        Revision Date: 16/12/2003


function [G,d]=SR(G,d)

  
  n=length(d);  
  
  if (n~=1 && n~=0)
    dnew(n)=G(1,1)*d(1);
    r=d(1);
    
    for i=1:n-2
      [c,s,r]=Givens1(G(2,i)*r,d(i+1));
      Gnew(:,n-i)=[s;c];
      dnew(n-i)=G(1,i+1)*r;
    end
    
    i=n-1;
    [c,s,r]=Givens1(G(2,n-1)*r,d(n));
    Gnew(:,1)=[s;c];
    dnew(1)=r;
    
    G=Gnew;
    d=dnew;
  end
%-----------------------------------------------
% needed functions for the main routine
%--------------------------------------

function [c,s,r] = Givens1(x,y);
%
%  computes c,s,r such that
%
%  [c  s] [x] = [r]
%  [-s c] [y]   [0]
%
%  with c*c + s*s = 1;
%
   if (y == 0),
      c = 1; s = 0; r = x;
   else
      if (abs(x) >= abs(y))
         t = y/x; r = sqrt(1 + t*t);
         c = 1/r;
         s = t*c;
         r = x*r;
      else
         t = x/y; r = sqrt(1 + t*t);
         s = 1/r;
         c = t*s;
         r = y*r;
      end
   end
