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

%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=0;
    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.
    
    
    [v_bar_alt,fval,exitflag] = fminbnd(@(x) -lenderpayoffend(x,eta,c,mu,sigma),0,v_bar);
    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;
        
        
        
        
    
    
    
    
    