function x = fixcov(x)
% fixcov  [Not a public function] Remove numerically negative diagonals from covariance matrices.
%
% Backend IRIS function.
% No help provided.

% -IRIS Toolbox.
% -Copyright (c) 2007-2012 Jaromir Benes.

%**************************************************************************

tol = getrealsmall('mse');

% Unfold `x` in 3rd dimension. This is to handle 4-th and higher
% dimensional matrices without having to detect the exact structure of
% dimensions.
xsize = size(x);
x = x(:,:,:);

realx = real(x);
imagx = imag(x);
for i = 1 : size(x,3)
   % Set very small or negative entries to zero.   
   index = abs(diag(realx(:,:,i))) < tol;
   if any(index)
      realx(index,index,i) = 0;
   end
   index = abs(diag(imagx(:,:,i))) < tol;
   if any(index)
      imagx(index,index,i) = 0;
   end
end
x = complex(realx,imagx);

% Get `x` back in shape.
x = reshape(x,xsize);

end
