% BRLS  Retrieve the Givens Vector representation
%       of a lower triangular semiseparable matrix
%
%       [G,d]=BRLS(S)
%       Given as input a square lower triangular semiseparable matrix,
%       BRLS retrieves the Givens-vector representation of the lower
%       triangular semiseparable matrix S.
%
%
%       Software of the MaSe - Group
%       mase-at-cs.kuleuven.ac.be
%       Revision Date: 15/12/2003

function [G,d]=BRLS(S)
  
  n=size(S);
  if n==0
    G=[];d=[];G1=[];d1=[];
  elseif n==1
    G=[];d=S(1,1);G1=[];d1=[];
  else
      [G,d]=buildrep(S);
  end
  



function [G,D]=buildrep(S)
  
  n=size(S,1);
  D=[];
  G=[];
  
  % first we will simply calculate the norm of
  % the columns, this will correspond to the
  % vector elements in the vector Givens
  % representation
  for i=1:n
   D(i)=norm(S(i:n,i))*sgn(S(i,i));
  end
  
  % we calculate now the matrix which will give
  % the relation between the different rows in
  % the matrix in a stable way
  for i=1:n
    for j=1:i
      S2(i,j)=norm(S(i,1:j));
    end
  end
  
  % before we continue to calculate all the different
  % Givens transformations we will check if the signs of
  % the different rows match the signs of
  % the original matrix, if not we multiply them with
  % (-1), such that the Givens will still have the sign 
  % correspondance.
  % assume the first row to be positive
  startsign=1;
  for i=1:n-1
   S2(i+1,:)=S2(i+1,:)*startsign;
   [mx,pos]=max(abs([S(i,1:i),S(i+1,1:i)]));
   if (pos > i)
     if sgn(S(i,pos-i))~=sgn(S(i+1,pos-i))
       S2(i+1,:)=(-1)*S2(i+1,:);
       startsign=startsign*(-1);
     end
   else
     if sgn(S(i,pos))~=sgn(S(i+1,pos))
       S2(i+1,:)=(-1)*S2(i+1,:);
       startsign=startsign*(-1);
     end
   end
  end
  
  for i=n-1:-1:1
    Gh=givens(S2(i,i),S2(i+1,i));
    S2(i:i+1,1:i)=Gh*S2(i:i+1,1:i);
    G(1,i)=Gh(1,1);
    G(2,i)=Gh(1,2);
  end

  
  
  %%%%%%%%%%%%%%%%%%%
  % a useful function for testing the sign
  % here we assume that the sign of zero is positive
  %%%%%%%%%%%%%%%%%%%%
  
function s=sgn(x)
  if x<0
    s=-1;
  else
    s=1;
  end
  