Filename_Channel = input('Channel File Name: = ','s');
Filename_Parameters = input('Parameters File Name: = ','s');
%PeG = input('\epsilon = ');
Filename_Data = input('Data File Name: = ','s');
%Filename_Data = [Filename_Data '_PeG' num2str(PeG*10^3)];

M = 10;
T = 6;
B = 45;
B_ = mod(B,M);
b = (B-B_)/M;
k = 1;

if B_ <= M/2;
    disp('B_ <= M/2')
    if T <= b*(M-B_)/B_;
        disp('T small, R = T/T+b')
        R_Macro = T/(T+b)
        x = T+b;
        u = M*b;
        n = M*x - 2*u;
        R = (u+n)/(2*u+n+k*M)
    else
        disp('R = PEC')
        R_Macro = (M*(T+b+1) - B)/(M*(T+b+1))
        x = T+b+1;
        u = B;
        n = M*x - 2*u;
        R = (u+n)/(2*u+n+k*M)
    end
else
    disp('B_ > M/2')
    if T == b;
        disp('T min, R = M-B_/M')
        R = (M-B_)/M;
    else
        disp('R = PEC')
        R_Macro = (M*(T+b+1) - B)/(M*(T+b+1))
        x = T+b+1;
        u = B;
        n = M*x - 2*u;
        R = (u+n)/(2*u+n+k*M)
    end
end
B_SCo = floor(M*T*(1-R)/R)
B_RLC = (1-R)*M*(T+1)
N_Macro = (k/(k+x))*(M*T+1)
Code_Parameters = var2struct(M,T,B,B_,b,k,x,u,n,R,B_RLC,B_SCo,N_Macro);
MySeed = 10;
DisplayEvery = 100;
PeGs = [0:1:10]*1E-3;

for index_PeG = 1:length(PeGs);
    PeG = PeGs(index_PeG);
    % Good State
    Long_Channel_Length = 1E6;
    Channel_Length = 1E4;
    Channel_Parameters_Good = var2struct(Long_Channel_Length,Channel_Length,PeG,MySeed);
    [Code_Losses_Good(index_PeG)] = Run_Macro_GoodState(Channel_Parameters_Good,Code_Parameters);
    % Bad State
    Channel_Parameters_Bad = load(Filename_Channel);
    Channel_Parameters_Bad.PeG = PeG;
    Channel_Parameters_Bad.MySeed = MySeed;
    Channel_Parameters_Bad.DisplayEvery = DisplayEvery;
    [Code_Losses_Bad(index_PeG)] = Run_Macro_BadState(Channel_Parameters_Bad,Code_Parameters);
end
save(Filename_Parameters,'Code_Parameters','Channel_Parameters_Bad','Channel_Parameters_Good','PeGs')
save(Filename_Data,'Code_Losses_Good','Code_Losses_Bad');
for index = 1:length(PeGs);
    
end

%% Plotting
Code_Losses_Bad_Array = cell2mat(struct2cell(Code_Losses_Bad.'))./(Channel_Parameters_Bad.Long_Channel_Length/M);
Code_Losses_Good_Array = cell2mat(struct2cell(Code_Losses_Good.'))./(Channel_Parameters_Good.Long_Channel_Length/M);
Code_Losses_Array = Code_Losses_Bad_Array + Code_Losses_Good_Array;

LineWidth = 3;
figure
semilogy(PeGs,Code_Losses_Array,'o-','LineWidth',LineWidth)
grid on
legend('Uncoded','Optimal Code','Optimal Robust Code','MDP','SCo','SCo (MDP)')
xlabel('\epsilon')
ylabel('P_{Loss}')
%title(Channel_Title)