clc;
clear;

% BPEA Fall 2013: The Decline in the U.S. Labor Share, Section IV
% Elsby, Hobijn, and Sahin
%
% This program calculates the (total) backward requirements of domestic value added
% for final demand in the U.S. economy for 1993-2010. It does so under two
% assumptions: (1) some goods and services are imported, (2) all final
% demand is domestically supplied.
%
% The difference between the results under these two assumptions can then
% is the amount of domestic value added that would have been produced under
% current factor prices and productivity levels if all imports were
% domestically supplied. It is a measure of the degree of import
% competition that a sector faces.

for iYear = 1993:2010

    disp( iYear );
        
    % Initializing the IOtables object for the year for which the
    % calculations are being done
    X = IOtables.IOYear( iYear );
    
    % Initializing the output matrices if the year is the first year
    if ( iYear == 1993 )
        
        NoInd = X.Settings.NoIndustries;
        
        VA_Out = zeros(NoInd,18);
        VA_Dom_Out = zeros(NoInd,18);
        Steps_Out  = zeros(NoInd,18);
        Steps_Dom_Out = zeros(NoInd,18);
        TotVA_Out = zeros(NoInd,18);
    end
    
    FD = X.Matrices.InitialFD;
    [ VA , M , VA_Dom ] = X.SupplyChain.BackwardRequirements( FD , 0 );
    [ Forward , Forward_Dom , Backward , Backward_Dom ] = X.SupplyChain.Length;
    VA_Out(:,iYear-1992) = VA;
    VA_Dom_Out(:,iYear-1992) = VA_Dom;
    Steps_Out(:,iYear-1992) = Backward((NoInd+1):(2.*NoInd),1);
    Steps_Dom_Out(:,iYear-1992) = Backward_Dom((NoInd+1):(2.*NoInd),1);
    TotVA_Out(:,iYear-1992) = X.Matrices.TotVA;
    
end

% Writing the output to text files that we load into Excel
OutputFile = 'C:\Bart\Research\Brookings2013\Progs\MATLAB\Output\TotVA_Out.xlsx';
xlswrite(OutputFile,TotVA_Out);

OutputFile = 'C:\Bart\Research\Brookings2013\Progs\MATLAB\Output\VA_Out.xlsx';
xlswrite(OutputFile,VA_Out);

OutputFile = 'C:\Bart\Research\Brookings2013\Progs\MATLAB\Output\VA_Dom_Out.xlsx';
xlswrite(OutputFile,VA_Dom_Out);

OutputFile = 'C:\Bart\Research\Brookings2013\Progs\MATLAB\Output\Steps_Out.xlsx';
xlswrite(OutputFile,Steps_Out);

OutputFile = 'C:\Bart\Research\Brookings2013\Progs\MATLAB\Output\Steps_Dom_Out.xlsx';
xlswrite(OutputFile,Steps_Dom_Out);