function [bootp,wald]=blockbootstrap(y,isfe,blocksize,x1,x2,x3,x4);
% Block-bootstrap for robust p-values in panel regressions
% Bauer, Rudebusch, Wu (2014, AER) Comment on ``Term Premia and
% Inflation Uncertainty: Empirical Evidence from an International Panel Dataset'' 
%
% This code was generously provided to us by Jonathan Wright.

%Percentile-t confidence interval
bigt=length(y);
nblocks=ceil(bigt/blocksize);

%isfe=0 means pooled, no fixed effects
%isfe=1 means fixed effects
%isfe=2 means a different slope for each country; Wald test is for
%hypothesis that these are all the same

if nargin==4; [bhat,vcov]=panelreg(y,isfe,x1); end;
if nargin==5; [bhat,vcov]=panelreg(y,isfe,x1,x2); end;
if nargin==6; [bhat,vcov]=panelreg(y,isfe,x1,x2,x3); end;
if nargin==7; [bhat,vcov]=panelreg(y,isfe,x1,x2,x3,x4); end;

%if isfe==2;
%    k=length(bhat)/2;
%    bigr=diag(ones(2*k,1),0)+diag(-ones((2*k)-1,1),1); bigr=bigr(k+1:end-1,:);
%    rhat=bigr*bhat;
%    wald=rhat'*inv(bigr*vcov*bigr')*rhat;
%end;

rand('seed',123); bbdraws=1000;
for imc=1:bbdraws;
    if bigt==nblocks*blocksize;
        g=kron(blocksize*floor(rand(nblocks,1)*nblocks),ones(blocksize,1))+kron(ones(nblocks,1),[1:1:blocksize]');        
        else;
        g=kron(blocksize*floor(rand(nblocks,1)*(nblocks-1)),ones(blocksize,1))+kron(ones(nblocks,1),[1:1:blocksize]');
        g=g(1:bigt);
    end;
    if nargin==4; [bhatboot,vcovboot]=panelreg(y(g,:),isfe,x1(g,:)); end;
    if nargin==5; [bhatboot,vcovboot]=panelreg(y(g,:),isfe,x1(g,:),x2(g,:)); end;
    if nargin==6; [bhatboot,vcovboot]=panelreg(y(g,:),isfe,x1(g,:),x2(g,:),x3(g,:)); end;
    if nargin==7; [bhatboot,vcovboot]=panelreg(y(g,:),isfe,x1(g,:),x2(g,:),x3(g,:),x4(g,:)); end;
    tstatboot(:,imc)=(bhatboot-bhat)./sqrt(diag(vcovboot));
    if isfe==2;
    waldboot(imc)=((bigr*bhatboot)-rhat)'*inv(bigr*vcovboot*bigr')*((bigr*bhatboot)-rhat);
    end;
end;
tstatboot=sort(tstatboot')';
tstat=bhat./sqrt(diag(vcov));
for i=1:length(bhat);
bootp(i,1)=2*min(mean(tstat(i)<tstatboot(i,:)),mean(tstat(i)>tstatboot(i,:)));
end;

%if isfe==2; wald=[wald mean(wald<=waldboot)]; end;