function [x,Cx,xsd] = cpaircov(x,Cx)

% CPAIRCOV	Covariance matrix of complex numbers
%	[X,CX] = CPAIRCOV(X,CX) replaces the neighbour complex conjugate 
%	pairs in the variable set X by their real and imaginary part. The 
%	corresponding covariance matrix CX is transformed accordingly.
%	Complex standard devation is returned in an optional third argument. 
%
% [+GenLib General Purpose Library+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

n = length(x); m = size(x);

J = eye(n); K = zeros(n,1);
k = 1;
while k <= n
 if imag(x(k)) ~= 0
  J(k+[0 1],k+[0 1]) = [1 1;-j j] / 2;
  K(k) = 1;
  k = k + 2;
 else
  k = k + 1;
 end
end

if m(1) == 1
 x = real(x * J.');
else
 x = real(J * x);
end

if nargin > 1
 Cx = real(J * Cx * J.');
 xsd = sqrt(diag(Cx));
 K = find(K); xsd(K) = xsd(K) + j*xsd(K+1); xsd(K+1) = xsd(K);
end
