function [g,iter,iterint,lambda,WSC,Popt,BER] = ExpectedDiscretePerfectCSI2(gbar,K,w,Pbar,R,Eta)
w = w(:);
% [K,M,N] = size(G);
% G = mean(Gmat,3);
% Wtmp = ones(K,1)*w';
% W = repmat(Wtmp,[1,1,N]);
% lambdamin = K/log(2)*min(w)/(Pbar+sum(mean(max(1./G,[],2),3)));
% if lambda == 0
lambdamin = 0;
lambdamax = 2;
[x,fval,exitflag,output] = fminbnd(@(x) ExpectedDualDiscrete3(x,w,gbar,Pbar,R,Eta,K,0),lambdamin,lambdamax);
lambda = x;
iter = output.iterations;
% else
%   iter = 0;
% end;
[Theta, maxP, maxR, iterint]=ExpectedDualDiscrete3(lambda,w,gbar,Pbar,R,Eta,K,1);
% Popt = mean(sum(maxP),3);
% % ptot = sum(sum(sum(maxP)))/N;
% BER = 0.2*exp(-1.6*maxP.*Gtrue./max((2.^maxR-1),1));
% BER(maxP==0) = 0;
% maxR(BER>1.1e-3) = 0;
% if ptot > 1,
%   ptot
% end;
% if ptot == 0,
%   WSC = 0;
% else,
% if sum(Popt) > Pbar
%   sum(Popt)
% else
% end;
  WSC = mean(sum(maxR),3);
  f = sum(w'.*WSC);
  g = (Theta-f)/f;
% end

% WSC = mean(sum(log2(1+Popt.*Gtrue)),3);
% WSC = mean(sum(maxR.*(1-BER)),3);




% lambda = 1;

% minTheta = inf;

% alpha = 1;
% i = 1;
% gap = 1;
% lambdavec = linspace(lambda-1e-2,lambda+1e-2,100);
% Thetavec = zeros(size(lambdavec));
% fvec = Thetavec;
% for i = 1:length(lambdavec),
%   [Theta, maxP] = Dual(lambdavec(i),W,G,M,K,Pbar);
%   Thetavec(i) = Theta;  
%   ptot = sum(sum(maxP));
%   WSC = sum(log2(1+(maxP*Pbar/ptot).*G))/K;
%   fvec(i) = sum(w'.*WSC);
% end;
% plot(lambdavec,Thetavec,'b-',lambdavec,fvec,'r-')
% g

% while gap(end) > 1e-3,
%   [Theta, maxP] = Dual(lambda,W,G,M,K,Pbar);
% %   Thetaest = DualEst(lambda,W,G,M,K,Pbar);
%   lambdavec(i) = lambda;
%   Thetavec(i) = Theta; 
%   if Theta < minTheta,
%     minTheta = Theta;
%   end;
%   ptot(i) = sum(sum(maxP));
%   if ptot(i) == 0,
%     WSC = 0;
%   else,
%     WSC = sum(W.*log2(1+(maxP*Pbar/ptot(i)).*G));
%   end;
%   f(i) = sum(WSC);
%   gap(i) = Thetavec(i)-f(i);
%   lambda = max(lambda + alpha/sqrt(i)*sign(ptot(i)-Pbar),eps);
%   i = i+1;
% %   [i,gap(end)]
% end;
% g=gap(end);
% iter = i-1;
% lambda;

% gap = Theta(i)-f(i); 
% figure
% subplot(2,2,1);
% plot([1:i-1],gap)
% title('Gap')
% subplot(2,2,2);
% plot([1:i-1],lambdavec)
% title('\lambda')
% subplot(2,2,3);
% plot([1:i-1],Thetavec)
% title('\theta')
% subplot(2,2,4);
% plot([1:i-1],ptot)
% title('Power')
