% BSSD   Build a  semiseparable plus diagonal matrix
%       
%       SSD=BSSD(G,d,diagonal)
%       Given a sequence of Givens transformations, a vector and a diagonal
%       the function constructs a symmetric semiseparable matrix plus
%       diagonal 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) |
%     
%       d= [d(1) d(2) .. ..  d(n)]
%
%
%       SSD=BSSD(G,d,G1,d1,diagonal)
%       Given two sequences of Givens vector representations, the
%       function constructs a semiseparable plus diagonal matrix whose strict upper
%       triangular part is represented with the Givens vector
%       representation G1 and d1, and whose lower triangular part is
%       represented with the representation G,d.
%
%
%       Software of the MaSe - Group
%       mase-at-cs.kuleuven.ac.be
%       Revision Date: 14/07/2004


function A=BSSD(G,D,G1,D1,diagonal)
  

  n=length(D);
  A=zeros(n,n);
  if n~=0
    A(1,1)=D(1);
    for i=1:n-1;
      % construction of the givens transformation
      Giv=[G(1,i) , -G(2,i);  G(2,i), G(1,i) ]; 
      A(i:i+1,:)=Giv*A(i:i+1,:);
      A(i+1,i+1)=D(i+1);
    end;
    
    if nargin==3  
      % this means we have a symmetric matrix
      A=A+tril(A,-1)';
      diagonal=G1;
    else
      A2=zeros(n,n);
      if n~=1
        A2(1,2)=D1(1);
        for i=2:n-1;
          % construction of the upper triangular part
          Giv=[G1(1,i-1) , G1(2,i-1);  -G1(2,i-1), G1(1,i-1) ]; 
          A2(:,i:i+1)=A2(:,i:i+1)*Giv;
          A2(i,i+1)=D1(i);
        end
      end
      A=A+A2;
    end;
  end;

  A=A+diag(diagonal);
