function res=myfunequity_multiquarters(Z)
global solF currente targetR kappa sigma elbarnew beta KKK lambda criticalc dt n newe

ee=zeros(n+1,1);ee(1)=currente;KK=ones(n+1,1);ppe=zeros(n+1,1);qqe=zeros(n+1,1);
ppe(1)=deval(solF,ee(1),1);    qqe(1)=deval(solF,ee(1),2);
currentequity=min((1-lambda)*(ppe(1)+qqe(1)),currente);
for t=2:n+1;
    
xx=musigma(ee(t-1));
mue=xx(1);sigmae=xx(2);
ee(t)=ee(t-1)+mue*dt+sigmae*Z;
if ee(t)>elbarnew
    ppe(t)=deval(solF,ee(t),1);
    qqe(t)=deval(solF,ee(t),2);
    
    KK(t)=KK(t-1)*(1+(qqe(t)-1)/kappa*dt+sigma*Z);
else
    Zcritical=(elbarnew-ee(t-1)-mue*dt)/sigmae;
    gap=Z-Zcritical;
    ee(t)=elbarnew;
   ppe(t)=deval(solF,elbarnew,1);qqe(t)=deval(solF,elbarnew,2);
   KKK=KK(t-1)*(1+(qqe(t)-1)/kappa*dt+sigma*Zcritical);
   x=(KKK*elbarnew)/(1+elbarnew*beta)*gap;
   KK(t)=KKK*(1-sigma*gap)+beta*x;
end

end
newequity = min( (1-lambda)*(ppe(t)+qqe(t)), ee(t) ) * KK(t);
res=newequity/currentequity-1-targetR;
newe=ee(t);


   