%  QRSS    Performs on step of QR without shift on a semiseparable matrix
%  
%          [G,d]=QRSS(G,d)
%          Performs one step of QR without shift on the semiseparable
%          matrix represented with Givens and vector representation in
%          order O(n) operations. 
%         
%
%          Software of the MaSe - Group
%          mase-at-cs.kuleuven.ac.be
%          Revision Date: 16/12/2003

function [G,d]=QRSS(G,d)
 
  if (isempty(d))
    d=[];
    G=[];
  else
    [G,d]=CRep(G,d);
    [G,d]=SR(G,d);
  end
  




%---------------------------------------------------------------
% This function will change the representation
% of the semiseparable matrix from top to bottem
% to the representation which will start
% to build from the bottem to the top in fact one
% step of QR without shift is performed on the matrix
%
% [G,d]=CRep(G,d)

function [Gnew,dnew]=CRep(G,d)

  % the new representation 
  % will be stored in Gnew and
  % dnew
  % this can clearly be seen as an
  % easy O(n) algorithm 

  Gnew=[];
  n=length(d);
  
  % initialization
  dnew(1)=d(n);  

  for i=n:-1:2
    % initial parameter settings
    c=G(1,i-1);
    s=G(2,i-1);
    dwork=dnew(n-i+1);

    % updating the diagonal
    dnew(n-i+1)=-s^2*d(i-1)+c*dwork;
    dnew(n-i+2)=s*(c*s*d(i-1)+s*dwork)+c*d(i-1); 

    % updating the givens
    Gnew(1:2,n-i+1)=[c ; s]; 
  end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

  n=length(d);  
  
  if n~=1
    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;
  else
    G=[];
    d=d(1);
  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
