function [bhat,vcov] = panelreg(y,isfe,x1,x2,x3,x4);  %Allows for up to 4 regressors
% Panel regression
% 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.

[bigt,k]=size(x1);
y0=reshape(y,bigt*k,1); x0=reshape(x1,bigt*k,1);
if nargin>3; x0=[x0 reshape(x2,bigt*k,1)]; end; 
if nargin>4; x0=[x0 reshape(x3,bigt*k,1)]; end;  
if nargin>5; x0=[x0 reshape(x4,bigt*k,1)]; end;  

if isfe==0; x0=[ones(bigt*k,1) x0]; end;
if isfe==1;
	for j=1:k;
	x0=[x0 zeros(bigt*k,1)];
	x0(((j-1)*bigt)+1:j*bigt,end)=ones(bigt,1);
	end;
end;
if isfe==2;
    for j=1:k;
	x0=[x0 zeros(bigt*k,1)];
	x0(((j-1)*bigt)+1:j*bigt,end)=ones(bigt,1);
	end;
    for j=1:k;
	x0=[x0 zeros(bigt*k,1)];
	x0(((j-1)*bigt)+1:j*bigt,end)=ones(bigt,1).*x0(((j-1)*bigt)+1:j*bigt,1);
	end;
    x0=x0(:,2:end);
end;

g=isnan(y0);
for i=1:size(x0,2); g=g+isnan(x0(:,i)); end;
y0=y0(find(g==0),:); x0=x0(find(g==0),:); 
[bhat,vcov]=olswhite(y0,x0);

bhat=bhat(1:nargin-2); vcov=vcov(1:nargin-2,1:nargin-2);