%% Run this script first to optimise the HBS-EXIOBASE bridge
% Database: EXIOBASE 3.7

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all

% IO contains EXIOBASE - including the "IO" struct, "meta" struct (which can be found online at https://zenodo.org/record/3583071)
% as well as the taxes, transport and trade margins as well. For access to these, contact the EXIOBASE core team. 
load('IO_start.mat')

number_countries = length(meta.raw_countries);
countries=meta.raw_countries;
sectors=meta.labsZ(1:200,2);

% Generate HBS per capita demand (in mill EUR)
% SOURCE: import the data in coicop format (63 products - COICOP 1-3) 
% import means from the survey (having set negatives to missing)
ces_eur = xlsread('DIS_background_files.xlsx','per_CES_weighted','E3:BA65'); 
ces_meur = ces_eur/1000000;

% Generate EXIOBASE per capita demand (in mill EUR)
pop =table2array(IO.pop(:,3));
YHH_pp_cap = su_ypp./pop';

% set ces expenditure to zero in the countries where we would need to
% implement new bridges (DE) and (SE)
for i=1:size(ces_eur,2)
    for j=1:size(ces_eur,1)
        if i==6 || i==25
            ces_meur(j,i)=0;
        else
        end
    end
end

% The original bridge draws conceptual links between the HBS and EXIOBASE
% sectors, consulting the sectoral definitions
% TARGET: the per capita hhld demand in pp - YHH_pp_cap
bridge = xlsread('DIS_background_files.xlsx','bridge_ini','D3:GU65'); 

tic

CES=zeros(number_countries,length(sectors)); %the CES expenditure in the IO structure
for i=1:size(ces_eur,2)
    country_code = cell2mat(meta.raw_countries(i));
    if sum(ces_meur(:,i))>0
        new_bridge.(country_code) = adjust_bridge(bridge,ces_meur(:,i),YHH_pp_cap(:,i));
        ces_200.(country_code)=ces_meur(:,i)'*new_bridge.(country_code);
    else
        new_bridge.(country_code)=bridge;
        ces_200.(country_code)=ces_meur(:,i)'*new_bridge.(country_code);
     disp(meta.raw_countries(i))   
    end
    ces = ces_200.(country_code);
    CES(i,:) = ces;
end

toc

% Ypp expenditure from the surveys is thus bridged to 200 exiobase sectors
% Compare CES 200 to exio pp

CES_pp = CES';

clear ces_200 ces CES filename bridge ces_eur ces_eur_de ces_eur_se i j bridge_de bridge_se su

save new_bridge.mat