%% Code to calibrate parameters for division level model


clear; 
clc;
addpath('\Model\Tables\CompEcon2017\CEtools')

format short g
% Import data
pre_data=xlsread('\Inputs for model.xlsx','pre','A2:f15');
post_data=xlsread('\Inputs for model.xlsx','post','A2:f15');

% Create parametr saving object
params = zeros(2,14,2);

% Loop over pre and post period
for pre = 1:2

if pre == 1 
data = pre_data;
else
data=post_data;
end

% Loop over industries
for option = 1:14

% Put parameters into relevant places

   selast = data(option,1);
   concen =data(option,2); 
   Markuptarget = data(option,3);                      % our target for aggregate markup
   p.xi         = 5;          % Pareto tail productivity
   p.sigma      = 1.0084;          % demand elasticity: match level of markups

    l_share = data(option,4);
    k_share = data(option,5);
m_share= data(option,6);

x            = [p.xi;   p.sigma];
 
lb           = [0;       0];  
ub           = [20;       20];

ftarget      = @(x) objective(x, Markuptarget, selast, concen,l_share, k_share, m_share );



options             = optimset('fminsearch');
options.Display     = 'iter';
options.TolX        = 1e-5;
options.MaxFunEvals = 200;

if selast>0.05
x                   = fminsearchbnd(ftarget, x, lb, ub, options);
 
% SAave outputs
params(:,option,pre) = x;
end
end
end

% export
writematrix(params(:,:,1), 'G:\Research\JonathanH\EMX 2022 Replication Package\out_div_pre.xlsx')
writematrix(params(:,:,2), 'G:\Research\JonathanH\EMX 2022 Replication Package\out_div_post.xlsx')
