clear all; %#ok<CLALL>
close all;
clc;
cd(fileparts(matlab.desktop.editor.getActiveFilename));


CurrFileName = 'RActual_SmallSim';
GFEVcHorizon = 1;
TotalNumGibbsDraws = 6000;
NumFactorsK = 2;
BurnInPeriod = 4000;



%Load the data
NetworkName = strcat(CurrFileName,'_H',num2str(GFEVcHorizon),'_Draws',num2str(TotalNumGibbsDraws));
warning('off'); TickerMetadata = readtable(strcat(CurrFileName,'_Metadata.csv')); warning('on');
load(strcat('.\Output\',NetworkName,'.mat')); %#ok<LOAD>

%Calculate medians across draws after burn in period
    DrawsToKeep = EstimatedNetwork.FDraws(:,:,BurnInPeriod+1:end);
    FDraws_Medians = median(DrawsToKeep,3);

    DrawsToKeep = EstimatedNetwork.RAtoRA_Firm(:,:,BurnInPeriod+1:end);
    RAtoRA_Firm_Medians = median(DrawsToKeep,3);

    DrawsToKeep = EstimatedNetwork.RIFtoRAF(:,:,BurnInPeriod+1:end);
    RIFtoRAF_Medians = median(DrawsToKeep,3);

    DrawsToKeep = EstimatedNetwork.RAtoRA(:,:,BurnInPeriod+1:end);
    RAtoRA_Medians = median(DrawsToKeep,3);

    DrawsToKeep = EstimatedNetwork.RItoRA(:,:,BurnInPeriod+1:end);
    RItoRA_Medians = median(DrawsToKeep,3);

%Save connections matrices to CSV
NamesList = [];
for ii = 1:1:NumFactorsK
    NamesList = [NamesList; strcat("F",int2str(ii))];
end

FDraws_Medians_Table = array2table(FDraws_Medians);
FDraws_Medians_Table = renamevars(FDraws_Medians_Table,1:width(FDraws_Medians_Table), NamesList);
writetable(FDraws_Medians_Table,strcat('.\Output\','FDraws_Medians.csv'),'WriteRowNames',true);

NamesList = [string(TickerMetadata.CleanTicker)];

RAtoRA_Firm_Medians_Table = array2table(RAtoRA_Firm_Medians);
RAtoRA_Firm_Medians_Table = renamevars(RAtoRA_Firm_Medians_Table,1:width(RAtoRA_Firm_Medians_Table), NamesList);
RAtoRA_Firm_Medians_Table.Properties.RowNames=NamesList;
writetable(RAtoRA_Firm_Medians_Table,strcat('.\Output\','RAtoRA_Firm_Medians.csv'),'WriteRowNames',true);

for ii = 1:1:NumFactorsK
    NamesList = [NamesList; strcat("F",int2str(ii))];
end
RIFtoRAF_Medians_Table = array2table(RIFtoRAF_Medians);
RIFtoRAF_Medians_Table = renamevars(RIFtoRAF_Medians_Table,1:width(RIFtoRAF_Medians_Table), NamesList);
RIFtoRAF_Medians_Table.Properties.RowNames=NamesList;
writetable(RIFtoRAF_Medians_Table,strcat('.\Output\','RIFtoRAF_Medians.csv'),'WriteRowNames',true);

disp('Done!');