function [g,iter,lambda,WSC,Popt] = ExpectedDiscreteImperfectCSI(G,Gtrue,sigma2w,sigma2e,w,Pbar,R,Eta,BER)
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)));
lambdamin = 0;
lambdamax = 10;
[x,fval,exitflag,output] = fminbnd(@(x) ExpectedDualDiscreteImperfect(x,W,G,Pbar,sigma2w,sigma2e,R,Eta,BER),lambdamin,lambdamax);
lambda = x;
iter = output.iterations;

[Theta, maxP, maxR]=ExpectedDualDiscreteImperfect(lambda,W,G,Pbar,sigma2w,sigma2e,R,Eta,BER);
ptot = sum(sum(sum(maxP)))/N;
% if ptot > 1,
%   ptot
% end;
% if ptot == 0,
%   WSC = 0;
% else,
Popt = maxP;
% WSC = mean(sum(log2(1+Popt.*Gtrue)),3);
WSC = mean(sum(maxR),3);
% end;
f = sum(w'.*WSC);
g = (Theta-f);



% 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')
