function [n] = returnnforsigmag2(sigmagsq)  % Remember you have to specify Pt as well, and make sure sigmagsq > Pt/Pshannon

global Pt;
global log10pe;
global sigmagsq2
global R;

max_iter = 15;
sigmagsq2 = sigmagsq;

%log10pe

%R = 1/3;

sigmaPsq = 1;

Pshannon = 2^(2*R)-1;

Cg = 0.5*log2(  1  +  Pt/sigmagsq  );

deltag = 1 - Cg/R;

if deltag<0
    
    disp('delta(G) negative');
    Cg
    sigmagsq
    deltag
end

logpe = log10pe* log(10);

hbinvdeltag = hbinv(deltag);

%epsilon =  (3 + 4*log(2) + 4*log(1/hbinvdeltag) )*sigmagsq;  

%epsilon fixed now.

%epsilonprime = epsilon/sigmagsq;

div = 0.5*( sigmagsq  -1  - log(sigmagsq)   );


epsilonprime1 = 0;
epsilonprime2 = 2*log(2/hbinvdeltag);





for i = 1:max_iter

    epsilonprime = (epsilonprime1 + epsilonprime2)/2;
    
    ntemp =   log(2/hbinvdeltag) /  (   0.5*epsilonprime  - 0.5*log(1+epsilonprime)  );

    if logpe > log(hbinvdeltag/2) - 0.5*ntemp*epsilonprime*(sigmagsq-1) - ntemp*div % The pe condition is satisfied; n can be made larger
    
        epsilonprime1 = epsilonprime;

    else
    
        epsilonprime2 = epsilonprime;

    end
    
end

if ntemp < min([28, 29-100*(sigmagsq-1), (2/(sigmagsq-1))^(5/9), 0.45/(sigmagsq-1) - 0.6])
    
    ntemp = 1;
    
end


epsilonprime;
n = - max(ntemp,1);

%REmember to return negative value for n