% Convert pwt 9.1 to CSV file for rgdpna and population
% Rearrange

clear all;
small = 1.0e-10;

 
% Read Country Codes
[t1,country_code,t2] = xlsread('pwt91.xlsx','Data','A2:A12377');
[t1,country,t2] = xlsread('pwt91.xlsx','Data','B2:B12377');
[year,t1,t2] = xlsread('pwt91.xlsx','Data','D2:D12377');
[pop,t1,t2] = xlsread('pwt91.xlsx','Data','G22:G12377');  % First 20 years blank
pop = [NaN(20,1);pop];
[rgdpna,t1,t2] = xlsread('pwt91.xlsx','Data','S22:S12377'); % First 20 years blank
rgdpna = [NaN(20,1);rgdpna];


% Replace comma with space
country = strrep(country,',',' ');


n_countries = 182;
n_years = 68;

% Files
outfile_name = ['pwt91_pop_20191101.csv'];
fileID = fopen(outfile_name,'w');

% fprintf(fileID,'CountryCode,');
% for i = 1:n_countries;
%     j = (i-1)*n_years+1;
%     str1 = char(country_code(j));
%     str2 = char(country(j));
%     a=[num2str(i) ' ' num2str(j) ' ' str1 ' ' str2 '\n'];
%     fprintf(a);
% end;


fprintf(fileID,'CountryCode,');
for i = 1:n_countries;
    j = (i-1)*n_years+1;
    str = char(country_code(j));
    if i < n_countries
        ss = [str ','];
    else
        ss = [str '\n'];
    end
    fprintf(fileID,ss);
end;
fprintf(fileID,'Country,');
for i = 1:n_countries;
    j = (i-1)*n_years+1;
    str = char(country(j));
    if i < n_countries
        ss = [str ','];
    else
        ss = [str '\n'];
    end
    fprintf(fileID,ss);
end;

for t = 1:n_years;
    fprintf(fileID,'%4i,',year(t));
    for i = 1:n_countries;
      j = (i-1)*n_years+t;
      if isnan(pop(j)) == 0
        fprintf(fileID,'%.8g',pop(j));
      end
      if i < n_countries
        ss = [','];
      else
        ss = ['\n'];
      end
      fprintf(fileID,ss);
    end;
end;

outfile_name = ['pwt91_rgdpna_20191101.csv'];
fileID = fopen(outfile_name,'w');

% fprintf(fileID,'CountryCode,');
% for i = 1:n_countries;
%     j = (i-1)*n_years+1;
%     str1 = char(country_code(j));
%     str2 = char(country(j));
%     a=[num2str(i) ' ' num2str(j) ' ' str1 ' ' str2 '\n'];
%     fprintf(a);
% end;


fprintf(fileID,'CountryCode,');
for i = 1:n_countries;
    j = (i-1)*n_years+1;
    str = char(country_code(j));
    if i < n_countries
        ss = [str ','];
    else
        ss = [str '\n'];
    end
    fprintf(fileID,ss);
end;
fprintf(fileID,'Country,');
for i = 1:n_countries;
    j = (i-1)*n_years+1;
    str = char(country(j));
    if i < n_countries
        ss = [str ','];
    else
        ss = [str '\n'];
    end
    fprintf(fileID,ss);
end;

for t = 1:n_years;
    fprintf(fileID,'%4i,',year(t));
    for i = 1:n_countries;
      j = (i-1)*n_years+t;
      if isnan(rgdpna(j)) == 0
        fprintf(fileID,'%.8g',rgdpna(j));
      end
      if i < n_countries
        ss = [','];
      else
        ss = ['\n'];
      end
      fprintf(fileID,ss);
    end;
end;

