%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Author: Diana Stojanovic
%
%   Please send all questions and comments to the following e-mail address
%
%               dswongkaren AT gmail DOT com
%       (replace AT by @ and DOT by .)
% --------------------------------------------------------------------
%   This program calculates TFR and corresponding Support ratios and Fiscal support ratios 
%   in several fertility schedule scenarios
%       Replacement TFR
%       Intrinsic TFR
%       TFR that maximizes Support Ratio
%       TFR that maximizes Fisal support ratio
%       TFR that maximizes Consumption in low capital cost scenario
%       TFR that maximizes Consumption in high capital cost scenario
% --------------------------------------------------------------------

%--------------------------------------------------
% Gather necessary data; in default scenario, default profiles are assigned
Prep_DATA_S_Module

%--------------------------------------------------
%   Calculations for each country
%--------------------------------------------------
for ind_count =1:Ncountries 
    country = char(Pcountries(ind_count,:));
    country = peel_space(country)
    region = char(Pregions(ind_count,:));   % geographical or economic class

    AssignCountryData_S_Module          % profiles assigned for the currently processed country
    ProcessCountryData_S_Module         % some data preparation for each country
    
	%----------------------------------
	%   Observed (actual) variables 
	%----------------------------------
	TFR_act = sum(ASFR_1);
    Ro_act = femRatio*sum(ASFR_1.*L_f(1:numel(ASFR_1)))/100000;
	mu_act = mean_age(ages(ind_asfr), L_f(ind_asfr), ASFR_1(ind_asfr), 0);
	rho_act=0;
    
    [Ac_act, Ayl_act, A_act, SR_act, SRG_act, Nage_up_act] = ...
        Calculate_A_SR_combo(rho_act, ages, popul, c_prof, yl_prof, tgi_prof, tgo_prof, ageUp);

    %----------------------------------
	%   Intrinsic variables 
	%----------------------------------
	rho_int = log(Ro_act)/mu_act;
    
    [Ac_int, Ayl_int, A_int, SR_int, SRG_int, Nage_up_int] = ...
        Calculate_A_SR_combo(rho_int, ages, L, c_prof, yl_prof, tgi_prof, tgo_prof, ageUp);

    %----------------------------------
	%   Replacement variables 
	%----------------------------------
	Ro_rep = 1;
    TFR_rep = exp(-rho_int*mu_act)*TFR_act;
    
    [Ac_rep, Ayl_rep, A_rep, SR_rep, SRG_rep, Nage_up_rep] = ...
        Calculate_A_SR_combo(0, ages, L, c_prof, yl_prof, tgi_prof, tgo_prof, ageUp);

    %----------------------------------
	%   Optimized variables 
	%----------------------------------
	OptimizeSR_S_Module
    
    PrintCurrentCountryData_Table_entries(fids, region, Pyears(ind_count), country, TFR_act, TFR_rep, TFR_MSRG, TFR_MSR, TFR_PVC, TFR_GLD, SRG_int, SRG_rep, SRG_MSRG, SR_MSR, SR_GLD, SR_PVC) 
 
end
for Nfile = 1:numel(fids)
    fclose(fids(Nfile));
end
display('DONE!')

