% The correct code!!!
clear all;

global Rdata Rdec Rch W boltzmann temperature thermalNoise pathlossexp r lambda1;
global pathloss Enode degree pe pedesired dv dc iter;


dv = 3;
dc = 4;
W = 3e9;
pathlossexp = 3;
r = 10;
lambda1 = 1/200; % 3e8/60e9
boltzmann = 1.38065e-23;
temperature = 300;
Rdata = 1.5e9;
Rdec = Rdata;
Enode = 10e-12;
degree = 4;

Rch = Rdata/W;
thermalNoise = boltzmann * temperature * W;
pathloss = (r/lambda1)^pathlossexp;

log10pevec = [-1:-0.05:-10 -11:-0.1:-150];% -11:-0.5:-150];%[-0.05:-3:-62];%[-0.5:-0.05:-4,-4.25:-0.25:-6,-6.5:-0.5:-10,-11:-1:-40];

for i = 1:length(log10pevec)
    
    i

    log10pe = log10pevec(i);
    
    pe = 10^(log10pe);
    
    pedesired = pe;
    
    
    Ptvec = linspace(0,1,1000);
    
    for j = 1:length(Ptvec)
        
        Pttest = Ptvec(j);
        
        Totalpower(j) = CalcTotalPowerGivenP(Pttest);
        
    end
    
    [Ptotalminbrute(i),minindex(i)] = min(Totalpower);
    
    Ptoptbrute(i) = Ptvec(minindex(i));
    
    
    [Ptopt(i), Ptotalmin(i)] = fminbnd(@CalcTotalPowerGivenP,0.01,2,optimset('TolX',1e-100));
    
    iteropt(i) = iter;
    
%    Ptotalmin(i)
end

figure;
semilogy(Ptotalmin,log10pevec);% minimum total power
hold on;
semilogy(Ptopt,log10pevec,'r')%optimal transmit power
figure;
semilogy(iteropt,log10pevec)
save ldpcwaterslide.mat

beep;
