function makeConvergenceTables
%{
Make two tables showing convergence
one by region and one by country

Dick Startz
February 2019
%}

load('simulated3StateFuturesFrom2014Split');
[~,txt,~] = xlsread('Code-Country-Region.xlsx');
regions = txt(:,3);
nCountries = length(regions);

prob1970 = nan(nCountries,1);
prob2014 = nan(nCountries,1);

% find probabilities
iProb = 2;%convergent state
for iCountry = 1:nCountries
    firstOb = firstObForCountry(iCountry);
    lastOb = lastObForCountry(iCountry);
    prob2014(iCountry) = mean(S(lastOb,:)==iProb);
    if firstYearForCountry(iCountry) <=1970
        firstObToUse = firstOb + 1970 - firstYearForCountry(iCountry);
        prob1970(iCountry) = mean(S(firstObToUse,:)==iProb);
    end
end
t1 = table(prob1970,prob2014,firstYearForCountry,'RowNames',countryNames)

xlswrite('Convergence probability by country',countryNames,'A2:A175');
xlswrite('Convergence probability by country',...
    [prob1970,prob2014,firstYearForCountry],'B2:D175');
xlswrite('Convergence probability by country',regions,'E2:E175');

uniqueRegions = unique(regions);
nRegions = length(uniqueRegions);
regionProb1970 = zeros(nRegions,1);
regionProb2014 = zeros(nRegions,1);
sumRegionWeights1970 = zeros(nRegions,1);
sumRegionWeights2014 = zeros(nRegions,1);

for iRegion = 1:length(uniqueRegions)
    for iCountry = 1:nCountries
        if strcmp(uniqueRegions{iRegion},regions{iCountry})
            if ~isnan(prob1970(iCountry)) % some countries began later
                regionProb1970(iRegion) = regionProb1970(iRegion)...
                    + prob1970(iCountry)*popWeightROWLast(iCountry);
                sumRegionWeights1970(iRegion) = sumRegionWeights1970(iRegion)...
                    + popWeightROWLast(iCountry);
            end
            regionProb2014(iRegion) = regionProb2014(iRegion)...
                + prob2014(iCountry)*popWeightROWLast(iCountry);
            sumRegionWeights2014(iRegion) = sumRegionWeights2014(iRegion)...
                + popWeightROWLast(iCountry);
        end
    end
end
regionProb1970 = regionProb1970./sumRegionWeights1970; %renormalize
regionProb2014 = regionProb2014./sumRegionWeights2014;
t2 = table(regionProb1970,regionProb2014,'RowNames',uniqueRegions)

xlswrite('Convergence probability by region',...
    [regionProb1970,regionProb2014],'B2:C175');
xlswrite('Convergence probability by region',uniqueRegions,'A2:A175');
end

