function [momm,wtmat,maxq,pos_vec] = wtm_rm_noskew_opt(dt,optwt)

% Original program comes from Ruge Murcia's website and is named wtm
% We modified the program in three ways:
% 1) droppped skewness 
% 2) chose optimal window for bartlett kernel
% 3) normalized variances and correlations to have similar units so as to
%    reduce the condition number of the weighting matrix
 
% Moments
nob = size(dt,1); % number of observations 
nvar = size(dt,2); % number of variables
 
% Variances only (no covariances)
% for i = 1:nvar
%     if (i==1)
%         vars = dt(3:nob,i).*dt(3:nob,i);
%     else
%         vars = [vars dt(3:nob,i).*dt(3:nob,i)];  
%     end
% end
 
% Variance and covariances
vars = [];

pos_vec = [];
for i = 1:nvar
    for j = i:nvar
            pos_vec = [pos_vec; i j];
            if (i==j)
                vars = [vars dt(2:nob,i).*dt(2:nob,j)];
            else
                vars = [vars dt(2:nob,i).*dt(2:nob,j)/(sqrt(var(dt(2:nob,i),1))*sqrt(var(dt(2:nob,j),1)))];
            end
    end
end

autoc1 = dt(2:nob,:).*dt(1:nob-1,:)./(kron(var(dt,1),ones(nob-1,1)));
 

momm = [mean(vars)';mean(autoc1)'];
 



% Weighting matrix
if optwt > 0 % weigthing matrix is the optimal or its diagonal %
    % find optimal bandwidth
    maxq = optbandw(momm, 'bartlett');
    
    nob = size(vars,1)+1;
    wm = (vars-(ones(size(vars,1),1)*mean(vars)))';
    wm = [wm;(autoc1-(ones(size(autoc1,1),1)*mean(autoc1)))'];
    wtmat = wm*wm';
    wtmat = wtmat/(nob-1);
    for iim = 1:maxq
        kapg = wm(:,iim+1:nob-1)*wm(:,1:nob-1-iim)';
        kapg = kapg + kapg';
        kapg = kapg/(nob-1);
        wtmat = wtmat + (1-iim/(maxq+1))*kapg;
    end
    if optwt == 1 % weigthing matrix is the diagonal of the optimal one %
        wtmat = diag(wtmat);
        wtmat = eye(size(wtmat,1)).*(wtmat*ones(1,size(wtmat,1)));
    end
else % weigthing matrix is the identity matrix %
    wtmat = eye(size(momm,1));
end
