function Tableau_Final = FinalRes(type,MC)
% This function builds the final tables and extracts it to a LaTeX file

switch type
  case 'short'
    T = 50;
  case 'long'
    T = 100;
end
switch MC
  case 1
    target  = [1 -1 0 0.02];
    ptarget = 1.3431;
  case 2
    target  = [1 -2 0 0.02];
    ptarget = 1.8514; 
end
[~,~,Psample,~,~,~] = InitMonteCarlo(target,type);
target              = [target ptarget];

%% Load results
load(fullfile('../../Results/MonteCarlo',['Results' num2str(MC) '_CML' num2str(T) '.mat']))
CMLTab  = Tab;
load(fullfile('../../Results/MonteCarlo',['Results' num2str(MC) '_UML' num2str(T) '.mat']))
UMLTab  = Tab;

Target     = repmat(target([1:2 4:end]),1,2);
FTab       = [UMLTab(:,1:4) CMLTab(:,1:4)];

% Keep only the common valid replications over the 2 MC experiments
FinalTab = FTab;
for i = [1 5], FinalTab  = FinalTab(~isnan(FinalTab(:,i)),:); end

%% Calculate the true and the implied number of stockouts

% allocate memory
Nsample   = length(FinalTab);
NBstoCML  = NaN(Nsample,1);
NBstoUML  = NaN(Nsample,1);
NBstoTheo = NaN(Nsample,1);

for j = 1:Nsample
  Pobs           = Psample(j,:)';
  NBstoCML(j,1)  = length(find(Pobs>=FinalTab(j,8)));  % Number of stockouts implied by CML
  NBstoUML(j,1)  = length(find(Pobs>=FinalTab(j,4)));  % Number of stockouts implied by UML
  NBstoTheo(j,1) = length(find(Pobs>=ptarget));        % Number of theoretical stockouts
end

% Process Results
MeanTab    = nanmean(FinalTab);
SDTab      = nanstd(FinalTab);
Bias       = MeanTab-Target;
RMSE       = sqrt(Bias.*Bias+SDTab.*SDTab);

nb_discarded = size(Tab,1)-size(FinalTab,1);  % count the total number of discarded trials
display(nb_discarded)

FTabRes  = [MeanTab;SDTab;Bias;RMSE];
PTabRes  = [FTabRes(3,:)./Target.*100;FTabRes(4,:)./Target.*100];
PTabRes  = abs(PTabRes);
% Remove pstar
FTabRes  = FTabRes(:,[1:3 5:7]);
PTabRes  = PTabRes(:,[1:3 5:7]);


Tableau_Final  = array2table(FTabRes,...
                             'RowNames',{'Mean','St.dev.','Bias','RMSE'},...
                             'VariableNames',{'a' 'b' 'k' 'a1' 'b1' 'k1'}); 

%% Export Results in .tex
Res = {'Mean','Standard deviation','Bias','RMSE'};

fid = fopen(fullfile('..','..','Article','MCTables',['CompaMC' num2str(MC) 'FinalResultsML' num2str(T) '.tex']), 'w');
for i=1:2
  fprintf(fid,'%s',Res{i});
  for j=1:6
    if isnan(FTabRes(i,j))
      fprintf(fid,'&n.a.');
    else
      fprintf(fid,'&%4.4f',FTabRes(i,j));
    end
  end
  fprintf(fid,'\\\\ \n');
end

for i=3:4
  fprintf(fid,'%s',Res{i});
  for j=1:6
    if isnan(FTabRes(i,j))
      fprintf(fid,'&n.a.');
    else
      fprintf(fid,'&%4.4f',FTabRes(i,j));
    end
  end
  fprintf(fid,'\\\\ \n');
  for j =1:6 
    if isnan(PTabRes(i-2,j))
      fprintf(fid,'&--');
    else
      fprintf(fid,'&(%4.2f $\\%%$)',PTabRes(i-2,j));
    end
  end 
  fprintf(fid,'\\\\ \n'); 
end
fclose(fid);