function R = cov2corr(C,varargin)
% COV2CORR  [Not a public function] Autocovariance to autocorrelation function conversion.
%
% Syntax
% =======
%
%     R = covfun.cov2corr(C)
%     R = covfun.cov2corr(C,'acf')
%
% Backend IRIS function.
% No help provided.

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

% If called from within `acf` functions, std errors will be taken from
% the first page of each parameterisation. Otherwise, std errors will
% be updated for each individual matrix.
isacf = any(strcmpi(varargin,'acf'));

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

R = C;
realsmall = getrealsmall();
nalt = size(R,4);

for ialt = 1 : nalt
    for i = 1 : size(R,3)
        Ri = C(:,:,i,ialt);
        if i == 1 || ~isacf
            stdinv = diag(Ri);
            nonzero = abs(stdinv) > realsmall;
            stdinv(nonzero) = 1./sqrt(stdinv(nonzero));
            D = stdinv * stdinv.';
        end
        index = ~isfinite(Ri);
        Ri(index) = 0;
        Ri = D .* Ri;
        Ri(index) = NaN;
        R(:,:,i,ialt) = Ri;
    end
end

end