function [v_bar,x_star,payoff_lender,payoff_firm]=optimization(eta,c,mu,sigma,bar_u)

%computes the solution of optimization problem 2


%eta: percent of assets retained in bankruptcy by the borrower
%bankruptcy cost
%mu: mean of normal or T-dstribution
%sigma: standard deviation of normal or T-dstribution

global x_lbar;
global x_bar;


%x_lbar and x_bar are the upper and lower bounds for project realizations. If we
%choose a normal or a T-distribution for the project, then x_lbar must be
%sufficiently low and x_bar sufficiently large such that almost no
%probability mass is outside [x_lbar,x_bar]

x_lbar=-3;
x_bar=10;


%First, we determine v_bar at which (8) binds

v_bar=resvbar(eta,bar_u,mu,sigma);

%Next, we compute the value of x_star at which

x_star=optxstar(v_bar,eta,c,mu,sigma);

if x_star==-99 %i.e., the constraints cannot be satisfied
    v_bar=0;
    x_star=x_lbar+eps; %should be marginally larger than  x_lbar to avoid integration
                       %over interval [x_lbar,x_lbar].
    payoff_lender=0;
    payoff_firm=0;
else
    cand_payoff_lender=lenderpayoff(v_bar,x_star,eta,c,mu,sigma);

    % we must now check that there does not exist a solution at which the
    % lender's payoff is increased.

    %first we run a grid-search

    testvbar=linspace(0,min(v_bar,2),100);
    grid_length=testvbar(2)-testvbar(1);
    for i=1:length(testvbar)
        ll(i)=lenderpayoffend(testvbar(i),eta,c,mu,sigma);
    end;
  
    
    [max_value,max_index]=max(ll);
    
    if max_index<length(testvbar);
        lower_bound=testvbar(max_index)-grid_length;
        upper_bound=testvbar(max_index)+grid_length;
        lower_bound=max(lower_bound,0);
        upper_bound=min(upper_bound,v_bar);
    else
        if v_bar>2
            lower_bound=2-2*grid_length;
            upper_bound=vbar;
        else;
            lower_bound=v_bar-4*grid_length;
            upper_bound=v_bar;
        end;
    end;



    [v_bar_alt,fval,exitflag] = fminbnd(@(x) -lenderpayoffend(x,eta,c,mu,sigma),lower_bound,upper_bound);
    lenderpayoff_slack=-fval;
 
   

    if lenderpayoff_slack>=cand_payoff_lender
        v_bar=v_bar_alt;
        x_star=optxstar(v_bar,eta,c,mu,sigma);
        payoff_lender=lenderpayoff_slack;
        payoff_firm=firmpayoff(v_bar,eta,mu,sigma);
    else
        payoff_lender=cand_payoff_lender;
        payoff_firm=firmpayoff(v_bar,eta,mu,sigma);
    end;
end;








