%Michal Paluch, Alois Kneip, and Werner Hildenbrand,
%"Individual vs. Aggregate Income Elasticities for Heterogeneous Populations", Journal of Applied Econometrics, forthcoming

%This code collects the estimation and bootstrap results and writes it into tables shown in the paper

function T = final_resultstable(c);

T = [];
for cat = c,
    for year = 74:93;
        infile = sprintf('E:/phk/results/phk_final_%d_%d.txt',cat,year);
        d = dlmread(infile);  %
        
		bsfile = sprintf('E:/phk/results/phk_finalbs_summary_%d_%d.txt',cat,year);
		bs = dlmread(bsfile,'\t'); % File contains: [MLR,mLR,mHM,bias,mHMb] for each bootstrap replication
		
		%Estimates for the true sample
		mHM = mean(d(,11));
        mLR = mean(d(,13));
        MLR = mean(d(,14))/mean(exp(d(,1)));
        covmat = cov(exp(d(,1)),d(,11))/mean(exp(d(,1)));
        bias = covmat(2,1); 
		mHMb = mean(d(,11)./d(,12)) 
           
        %Standard deviations of the estimates 
		diffcov = bias - (bs(:,4) + bias - mean(bs(:,4)));
        diffmHM = mHM - (bs(:,3) + mHM -mean(bs(:,3)));
		diffmHMb = mHMb - (bs(:,5) + mHMb -mean(bs(:,5)));
        diffmLR = mLR - (bs(:,2) + mLR - mean(bs(:,2)));
        diffMLR = MLR - (bs(:,1) + MLR - mean(bs(:,1)));
		semHM = std(diffmHM);
		semHMb = std(diffmHMb);
        semLR = std(diffmLR);
        seMLR = std(diffMLR);
        sec = std(diffcov);
        
		% 95 percent confidence intervals for the covariance term
		lb = bias - quantile(diffcov,0.975);
        ub = bias - quantile(diffcov,0.025);
        T = [T;MLR,seMLR,mLR,semLR,mHM,semHM,bias,sec,lb,ub]; %Output as in the tables in the paper
    end
    
	%Now Wilcoxon Tests for equality
    [ct,ctp] = signrank(T(:,7)); %Test whether the covariance term is zero
    [mt,mtp] = signrank(T(:,1),T(:,3)); %Test whether betaagg = betamean
    [mht,mhtp] = signrank(T(:,1),T(:,5)); %Test whether betaagg = mean(individual from HM-approach)
    m = mean(T);
    T = [T; m;99,99,mt,99,mht,99,ct,99,99,99];
    dlmwrite(sprintf('testtable_%d.txt',cat),T,'\t');
end