%New code for AWGN channel for JSAC
function [sigmagopt,nmax] = maxnforptAndInterference2()%Pt,pe)

global Pt r TotalNoise lambda1 alpha1 Preceived;
global RChUse planck temp Wused Interference TotalNoise Preceived;


TotalNoise = planck*temp*Wused + Interference;



PRxshannon = TotalNoise*(2^(RChUse) - 1);

Preceived =  min(Pt,Pt*lambda1^alpha1/r^alpha1);

if PRxshannon >  Preceived

    disp('d (or, less likely, Pt) too small!');

    nmax = 1e8000;
    sigmagopt = -1;

else


    sigmagstart = Preceived/(2^(2*RChUse)-1); % The value of sigmagsq satisfying 0.5*log2(1+P/sigmagsq)=R

    sigmagend = sigmagstart*30 ; % if it is made too large, the optimizer misses the optimal value.

    [sigmagopt, minusnmax]=fminbnd(@returnnegn,sigmagstart,sigmagend);
    nmax = -minusnmax;
    nmax=max(1,nmax);
    
end




function [negn] = returnnegn(sigmagsq)


global RChUse  TotalNoise Preceived log10pe;
Cg = log2(1+ Preceived/sigmagsq);


pe = 10^log10pe;
deltag = 1- Cg/RChUse;

hbinvdeltag = hbinv(deltag);

a = 0.5 * (  sigmagsq/TotalNoise - 1 - log( sigmagsq/TotalNoise   )   );

b = ( 1.5 + 2 * log(2/hbinvdeltag)  )  *  (sigmagsq/TotalNoise -1);

c =  log(2* pe/ hbinvdeltag);

n = (-b + sqrt(b^2 - 4 * a * c)  )/ (2 * a);

negn = -n;
