function [CLTVarR,Rj] = ReMeDI2CLTVarR(logprice,j,kn,iN,NW)
%% Description:
%
%  Estimating the asymptotic variance of ReMeDI2 in a robust way 
%
%  Inputs:  j --- jth second moments
%           logprice --- the logarithmic price
%           kn --- tuning parameters of the estimator
%           iN --- number of sums in the asy variance
%           NW ---  if NW == 1, apply Newy-West kernel
%
%  Outputs: CLTVar --- an estimate of asym variance
%
%  Date: 22 Nov 2016
%
%  Author: Z. Merrick Li
%%
n = length(logprice);
y = logprice;
% estimate the j-th second moments
Rj = ReMeDI2(y,j,kn);

% prepare to compute the asymptotic (co)variances
dy2kn = y(1+3*kn+j:n) - y(1+j+2*kn:n-kn); % length = n-3*kn-j
dykn = y(1+2*kn:n-kn-j) - y(1:n-3*kn-j); % length = n-3*kn-j
prod_dy = -dy2kn.*dykn-Rj;
asymcov = [];

% compute the asymptotic (co)variances
if NW == 1
    Kel = 1 - [1:iN]/(iN+1);
    Kel = Kel';
else 
    Kel = ones(iN,1);
end
for i = 1:n-3*kn-j-iN
    Kelcov = prod_dy(i+1:i+iN).*Kel;
    vartemp = prod_dy(i)^2 + ...
	2*sum(prod_dy(i)*Kelcov);
    asymcov = [asymcov; vartemp];
end
CLTVarR = mean(asymcov);
end	