% GIVENSNCH Compute a Givens transformation matrix
%
%    [c,s,r] = GIVENSCH(x,y) returns the cosine and sine of the complex
%    Givens rotation matrix and the resulting norm r.
%    
%        | c       s       |                  | x |     | r |
%    G = |                 |   such that  G * |   |  =  |   |
%        |-conj(s) conj(c) |                  | y |     | 0 |
% 
%    where c, s are complex, and c^2 + |s|^2 = 1. 
%    The r is real
%
%    Software of the MaSe - Group
%    mase-at-cs.kuleuven.ac.be
%    Revision Date: 21/06/2007

function [c,s,r] = GIVENSNCH(x,y);

   if (y == 0),
      c = 1; s = 0; r = x;
   else
      if (abs(x) >= abs(y))
         %disp('Case 1')
         t = y/x; r = sqrt(1 + abs(t)^2);
         c = 1/r;
         s = t'*c;
         r = x*r;
      else
         %disp('Case 2')
         t = x/y; r = sqrt(1 + abs(t)^2 );
         s = 1/r;
         c = t'*s;
         r = y*r;
      end
   end

   
   %% Unfortunately this Algorithm can output negative values of r,
   %% This is not consistent with our computations, we will identify the
   %% Givens transformations uniquely by outputting only positive real r
   %% In order to turn slightly the Givens transformation we will
   %% multiply the result with abs(x)
   
   if (x~=0)
     % First we turn the matrix, such that c is real
     %theta=conj(c)/abs(c);
     
     % Or we assume the r to be real
     theta=conj(sign(r));
     c=c*theta;
     s=s*theta;
     r=theta*r;
     
     
   end
   
   