function [solution,J]=propt_gain(p_real,x0,sol_n)

toms t

    x1g =x0(:,1);
    x2g = x0(:,2);
    x3g = x0(:,3);
    ug = x0(:,4);

for i=1:1

p = tomPhase('p', t, 0, 250, 50);
setPhase(p);

tomStates x1 x2 x3
tomControls T

% Initial guess
% Note: The guess for tf must appear in the list before expression involving t.
x0 = {collocate({x1 == x1g; x2 == x2g; x3==x3g})
    icollocate(T==ug)};

% Box constraints
 cbox = {};

atPoints(sol_n.time,T)==sol_n.T_p;

% Boundary constraints
cbnd = initial({x1 == p_real.ca0; x2 == p_real.cb0; x3==p_real.V0});

% Various constants and expressions
k1 = p_real.k1;
k2 = p_real.k2;
x2_in=p_real.cb_in;


% ODEs and path constraints
ceq = collocate({dot(x1) == -k1*x1.*x2-x1.*T./x3;
       dot(x2) == -k1*x1.*x2-2*k2*x2.^2-(x2-x2_in).*T./x3;
        dot(x3)== T });

    
  
   
    
% Objective
nc1=p_real.ca0*p_real.V0-final(x1)*final(x3);
nd1=(1/2)*(p_real.cb0*p_real.V0+p_real.cb_in*(final(x3)-p_real.V0)-final(x2)*final(x3)-p_real.ca0*p_real.V0+final(x1)*final(x3));
J=(nd1-nc1);
% objective = J+1*integrate(dot(T)^2);


options = struct;
options.name = 'Batch Reactor';
solution = ezsolve(norm(atPoints(sol_n.time,T)-sol_n.T_p), {cbox, cbnd, ceq}, x0, options);

x1g = subs(collocate(x1),solution);
x2g = subs(collocate(x2),solution);
x3g = subs(collocate(x3),solution);
ug  = subs(collocate(T),solution);

end

% Extract optimal states and controls from solution
t  = subs(collocate(t),solution);
x1 = subs(collocate(x1),solution);
x2 = subs(collocate(x2),solution);
x3 = subs(collocate(x3),solution);
T  = subs(collocate(T),solution);

J=subs(J,solution);
subplot(2,1,1)
plot(t,x1,'+',t,x2,'+',t,x3,'+');
legend('x1','x2','x3');
title('Batch Reactor state variables');

subplot(2,1,2)
plot(t,T,'+');
legend('u');
title('Batch Reactor control');
solution.time=t;
solution.x1=x1;
solution.x2=x2;
solution.x3=x3;
solution.u=T;




