function cc = c_cor(var1,var2,k)

%c_cor    Calculates cross-correlations for multiple variables
%   c_cor(VAR1,VAR2,K) calculates correlations between each column of 
%     VAR1_t and the corresponding columns of VAR2_t-k, k = -K,-K+1,...,K.
%
%   VAR1, VAR2 = TxN data vectors. 
%   K = number of leads and lags.
%
%   CC = (2*K+1)-by-N matrix of calculated statistics
%     Row i, col j gives correlation between VAR1_t,j and VAR2_t+(K+1-i),j.

if size(var1) ~= size(var2)
    error('Data vectors must be same size')
end
n = size(var1,2);
var1 = bsxfun(@minus,var1,mean(var1));
var2 = bsxfun(@minus,var2,mean(var2));
%var1 = var1-mean(var1);    %Works on newer versions
%var2 = var2-mean(var2);

cc = zeros(2*k+1,n);
for i = 0:k
     var1_ld = var1(1:end-i,:);
     var2_ld = var2(i+1:end,:);
     var1_lg = var1(i+1:end,:);
     var2_lg = var2(1:end-i,:);
     cc(k+1-i,:) = diag(corr(var1_ld,var2_ld));
     cc(k+1+i,:) = diag(corr(var1_lg,var2_lg));
end

%                                               G. Ramey - UCSD - 4/18/2019
