clear all
global log10pe;
global Pt;
global gamma;
global Ptoptfinal2 Rch Enode Rdata Rdec thermalNoise boltzmann T W R maxdeg Shlt;

Enode = 10e-12;
Rdata = 1.5e9;
Rdec = Rdata;
boltzmann = 1.38e-23;
NoiseFigure = 1;
T = 300*NoiseFigure;
W = 45e8;
thermalNoise = boltzmann*T*W;
pathlossexp = 3;
r = 5;
lambda = (1/200);
maxdeg =6;

Rch = Rdata/(2*W);
R =Rch;
pathloss = (r/lambda)^pathlossexp;

log10pevec =   [-0.5:-0.1:-5 -5.25:-0.25:-10 -11:-1:-32 -34:-3:-150];
gamma = Enode*Rdec/ (Rch*thermalNoise*pathloss);


for i = 1:length(log10pevec)
    

    
    log10pe = log10pevec(i)

    pe = 10^log10pe;
    ShannonLimit(i) = (qfuncinv( hbinv(1-Rch*(1-pe))  ))^2* pathloss * thermalNoise;
    Shlt = ShannonLimit(i)/ pathloss/ thermalNoise;
    
    [PtoptNormalized(i), PtotalminNormalized(i)] = findptopt2();
    Ptopt(i) = PtoptNormalized(i) * pathloss * thermalNoise;
%    Ptopt(i) = max(Ptopt(i),ShannonLimit(i));
    Ptotalmin(i) = PtotalminNormalized(i) * pathloss * thermalNoise;
%    Ptotalmin(i) = max(Ptotalmin(i),ShannonLimit(i));

    Optimal_transmit_power = Ptopt(i)
    Total_power = Ptotalmin(i)
    
end
figure;
semilogy(Ptotalmin,log10pevec);
hold on;
semilogy(Ptopt,log10pevec,'r');
semilogy(ShannonLimit,log10pevec,'k');
beep
