% THIS CODE EXECUTES ALL NECESSARY SUBROUTINES IN MATLAB AND FORTRAN TO
% REPLICATE EXLER, LIVSHITS, MACGEE, TERTILT, 2024, JEEA
tic

clear all, close all

%% Setup
addpath('fullrun\','postprocessing\')
outfileName = 'NewOrderPlus.txt';           %executable output file name
outputTableName = 'output/tables.xlsx';     %excel file name
outputSheetName = 'output_collect';         %excel file sheet
stataInput = fullfile(pwd,'scfdata');       %SCF data for Stata
doFilePath = fullfile(pwd,'postprocessing','unusual_income.do');  %do file path Stata

outFolder = 'output/';                      %folder to collect all output

if ~isfolder(outFolder)
    mkdir(outFolder)
end

% Get standard colors
figure
coloruse = get(gca,'colororder');
coloruse = coloruse(1:2,:);  %1 - rational, 2 - behavioral
close

numCores = feature('numCores');         %number of physical cores
nOut = 56;                              %number of output vars
shareCollege = 0.38;                    %share college graduates

onlycollect = false;                     %only collects output files without solving model

% Generate ouput excel file: tables.xlsx
copyfile('postprocessing\tablestemplate.xlsx',fullfile(outFolder,'tables.xlsx'))

% Copy fortran code into fullrun folder
copyfile('fortrancode\PricingRevisedDown.exe',fullfile('fullrun','PricingRevisedDown.exe'))
copyfile('fortrancode\PricingRevisedDown with dump.exe',fullfile('fullrun','PricingRevisedDown with dump.exe'))

% Set up a parallel pool with the specified size
if isempty(gcp('nocreate')) && ~onlycollect
    % Prompt user for pool size
    userPoolSize = input(sprintf('Enter the desired number of parallel workers (1-%d): ', numCores));
    try
        userPoolSize = int8(userPoolSize);
    catch
        userPoolSize = NaN;
    end

    poolSize = min(userPoolSize, numCores);

    parpool(poolSize);

end

% Define directories
rootDir = fullfile(pwd);
runDir = fullfile(pwd, 'fullrun');

% Get a list of all subfolders that contain results from fortran executable
experimentFolders = dir(runDir);
experimentFolders = experimentFolders([experimentFolders.isdir]);
experimentFolders = experimentFolders(~ismember({experimentFolders.name}, {'.', '..'}));

%% Run fortran executable to generate all necessary model outcomes and all Tables

disp('Computing all experiments...');
run_experiments
disp(['time needed fullrun (mins) ',num2str(toc/60)])
%% Produce figures and Table A6
tic
disp('Calculating Type Score distributions...')
type_score_distributions
disp(['time needed type score distributions (mins) ',num2str(toc/60)])

tic
disp('Calculating Cross-Subsidization...')
cross_subsidization
disp(['time needed cross subsidization (mins) ',num2str(toc/60)])

tic
disp('Calculating Policy experiments...')
policyexperiments
disp(['time needed policy experiments (mins) ',num2str(toc/60)])

tic
disp('Calculating life cycle earning multipliers...')
lifecycleprofiles
disp(['time needed life cycle profiles (mins) ',num2str(toc/60)])

%% Produce Table A1
tic
disp('Calculating unusual income realizations in Stata...')
stataPath = findStataExecutable;

stataCommand = sprintf('"%s" /e do "%s" "%s" "%s"', stataPath, doFilePath, stataInput, fullfile(pwd,outFolder));

% Execute the command
[status, cmdout] = system(stataCommand);

% Check if the command executed successfully
if status == 0
    disp('Success!');
else
    disp('Error executing Stata .do file:');
    disp(cmdout);
end
disp(['time needed type score distributions (mins) ',num2str(toc/60)])



