function gres = gran_res(id,year,X,w)

% Create a balanced matrix of growth rates, where 0's fill in missing,
% which is ok b/c will sum over zeros and not count when taking averages

[h1,h2,ii]=unique(id);
[h1,h2,jj]=unique(year);

N=max(ii);
T=max(jj);

bigX=zeros(N,T);
bigX(sub2ind([N T],ii,jj))= X;

bigO=zeros(N,T);
bigO(sub2ind([N T],ii,jj))=1;
counts=sum(bigO,2);
mX=sum(bigX,2)./sum(bigO,2);
demeanX=(bigX-repmat(mX,1,T)).*bigO;

% Demeaned matrix which is N,T and create a (T_n - 1) to divide by 

Y = reshape(demeanX,N,T);

t = counts - ones(size(counts,1),1);
tt = repmat(t,1,T);
TT = reshape(tt,N,T);

Y = Y./sqrt(TT);

% Get weights aligned correctly

W = zeros(N,T);
W(sub2ind([N T],ii,jj))=w;

% Create Granular residual = W'Y, where diagonal will be residual using
% contemporaneous weights (actually residual), but we will want to sample
% over rows, where each row uses weights for a given year (e.g., row 1 =
% 1991 weights), but multiplies different year's residuals.

gres = W'*Y;