function ac = ac_boot(var,k,n,conf)

%ac_boot    Calculates autocorrelations with bootstrapped error bands
%   cc_boot(VAR,K,N,CONF) calculates autocorrelations between VAR_t and 
%     VAR_t-1,...,VAR_t-K, for N bootstrapped samples, and outputs 
%     median values along with error band at significance CONF.
%
%   VAR = Tx1 data vector. 
%   K = number of leads and lags.
%   N = number of boostrap replications.
%   CONF = significance of reported error band.  Must be between 0 and 1.
%
%   CC = K-by-3 matrix of calculated statistics
%     Row i gives correlation between VAR_t and VAR_t-i.
%     Col 1 gives lower boundary of error band.
%     Col 2 gives median values across the bootstrapped samples.
%     Col 3 gives upper boundary of error band.

t = size(var,1);
var = var-mean(var);
var_mat = repmat(var,1,n);

boot_repl = zeros(k,n);
for i = 1:k
     draw = randi(t-i,t-i,n);
     var0_lg = var_mat(draw+i);
     var_lg = var_mat(draw);
     boot_repl(i,:) = diag(corr(var0_lg,var_lg));
end
boot_repl = sort(boot_repl,2);
low = round(n*(1-conf));   
high = round(n*conf);
ac = zeros(k,3);
ac(:,1) = boot_repl(:,low);
ac(:,2) = median(boot_repl,2);
ac(:,3) = boot_repl(:,high);

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