% BQ  Build a quasiseparable matrix
%       
%        A=BQ(G,v,d)
%        Given a sequence of Givens transformations and a diagonal
%        the function constructs a semiseparable matrix from it
%        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) |
%     
%        v= [v(1) v(2) .. ..  v(n)]
%
%
%
%        A=BQ(G,v,d)  OR  A=BQ(G,v,d,'tb')
%        will perform the givens in the direction from top to bottom.
%
%        A=BQ(G,v,d,'rl')
%        will perform the givens from right to left
%         
%        The diagonal elements are always from top left to bottom right
%
%        A=BQ(G,v,d,opt,verbose)
%        verbose=1 will print the direction of building the matrix
%        verbose=0 no info will be printed
%
%
%        Software of the MaSe - Group
%        mase-at-cs.kuleuven.ac.be
%        Revision Date: 12/10/2006


function Q=BQ(G,V,D,opt,verb)

  if not(exist('opt'))
    opt='tb';
  end
  if not(exist('verb'))
    verb=0;
  end
  
  
  % This piece will construct the strictly lower triangular part
  % of the quasiseparable matrix.
  n=length(D);
  Q=zeros(n,n);
  if n==0
    Q=[];
  elseif n==1;
    Q=D(1);
  elseif n==2
    Q=[D(1),V(1);V(1),D(2)];
  else
    if (opt=='rl')
      if verb
        disp('from right to left')
      end
      Q(n-1,n)=V(1);
      for i=n-1:-1:2;
        % construction of the givens transformation
        Giv=[G(1,n-i) , G(2,n-i); -G(2,n-i), G(1,n-i)]; 
        Q(i-1:i,:)=Giv*Q(i-1:i,:);
        Q(i-1,i)=V(n-i+1);
      end;
      Q=Q'+diag(D)+Q;
    elseif (opt=='tb') 
      if verb
        disp('from top to bottom')
      end
      Q(1,2)=V(1);
      for i=1:n-2;
        % construction of the givens transformation
        Giv=[G(1,i) , G(2,i); -G(2,i), G(1,i)]; 
        Q(:,i+1:i+2)=Q(:,i+1:i+2)*Giv
        Q(i+1,i+2)=V(i+1)
        %pause
      end;
      Q=Q'+diag(D)+Q;  
    else
      disp('ERROR UNKNOWN OPTION')
    end
  end


