function [ beta_lambda_vec_vc, se_beta_lambda ] = beta_lambda_vc( param, par_var, analysis, excess_returns, factors, c_fac)
% Auxiliary procedure for two-pass regressions in a_T * G_T = 0 setup:
% Returns the variance-covariance matrix of the vectorized matrix
% beta_lambda (vectorization by vertically concatenating its rows) and the
% standard eroors of the matrix beta_lambda computed. 

% The input variables are beta_lambda by the function get_beta_lambda.m and
% the variance-covariance matrix of the parameter estimates coming for the
% var_GMM.m function. We apply the delta method to compute the
% variance-covariance matrix.

% This input is given by the asymptotic vc-matrix which has to be divided
% by the number of observations

T=size(excess_returns,1);
N=size(excess_returns,2);
K=size(factors,2);


%% 1.) vectorize beta_lambda matrix

func=@(param)get_beta_lambda_vec( param, analysis, excess_returns, factors, c_fac );

[jacobi,~]=jacobianest(func,param);

beta_lambda_vec_vc=jacobi*par_var*jacobi'/T;
% vector of standard errors is read out and reshaped to correspond to the
% structure of beta_lambda: rows equal to number of factors, columns is
% number of test assets

% the standard errors are the square roots of the main diagonal of the
% matrix
if analysis==2
    
    se_beta_lambda=reshape(sqrt(diag(beta_lambda_vec_vc)),[N,K])';
    
elseif analysis==7
    
    se_beta_lambda=reshape(sqrt(diag(beta_lambda_vec_vc)),[N,c_fac])';
    
end


end

