function [K] = ku0u0(x, y, xp, yp, hyp, ubar, vbar, ubarp, vbarp, dt, i)

logsigma = hyp(1);
logthetax = hyp(2);
logthetay = hyp(3);

a1 = hyp(4);
a2 = hyp(5);

logsigmap = hyp(6);
logthetaxp = hyp(7);
logthetayp = hyp(8);

n_x = size(x,1);
n_y = size(y,1);
n_xp = size(xp,1);
n_yp = size(yp,1);

x = repmat(x,1,n_xp);
y = repmat(y,1,n_yp);
xp = repmat(xp',n_x,1);
yp = repmat(yp',n_y,1);

ubar = repmat(ubar,1,n_xp);
vbar = repmat(vbar,1,n_yp);
ubarp = repmat(ubarp',n_x,1);
vbarp = repmat(vbarp',n_y,1);

switch i

case 0

K=dt.^2.*exp(1).^(logsigmap+(-2).*logthetaxp+(-1/2).*exp(1).^((-1).* ...
  logthetaxp).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetayp).*(y+(-1) ...
  .*yp).^2).*(exp(1).^logthetaxp+(-1).*(x+(-1).*xp).^2)+a1.*dt.*exp(1).^( ...
  logsigma+(-5).*logthetay+(-1/2).*exp(1).^((-1).*logthetax).*(x+(-1).*xp) ...
  .^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2).*(exp(1).^((-2) ...
  .*logthetax+logthetay).*ubar.*((-1).*exp(1).^logthetax.*(x+(-1).*xp).*( ...
  exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.* ...
  dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).* ...
  ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).* ...
  yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).* ...
  exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).* ...
  logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+ ...
  3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1) ...
  .^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...
  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...
  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+a1.*dt.*exp(1).^( ...
  logthetax+2.*logthetay).*ubarp.*(exp(1).^logthetay+(-1).*(y+(-1).*yp) ...
  .^2)+(-2).*dt.*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).*(exp(1) ...
  .^logthetay+(-1).*(y+(-1).*yp).^2))+vbar.*(exp(1).^logthetay.*(a1.*dt.* ...
  exp(1).^((-1).*logthetax+logthetay).*(3.*exp(1).^(logthetax+logthetay).* ...
  vbarp+(-2).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).* ...
  exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^2)+(-2).*exp(1).^(2.*logthetay) ...
  .*(y+(-1).*yp)+2.*dt.*exp(1).^(a2+(-2).*logthetax).*((-6).*exp(1).^(2.* ...
  logthetax+logthetay)+(-1).*exp(1).^(logthetax+2.*logthetay)+exp(1).^(2.* ...
  logthetay).*(x+(-1).*xp).^2+2.*exp(1).^(2.*logthetax).*(y+(-1).*yp).^2) ...
  .*(y+(-1).*yp))+(-1).*(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).* ...
  (y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^( ...
  2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...
  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...
  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...
  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...
  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...
  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...
  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...
  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(y+ ...
  (-1).*yp)))+exp(1).^(logsigma+(-4).*logthetay+(-1/2).*exp(1).^((-1).* ...
  logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).* ...
  yp).^2).*(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp) ...
  .^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.* ...
  logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...
  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...
  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...
  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...
  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...
  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...
  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...
  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+(-1) ...
  .*dt.*exp(1).^(a2+logsigma+(-6).*logthetay+(-1/2).*exp(1).^((-1).* ...
  logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).* ...
  yp).^2).*((-2).*exp(1).^((-2).*logthetax+2.*logthetay).*(exp(1).^(2.*( ...
  logthetax+logthetay))+dt.*(6.*exp(1).^(a2+2.*logthetax+logthetay)+exp(1) ...
  .^(a2+logthetax+2.*logthetay)+a1.*exp(1).^(logthetax+2.*logthetay).* ...
  ubarp.*(x+(-1).*xp)+(-1).*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).^2+3.* ...
  a1.*exp(1).^(2.*logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-6).*exp(1) ...
  .^(a2+2.*logthetax).*(y+(-1).*yp).^2))+exp(1).^((-2).*logthetax+2.* ...
  logthetay).*((-1).*exp(1).^logthetax+(x+(-1).*xp).^2).*(exp(1).^(2.* ...
  logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^(( ...
  -1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+ ...
  3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1) ...
  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...
  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*( ...
  3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+( ...
  -1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.* ...
  logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...
  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...
  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+(-2).*dt.*exp(1) ...
  .^(a2+(-2).*logthetax+4.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).* ...
  yp).^2)+(-2).*dt.*exp(1).^((-3).*logthetax+4.*logthetay).*(a1.*exp(1) ...
  .^logthetax.*ubarp+(-2).*exp(1).^a2.*(x+(-1).*xp)).*(x+(-1).*xp).*(exp( ...
  1).^logthetay+(-1).*(y+(-1).*yp).^2)+(exp(1).^(2.*logthetay).*(exp(1) ...
  .^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...
  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...
  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...
  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...
  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...
  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...
  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...
  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...
  logthetax).*(y+(-1).*yp).^4)).*((-1).*exp(1).^logthetay+(y+(-1).*yp).^2) ...
  +(-2).*exp(1).^logthetay.*(a1.*dt.*exp(1).^((-1).*logthetax+logthetay).* ...
  (3.*exp(1).^(logthetax+logthetay).*vbarp+(-2).*exp(1).^logthetay.* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+( ...
  -1).*yp).^2)+(-2).*exp(1).^(2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^( ...
  a2+(-2).*logthetax).*((-6).*exp(1).^(2.*logthetax+logthetay)+(-1).*exp( ...
  1).^(logthetax+2.*logthetay)+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.* ...
  exp(1).^(2.*logthetax).*(y+(-1).*yp).^2).*(y+(-1).*yp)).*(y+(-1).*yp)); ...

case 1 % logsigma

K=exp(1).^(logsigma+(-6).*logthetay+(-1/2).*exp(1).^((-1).*logthetax).*(x+ ...
  (-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2).*(a1.* ...
  dt.*exp(1).^logthetay.*(exp(1).^((-2).*logthetax+logthetay).*ubar.*((-1) ...
  .*exp(1).^logthetax.*(x+(-1).*xp).*(exp(1).^(2.*logthetay).*(exp(1) ...
  .^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...
  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...
  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...
  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...
  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...
  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...
  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...
  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...
  logthetax).*(y+(-1).*yp).^4))+a1.*dt.*exp(1).^(logthetax+2.*logthetay).* ...
  ubarp.*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+(-2).*dt.*exp(1).^(a2+ ...
  2.*logthetay).*(x+(-1).*xp).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2))+ ...
  vbar.*(exp(1).^logthetay.*(a1.*dt.*exp(1).^((-1).*logthetax+logthetay).* ...
  (3.*exp(1).^(logthetax+logthetay).*vbarp+(-2).*exp(1).^logthetay.* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+( ...
  -1).*yp).^2)+(-2).*exp(1).^(2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^( ...
  a2+(-2).*logthetax).*((-6).*exp(1).^(2.*logthetax+logthetay)+(-1).*exp( ...
  1).^(logthetax+2.*logthetay)+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.* ...
  exp(1).^(2.*logthetax).*(y+(-1).*yp).^2).*(y+(-1).*yp))+(-1).*(exp(1).^( ...
  2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1) ...
  .^((-1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).* ...
  xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1) ...
  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...
  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*( ...
  3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+( ...
  -1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.* ...
  logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...
  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...
  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(y+(-1).*yp)))+ ...
  exp(1).^(2.*logthetay).*(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1) ...
  .*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1) ...
  .^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...
  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...
  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...
  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...
  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...
  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...
  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...
  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+(-1) ...
  .*dt.*exp(1).^a2.*((-2).*exp(1).^((-2).*logthetax+2.*logthetay).*(exp(1) ...
  .^(2.*(logthetax+logthetay))+dt.*(6.*exp(1).^(a2+2.*logthetax+logthetay) ...
  +exp(1).^(a2+logthetax+2.*logthetay)+a1.*exp(1).^(logthetax+2.* ...
  logthetay).*ubarp.*(x+(-1).*xp)+(-1).*exp(1).^(a2+2.*logthetay).*(x+(-1) ...
  .*xp).^2+3.*a1.*exp(1).^(2.*logthetax+logthetay).*vbarp.*(y+(-1).*yp)+( ...
  -6).*exp(1).^(a2+2.*logthetax).*(y+(-1).*yp).^2))+exp(1).^((-2).* ...
  logthetax+2.*logthetay).*((-1).*exp(1).^logthetax+(x+(-1).*xp).^2).*( ...
  exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.* ...
  dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).* ...
  ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).* ...
  yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).* ...
  exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).* ...
  logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+ ...
  3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1) ...
  .^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...
  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...
  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+(-2).*dt.*exp(1) ...
  .^(a2+(-2).*logthetax+4.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).* ...
  yp).^2)+(-2).*dt.*exp(1).^((-3).*logthetax+4.*logthetay).*(a1.*exp(1) ...
  .^logthetax.*ubarp+(-2).*exp(1).^a2.*(x+(-1).*xp)).*(x+(-1).*xp).*(exp( ...
  1).^logthetay+(-1).*(y+(-1).*yp).^2)+(exp(1).^(2.*logthetay).*(exp(1) ...
  .^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...
  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...
  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...
  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...
  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...
  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...
  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...
  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...
  logthetax).*(y+(-1).*yp).^4)).*((-1).*exp(1).^logthetay+(y+(-1).*yp).^2) ...
  +(-2).*exp(1).^logthetay.*(a1.*dt.*exp(1).^((-1).*logthetax+logthetay).* ...
  (3.*exp(1).^(logthetax+logthetay).*vbarp+(-2).*exp(1).^logthetay.* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+( ...
  -1).*yp).^2)+(-2).*exp(1).^(2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^( ...
  a2+(-2).*logthetax).*((-6).*exp(1).^(2.*logthetax+logthetay)+(-1).*exp( ...
  1).^(logthetax+2.*logthetay)+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.* ...
  exp(1).^(2.*logthetax).*(y+(-1).*yp).^2).*(y+(-1).*yp)).*(y+(-1).*yp))); ...

case 2 % logthetax

K=(1/2).*exp(1).^(logsigma+(-6).*logthetay+(-1/2).*exp(1).^((-1).* ...
  logthetax).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).* ...
  yp).^2).*(a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(x+(-1).*xp).^2.* ...
  (exp(1).^((-2).*logthetax+logthetay).*ubar.*((-1).*exp(1).^logthetax.*( ...
  x+(-1).*xp).*(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).* ...
  yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.* ...
  logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...
  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...
  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...
  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...
  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...
  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...
  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...
  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+a1.* ...
  dt.*exp(1).^(logthetax+2.*logthetay).*ubarp.*(exp(1).^logthetay+(-1).*( ...
  y+(-1).*yp).^2)+(-2).*dt.*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).*(exp( ...
  1).^logthetay+(-1).*(y+(-1).*yp).^2))+vbar.*(exp(1).^logthetay.*(a1.* ...
  dt.*exp(1).^((-1).*logthetax+logthetay).*(3.*exp(1).^(logthetax+ ...
  logthetay).*vbarp+(-2).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1) ...
  .*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^2)+(-2).*exp(1).^( ...
  2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^(a2+(-2).*logthetax).*((-6).* ...
  exp(1).^(2.*logthetax+logthetay)+(-1).*exp(1).^(logthetax+2.*logthetay)+ ...
  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.*exp(1).^(2.*logthetax).*(y+( ...
  -1).*yp).^2).*(y+(-1).*yp))+(-1).*(exp(1).^(2.*logthetay).*(exp(1) ...
  .^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...
  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...
  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...
  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...
  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...
  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...
  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...
  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...
  logthetax).*(y+(-1).*yp).^4)).*(y+(-1).*yp)))+exp(1).^((-1).*logthetax+ ...
  2.*logthetay).*(x+(-1).*xp).^2.*(exp(1).^(2.*logthetay).*(exp(1) ...
  .^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...
  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...
  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...
  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...
  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...
  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...
  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...
  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...
  logthetax).*(y+(-1).*yp).^4))+(-2).*a1.*dt.*exp(1).^((-3).*logthetax+2.* ...
  logthetay).*((-1).*exp(1).^(2.*(logthetax+logthetay)).*ubar.*(x+(-1).* ...
  xp).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^( ...
  logthetax+logthetay).*(exp(1).^(logthetax+2.*logthetay).*ubar.*ubarp+( ...
  -2).*exp(1).^(2.*logthetay).*ubar.*ubarp.*(x+(-1).*xp).^2+(-1).*exp(1) ...
  .^(logthetax+logthetay).*(3.*ubar.*vbarp.*(x+(-1).*xp)+ubarp.*(3.*vbar.* ...
  (x+(-1).*xp)+ubar.*(y+(-1).*yp))).*(y+(-1).*yp)+2.*exp(1).^logthetay.* ...
  ubar.*ubarp.*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^logthetax.*( ...
  ubarp.*vbar+ubar.*vbarp).*(x+(-1).*xp).*(y+(-1).*yp).^3)+dt.*exp(1) ...
  .^a2.*((-6).*exp(1).^(logthetax+3.*logthetay).*ubar.*(x+(-1).*xp)+3.* ...
  exp(1).^(3.*logthetay).*ubar.*(x+(-1).*xp).^3+(-3).*exp(1).^(2.*( ...
  logthetax+logthetay)).*(ubar.*(x+(-1).*xp)+vbar.*(y+(-1).*yp))+6.*exp(1) ...
  .^(logthetax+2.*logthetay).*(x+(-1).*xp).*(vbar.*(x+(-1).*xp)+ubar.*(y+( ...
  -1).*yp)).*(y+(-1).*yp)+(-3).*exp(1).^(2.*logthetay).*ubar.*(x+(-1).*xp) ...
  .^3.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax+logthetay).*(6.*ubar.*(x+(-1) ...
  .*xp)+vbar.*(y+(-1).*yp)).*(y+(-1).*yp).^2+(-2).*exp(1).^(logthetax+ ...
  logthetay).*vbar.*(x+(-1).*xp).^2.*(y+(-1).*yp).^3+(-1).*exp(1).^(2.* ...
  logthetax).*ubar.*(x+(-1).*xp).*(y+(-1).*yp).^4))+(-2).*dt.*exp(1).^(a2+ ...
  (-4).*logthetax+2.*logthetay).*(exp(1).^(2.*(logthetax+logthetay)).*( ...
  exp(1).^logthetax+(-2).*(x+(-1).*xp).^2).*(exp(1).^logthetay+(-1).*(y+( ...
  -1).*yp).^2)+dt.*(6.*exp(1).^(a2+3.*logthetax+2.*logthetay)+6.*exp(1).^( ...
  a2+2.*logthetax+3.*logthetay)+6.*a1.*exp(1).^(2.*logthetax+3.*logthetay) ...
  .*ubarp.*(x+(-1).*xp)+(-18).*exp(1).^(a2+logthetax+3.*logthetay).*(x+( ...
  -1).*xp).^2+(-3).*a1.*exp(1).^(logthetax+3.*logthetay).*ubarp.*(x+(-1).* ...
  xp).^3+4.*exp(1).^(a2+3.*logthetay).*(x+(-1).*xp).^4+3.*a1.*exp(1).^(3.* ...
  logthetax+2.*logthetay).*(ubarp.*(x+(-1).*xp)+vbarp.*(y+(-1).*yp))+(-6) ...
  .*exp(1).^(a2+2.*(logthetax+logthetay)).*(2.*x.^2+(-4).*x.*xp+2.*xp.^2+( ...
  y+(-1).*yp).^2)+(-6).*a1.*exp(1).^(2.*(logthetax+logthetay)).*(x+(-1).* ...
  xp).*(vbarp.*(x+(-1).*xp)+ubarp.*(y+(-1).*yp)).*(y+(-1).*yp)+(-12).*exp( ...
  1).^(a2+3.*logthetax+logthetay).*(y+(-1).*yp).^2+24.*exp(1).^(a2+2.* ...
  logthetax+logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+18.*exp(1).^(a2+ ...
  logthetax+2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+3.*a1.*exp(1) ...
  .^(logthetax+2.*logthetay).*ubarp.*(x+(-1).*xp).^3.*(y+(-1).*yp).^2+(-4) ...
  .*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).^4.*(y+(-1).*yp).^2+(-1).*a1.* ...
  exp(1).^(3.*logthetax+logthetay).*(6.*ubarp.*(x+(-1).*xp)+vbarp.*(y+(-1) ...
  .*yp)).*(y+(-1).*yp).^2+2.*a1.*exp(1).^(2.*logthetax+logthetay).*vbarp.* ...
  (x+(-1).*xp).^2.*(y+(-1).*yp).^3+2.*exp(1).^(a2+3.*logthetax).*(y+(-1).* ...
  yp).^4+a1.*exp(1).^(3.*logthetax).*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^4+ ...
  (-4).*exp(1).^(a2+2.*logthetax).*(x+(-1).*xp).^2.*(y+(-1).*yp).^4))+(-1) ...
  .*dt.*exp(1).^(a2+(-1).*logthetax).*(x+(-1).*xp).^2.*((-2).*exp(1).^(( ...
  -2).*logthetax+2.*logthetay).*(exp(1).^(2.*(logthetax+logthetay))+dt.*( ...
  6.*exp(1).^(a2+2.*logthetax+logthetay)+exp(1).^(a2+logthetax+2.* ...
  logthetay)+a1.*exp(1).^(logthetax+2.*logthetay).*ubarp.*(x+(-1).*xp)+( ...
  -1).*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).^2+3.*a1.*exp(1).^(2.* ...
  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-6).*exp(1).^(a2+2.* ...
  logthetax).*(y+(-1).*yp).^2))+exp(1).^((-2).*logthetax+2.*logthetay).*(( ...
  -1).*exp(1).^logthetax+(x+(-1).*xp).^2).*(exp(1).^(2.*logthetay).*(exp( ...
  1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...
  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...
  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...
  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...
  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...
  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...
  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...
  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...
  logthetax).*(y+(-1).*yp).^4))+(-2).*dt.*exp(1).^(a2+(-2).*logthetax+4.* ...
  logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+(-2).*dt.*exp(1) ...
  .^((-3).*logthetax+4.*logthetay).*(a1.*exp(1).^logthetax.*ubarp+(-2).* ...
  exp(1).^a2.*(x+(-1).*xp)).*(x+(-1).*xp).*(exp(1).^logthetay+(-1).*(y+( ...
  -1).*yp).^2)+(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).* ...
  yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.* ...
  logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...
  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...
  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...
  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...
  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...
  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...
  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...
  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(( ...
  -1).*exp(1).^logthetay+(y+(-1).*yp).^2)+(-2).*exp(1).^logthetay.*(a1.* ...
  dt.*exp(1).^((-1).*logthetax+logthetay).*(3.*exp(1).^(logthetax+ ...
  logthetay).*vbarp+(-2).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1) ...
  .*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^2)+(-2).*exp(1).^( ...
  2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^(a2+(-2).*logthetax).*((-6).* ...
  exp(1).^(2.*logthetax+logthetay)+(-1).*exp(1).^(logthetax+2.*logthetay)+ ...
  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.*exp(1).^(2.*logthetax).*(y+( ...
  -1).*yp).^2).*(y+(-1).*yp)).*(y+(-1).*yp))+(-2).*dt.*exp(1).^((-2).* ...
  logthetax+4.*logthetay).*(exp(1).^(a2+logthetax)+a1.*exp(1).^logthetax.* ...
  ubarp.*(x+(-1).*xp)+(-2).*exp(1).^a2.*(x+(-1).*xp).^2).*(exp(1) ...
  .^logthetay+(-1).*(y+(-1).*yp).^2));

case 3 % logthetay

K=exp(1).^(logsigma+(-6).*logthetay+(-1/2).*exp(1).^((-1).*logthetax).*(x+ ...
  (-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2).*(exp( ...
  1).^((-2).*logthetax+3.*logthetay).*(exp(1).^(2.*logthetax+logthetay).*( ...
  3.*exp(1).^logthetay+(-2).*(y+(-1).*yp).^2)+dt.*(6.*exp(1).^(a2+2.* ...
  logthetax+logthetay)+3.*exp(1).^(a2+logthetax+2.*logthetay)+3.*a1.*exp( ...
  1).^(logthetax+2.*logthetay).*ubarp.*(x+(-1).*xp)+(-3).*exp(1).^(a2+2.* ...
  logthetay).*(x+(-1).*xp).^2+6.*a1.*exp(1).^(2.*logthetax+logthetay).* ...
  vbarp.*(y+(-1).*yp)+(-6).*exp(1).^(a2+2.*logthetax).*(y+(-1).*yp).^2+( ...
  -2).*exp(1).^(a2+logthetax+logthetay).*(y+(-1).*yp).^2+(-2).*a1.*exp(1) ...
  .^(logthetax+logthetay).*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+2.*exp(1) ...
  .^(a2+logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+(-1).*a1.*exp(1).^( ...
  2.*logthetax).*vbarp.*(y+(-1).*yp).^3))+a1.*dt.*exp(1).^((-3).* ...
  logthetax+2.*logthetay).*(exp(1).^(2.*logthetax+logthetay).*((-4).*exp( ...
  1).^(2.*logthetay).*ubar.*(x+(-1).*xp)+(-9).*exp(1).^(logthetax+ ...
  logthetay).*vbar.*(y+(-1).*yp)+3.*exp(1).^logthetay.*ubar.*(x+(-1).*xp) ...
  .*(y+(-1).*yp).^2+2.*exp(1).^logthetax.*vbar.*(y+(-1).*yp).^3)+a1.*dt.* ...
  exp(1).^logthetax.*(4.*exp(1).^(logthetax+3.*logthetay).*ubar.*ubarp+9.* ...
  exp(1).^(2.*(logthetax+logthetay)).*vbar.*vbarp+(-4).*exp(1).^(3.* ...
  logthetay).*ubar.*ubarp.*(x+(-1).*xp).^2+(-3).*exp(1).^(logthetax+2.* ...
  logthetay).*(3.*ubar.*vbarp.*(x+(-1).*xp)+ubarp.*(3.*vbar.*(x+(-1).*xp)+ ...
  ubar.*(y+(-1).*yp))).*(y+(-1).*yp)+(-12).*exp(1).^(2.*logthetax+ ...
  logthetay).*vbar.*vbarp.*(y+(-1).*yp).^2+3.*exp(1).^(2.*logthetay).* ...
  ubar.*ubarp.*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+2.*exp(1).^(logthetax+ ...
  logthetay).*(ubarp.*vbar+ubar.*vbarp).*(x+(-1).*xp).*(y+(-1).*yp).^3+ ...
  exp(1).^(2.*logthetax).*vbar.*vbarp.*(y+(-1).*yp).^4)+dt.*exp(1).^a2.*(( ...
  -12).*exp(1).^(logthetax+3.*logthetay).*ubar.*(x+(-1).*xp)+4.*exp(1).^( ...
  3.*logthetay).*ubar.*(x+(-1).*xp).^3+(-9).*exp(1).^(2.*(logthetax+ ...
  logthetay)).*(ubar.*(x+(-1).*xp)+vbar.*(y+(-1).*yp))+(-30).*exp(1).^(3.* ...
  logthetax+logthetay).*vbar.*(y+(-1).*yp)+9.*exp(1).^(logthetax+2.* ...
  logthetay).*(x+(-1).*xp).*(vbar.*(x+(-1).*xp)+ubar.*(y+(-1).*yp)).*(y+( ...
  -1).*yp)+(-3).*exp(1).^(2.*logthetay).*ubar.*(x+(-1).*xp).^3.*(y+(-1).* ...
  yp).^2+2.*exp(1).^(2.*logthetax+logthetay).*(6.*ubar.*(x+(-1).*xp)+ ...
  vbar.*(y+(-1).*yp)).*(y+(-1).*yp).^2+10.*exp(1).^(3.*logthetax).*vbar.*( ...
  y+(-1).*yp).^3+(-2).*exp(1).^(logthetax+logthetay).*vbar.*(x+(-1).*xp) ...
  .^2.*(y+(-1).*yp).^3+(-1).*exp(1).^(2.*logthetax).*ubar.*(x+(-1).*xp).*( ...
  y+(-1).*yp).^4))+dt.*exp(1).^(a2+(-4).*logthetax+logthetay).*(exp(1).^( ...
  2.*logthetax+logthetay).*(12.*exp(1).^(2.*(logthetax+logthetay))+5.*exp( ...
  1).^(logthetax+3.*logthetay)+(-5).*exp(1).^(3.*logthetay).*(x+(-1).*xp) ...
  .^2+(-18).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-4).*exp( ...
  1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+4.*exp(1).^(2.*logthetay) ...
  .*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+2.*exp(1).^(2.*logthetax).*(y+(-1).* ...
  yp).^4)+dt.*(45.*exp(1).^(a2+4.*logthetax+2.*logthetay)+15.*exp(1).^(a2+ ...
  2.*logthetax+4.*logthetay)+24.*exp(1).^(a2+3.*(logthetax+logthetay))+ ...
  15.*a1.*exp(1).^(2.*logthetax+4.*logthetay).*ubarp.*(x+(-1).*xp)+(-30).* ...
  exp(1).^(a2+logthetax+4.*logthetay).*(x+(-1).*xp).^2+(-5).*a1.*exp(1).^( ...
  logthetax+4.*logthetay).*ubarp.*(x+(-1).*xp).^3+5.*exp(1).^(a2+4.* ...
  logthetay).*(x+(-1).*xp).^4+12.*a1.*exp(1).^(3.*(logthetax+logthetay)).* ...
  (ubarp.*(x+(-1).*xp)+vbarp.*(y+(-1).*yp))+(-12).*exp(1).^(a2+2.* ...
  logthetax+3.*logthetay).*(2.*x.^2+(-4).*x.*xp+2.*xp.^2+(y+(-1).*yp).^2)+ ...
  45.*a1.*exp(1).^(4.*logthetax+2.*logthetay).*vbarp.*(y+(-1).*yp)+(-12).* ...
  a1.*exp(1).^(2.*logthetax+3.*logthetay).*(x+(-1).*xp).*(vbarp.*(x+(-1).* ...
  xp)+ubarp.*(y+(-1).*yp)).*(y+(-1).*yp)+(-90).*exp(1).^(a2+4.*logthetax+ ...
  logthetay).*(y+(-1).*yp).^2+(-36).*exp(1).^(a2+3.*logthetax+2.* ...
  logthetay).*(y+(-1).*yp).^2+24.*exp(1).^(a2+logthetax+3.*logthetay).*(x+ ...
  (-1).*xp).^2.*(y+(-1).*yp).^2+36.*exp(1).^(a2+2.*(logthetax+logthetay)) ...
  .*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+4.*a1.*exp(1).^(logthetax+3.* ...
  logthetay).*ubarp.*(x+(-1).*xp).^3.*(y+(-1).*yp).^2+(-4).*exp(1).^(a2+ ...
  3.*logthetay).*(x+(-1).*xp).^4.*(y+(-1).*yp).^2+(-3).*a1.*exp(1).^(3.* ...
  logthetax+2.*logthetay).*(6.*ubarp.*(x+(-1).*xp)+vbarp.*(y+(-1).*yp)).*( ...
  y+(-1).*yp).^2+(-20).*a1.*exp(1).^(4.*logthetax+logthetay).*vbarp.*(y+( ...
  -1).*yp).^3+3.*a1.*exp(1).^(2.*(logthetax+logthetay)).*vbarp.*(x+(-1).* ...
  xp).^2.*(y+(-1).*yp).^3+15.*exp(1).^(a2+4.*logthetax).*(y+(-1).*yp).^4+ ...
  4.*exp(1).^(a2+3.*logthetax+logthetay).*(y+(-1).*yp).^4+2.*a1.*exp(1).^( ...
  3.*logthetax+logthetay).*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^4+(-4).*exp( ...
  1).^(a2+2.*logthetax+logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^4+a1.* ...
  exp(1).^(4.*logthetax).*vbarp.*(y+(-1).*yp).^5))+(-1).*dt.*exp(1).^a2.*( ...
  (-2).*exp(1).^((-2).*logthetax+2.*logthetay).*(exp(1).^(2.*(logthetax+ ...
  logthetay))+dt.*(6.*exp(1).^(a2+2.*logthetax+logthetay)+exp(1).^(a2+ ...
  logthetax+2.*logthetay)+a1.*exp(1).^(logthetax+2.*logthetay).*ubarp.*(x+ ...
  (-1).*xp)+(-1).*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).^2+3.*a1.*exp(1) ...
  .^(2.*logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-6).*exp(1).^(a2+2.* ...
  logthetax).*(y+(-1).*yp).^2))+exp(1).^((-2).*logthetax+2.*logthetay).*(( ...
  -1).*exp(1).^logthetax+(x+(-1).*xp).^2).*(exp(1).^(2.*logthetay).*(exp( ...
  1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...
  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...
  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...
  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...
  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...
  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...
  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...
  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...
  logthetax).*(y+(-1).*yp).^4))+(-2).*dt.*exp(1).^(a2+(-2).*logthetax+4.* ...
  logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+(-2).*dt.*exp(1) ...
  .^((-3).*logthetax+4.*logthetay).*(a1.*exp(1).^logthetax.*ubarp+(-2).* ...
  exp(1).^a2.*(x+(-1).*xp)).*(x+(-1).*xp).*(exp(1).^logthetay+(-1).*(y+( ...
  -1).*yp).^2)+(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).* ...
  yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.* ...
  logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...
  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...
  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...
  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...
  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...
  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...
  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...
  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(( ...
  -1).*exp(1).^logthetay+(y+(-1).*yp).^2)+(-2).*exp(1).^logthetay.*(a1.* ...
  dt.*exp(1).^((-1).*logthetax+logthetay).*(3.*exp(1).^(logthetax+ ...
  logthetay).*vbarp+(-2).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1) ...
  .*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^2)+(-2).*exp(1).^( ...
  2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^(a2+(-2).*logthetax).*((-6).* ...
  exp(1).^(2.*logthetax+logthetay)+(-1).*exp(1).^(logthetax+2.*logthetay)+ ...
  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.*exp(1).^(2.*logthetax).*(y+( ...
  -1).*yp).^2).*(y+(-1).*yp)).*(y+(-1).*yp)).*((-6)+(1/2).*exp(1).^((-1).* ...
  logthetay).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^logthetay.*(exp(1).^((-2).* ...
  logthetax+logthetay).*ubar.*((-1).*exp(1).^logthetax.*(x+(-1).*xp).*( ...
  exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.* ...
  dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).* ...
  ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).* ...
  yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).* ...
  exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).* ...
  logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+ ...
  3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1) ...
  .^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...
  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...
  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+a1.*dt.*exp(1).^( ...
  logthetax+2.*logthetay).*ubarp.*(exp(1).^logthetay+(-1).*(y+(-1).*yp) ...
  .^2)+(-2).*dt.*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).*(exp(1) ...
  .^logthetay+(-1).*(y+(-1).*yp).^2))+vbar.*(exp(1).^logthetay.*(a1.*dt.* ...
  exp(1).^((-1).*logthetax+logthetay).*(3.*exp(1).^(logthetax+logthetay).* ...
  vbarp+(-2).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).* ...
  exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^2)+(-2).*exp(1).^(2.*logthetay) ...
  .*(y+(-1).*yp)+2.*dt.*exp(1).^(a2+(-2).*logthetax).*((-6).*exp(1).^(2.* ...
  logthetax+logthetay)+(-1).*exp(1).^(logthetax+2.*logthetay)+exp(1).^(2.* ...
  logthetay).*(x+(-1).*xp).^2+2.*exp(1).^(2.*logthetax).*(y+(-1).*yp).^2) ...
  .*(y+(-1).*yp))+(-1).*(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1).* ...
  (y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1).^( ...
  2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...
  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...
  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...
  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...
  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...
  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...
  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...
  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(y+ ...
  (-1).*yp))).*((-5)+(1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2)+ ...
  exp(1).^(2.*logthetay).*(exp(1).^(2.*logthetay).*(exp(1).^logthetay+(-1) ...
  .*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+logthetay).*(exp(1) ...
  .^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).* ...
  vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+( ...
  -1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1) ...
  .^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...
  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...
  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...
  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...
  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(( ...
  -4)+(1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2));

case 4 % a1

K=dt.*exp(1).^(logsigma+(-6).*logthetay+(-1/2).*exp(1).^((-1).*logthetax) ...
  .*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2).*( ...
  exp(1).^logthetay.*(exp(1).^((-2).*logthetax+logthetay).*ubar.*((-1).* ...
  exp(1).^logthetax.*(x+(-1).*xp).*(exp(1).^(2.*logthetay).*(exp(1) ...
  .^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).*logthetax+ ...
  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...
  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...
  (-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*(3.*exp(1).^(2.*( ...
  logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^( ...
  3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*( ...
  y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+ ...
  exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...
  logthetax).*(y+(-1).*yp).^4))+a1.*dt.*exp(1).^(logthetax+2.*logthetay).* ...
  ubarp.*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+(-2).*dt.*exp(1).^(a2+ ...
  2.*logthetay).*(x+(-1).*xp).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2))+ ...
  vbar.*(exp(1).^logthetay.*(a1.*dt.*exp(1).^((-1).*logthetax+logthetay).* ...
  (3.*exp(1).^(logthetax+logthetay).*vbarp+(-2).*exp(1).^logthetay.* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).*exp(1).^logthetax.*vbarp.*(y+( ...
  -1).*yp).^2)+(-2).*exp(1).^(2.*logthetay).*(y+(-1).*yp)+2.*dt.*exp(1).^( ...
  a2+(-2).*logthetax).*((-6).*exp(1).^(2.*logthetax+logthetay)+(-1).*exp( ...
  1).^(logthetax+2.*logthetay)+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+2.* ...
  exp(1).^(2.*logthetax).*(y+(-1).*yp).^2).*(y+(-1).*yp))+(-1).*(exp(1).^( ...
  2.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1) ...
  .^((-1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).* ...
  xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1) ...
  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...
  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*( ...
  3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+( ...
  -1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.* ...
  logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...
  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...
  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*(y+(-1).*yp)))+ ...
  a1.*dt.*exp(1).^((-2).*logthetax+2.*logthetay).*(exp(1).^logthetay.* ...
  ubar.*(exp(1).^(logthetax+logthetay).*ubarp.*(exp(1).^logthetay+(-1).*( ...
  y+(-1).*yp).^2)+(-1).*(x+(-1).*xp).*(exp(1).^(2.*logthetay).*ubarp.*(x+( ...
  -1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).* ...
  exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...
  .^logthetax.*vbarp.*(y+(-1).*yp).^3))+exp(1).^logthetax.*vbar.*(3.*exp( ...
  1).^(logthetax+2.*logthetay).*vbarp+(-3).*exp(1).^(2.*logthetay).* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-6).*exp(1).^(logthetax+logthetay).* ...
  vbarp.*(y+(-1).*yp).^2+exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).* ...
  yp).^3+exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^4))+(-1).*dt.*exp(1).^( ...
  a2+(-3).*logthetax+logthetay).*((-2).*exp(1).^(2.*(logthetax+logthetay)) ...
  .*(exp(1).^logthetay.*ubarp.*(x+(-1).*xp)+3.*exp(1).^logthetax.*vbarp.*( ...
  y+(-1).*yp))+(-2).*exp(1).^(logthetax+3.*logthetay).*ubarp.*(x+(-1).*xp) ...
  .*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+exp(1).^(2.*logthetay).*(( ...
  -1).*exp(1).^logthetax+(x+(-1).*xp).^2).*(exp(1).^(2.*logthetay).* ...
  ubarp.*(x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).* ...
  yp)+(-1).*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).* ...
  exp(1).^logthetax.*vbarp.*(y+(-1).*yp).^3)+exp(1).^(2.*logthetax).*((-1) ...
  .*exp(1).^logthetay+(y+(-1).*yp).^2).*(exp(1).^(2.*logthetay).*ubarp.*( ...
  x+(-1).*xp)+3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).* ...
  exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...
  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+(-2).*exp(1).^(2.*logthetax+ ...
  logthetay).*(3.*exp(1).^(logthetax+logthetay).*vbarp+(-2).*exp(1) ...
  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).*exp(1).^logthetax.* ...
  vbarp.*(y+(-1).*yp).^2).*(y+(-1).*yp))+exp(1).^((-1).*logthetax+3.* ...
  logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.*exp(1).^( ...
  logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1).^logthetay.* ...
  ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1).^logthetax.*vbarp.*(y+ ...
  (-1).*yp).^3));

case 5 % a2

K=dt.*exp(1).^(logsigma+(-6).*logthetay+(-1/2).*exp(1).^((-1).*logthetax) ...
  .*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetay).*(y+(-1).*yp).^2).*( ...
  exp(1).^a2.*(2.*exp(1).^((-2).*logthetax+2.*logthetay).*(exp(1).^(2.*( ...
  logthetax+logthetay))+dt.*(6.*exp(1).^(a2+2.*logthetax+logthetay)+exp(1) ...
  .^(a2+logthetax+2.*logthetay)+a1.*exp(1).^(logthetax+2.*logthetay).* ...
  ubarp.*(x+(-1).*xp)+(-1).*exp(1).^(a2+2.*logthetay).*(x+(-1).*xp).^2+3.* ...
  a1.*exp(1).^(2.*logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-6).*exp(1) ...
  .^(a2+2.*logthetax).*(y+(-1).*yp).^2))+(-1).*exp(1).^((-2).*logthetax+ ...
  2.*logthetay).*((-1).*exp(1).^logthetax+(x+(-1).*xp).^2).*(exp(1).^(2.* ...
  logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^(( ...
  -1).*logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+ ...
  3.*exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1) ...
  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...
  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*( ...
  3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+( ...
  -1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.* ...
  logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...
  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...
  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+2.*dt.*exp(1).^( ...
  a2+(-2).*logthetax+4.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp) ...
  .^2)+2.*dt.*exp(1).^((-3).*logthetax+4.*logthetay).*(a1.*exp(1) ...
  .^logthetax.*ubarp+(-2).*exp(1).^a2.*(x+(-1).*xp)).*(x+(-1).*xp).*(exp( ...
  1).^logthetay+(-1).*(y+(-1).*yp).^2)+(-1).*(exp(1).^(2.*logthetay).*( ...
  exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+a1.*dt.*exp(1).^((-1).* ...
  logthetax+logthetay).*(exp(1).^(2.*logthetay).*ubarp.*(x+(-1).*xp)+3.* ...
  exp(1).^(logthetax+logthetay).*vbarp.*(y+(-1).*yp)+(-1).*exp(1) ...
  .^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp).^2+(-1).*exp(1) ...
  .^logthetax.*vbarp.*(y+(-1).*yp).^3)+dt.*exp(1).^(a2+(-2).*logthetax).*( ...
  3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.*logthetay)+( ...
  -1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.* ...
  logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...
  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...
  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)).*((-1).*exp(1) ...
  .^logthetay+(y+(-1).*yp).^2)+2.*exp(1).^logthetay.*(a1.*dt.*exp(1).^(( ...
  -1).*logthetax+logthetay).*(3.*exp(1).^(logthetax+logthetay).*vbarp+(-2) ...
  .*exp(1).^logthetay.*ubarp.*(x+(-1).*xp).*(y+(-1).*yp)+(-3).*exp(1) ...
  .^logthetax.*vbarp.*(y+(-1).*yp).^2)+(-2).*exp(1).^(2.*logthetay).*(y+( ...
  -1).*yp)+2.*dt.*exp(1).^(a2+(-2).*logthetax).*((-6).*exp(1).^(2.* ...
  logthetax+logthetay)+(-1).*exp(1).^(logthetax+2.*logthetay)+exp(1).^(2.* ...
  logthetay).*(x+(-1).*xp).^2+2.*exp(1).^(2.*logthetax).*(y+(-1).*yp).^2) ...
  .*(y+(-1).*yp)).*(y+(-1).*yp))+a1.*dt.*exp(1).^(a2+(-2).*logthetax+ ...
  logthetay).*(exp(1).^logthetay.*ubar.*(x+(-1).*xp).*((-2).*exp(1).^(2.* ...
  logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+(-1).*exp(1).^(( ...
  -1).*logthetax).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^( ...
  logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+( ...
  -6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^( ...
  logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1) ...
  .*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4))+ ...
  vbar.*((-15).*exp(1).^(2.*(logthetax+logthetay))+(-3).*exp(1).^( ...
  logthetax+3.*logthetay)+3.*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+10.* ...
  exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+exp(1).^(logthetax+2.* ...
  logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(2.*logthetay).*(x+(-1).*xp) ...
  .^2.*(y+(-1).*yp).^2+(-1).*exp(1).^(2.*logthetax).*(y+(-1).*yp).^4).*(y+ ...
  (-1).*yp))+(-1).*dt.*exp(1).^(a2+(-4).*logthetax).*((-2).*exp(1).^(a2+ ...
  2.*logthetax+4.*logthetay).*(exp(1).^logthetay+(-1).*(y+(-1).*yp).^2)+ ...
  4.*exp(1).^(a2+logthetax+4.*logthetay).*(x+(-1).*xp).^2.*(exp(1) ...
  .^logthetay+(-1).*(y+(-1).*yp).^2)+(-2).*exp(1).^(a2+2.*(logthetax+ ...
  logthetay)).*(6.*exp(1).^(2.*logthetax+logthetay)+exp(1).^(logthetax+2.* ...
  logthetay)+(-1).*exp(1).^(2.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^( ...
  2.*logthetax).*(y+(-1).*yp).^2)+exp(1).^(a2+2.*logthetay).*((-1).*exp(1) ...
  .^logthetax+(x+(-1).*xp).^2).*(3.*exp(1).^(2.*(logthetax+logthetay))+ ...
  exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).* ...
  xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).* ...
  exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay) ...
  .*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp) ...
  .^4)+exp(1).^(a2+2.*logthetax).*((-1).*exp(1).^logthetay+(y+(-1).*yp) ...
  .^2).*(3.*exp(1).^(2.*(logthetax+logthetay))+exp(1).^(logthetax+3.* ...
  logthetay)+(-1).*exp(1).^(3.*logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^( ...
  2.*logthetax+logthetay).*(y+(-1).*yp).^2+(-1).*exp(1).^(logthetax+2.* ...
  logthetay).*(y+(-1).*yp).^2+exp(1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+ ...
  (-1).*yp).^2+exp(1).^(2.*logthetax).*(y+(-1).*yp).^4)+(-4).*exp(1).^(a2+ ...
  2.*logthetax+logthetay).*((-6).*exp(1).^(2.*logthetax+logthetay)+(-1).* ...
  exp(1).^(logthetax+2.*logthetay)+exp(1).^(2.*logthetay).*(x+(-1).*xp) ...
  .^2+2.*exp(1).^(2.*logthetax).*(y+(-1).*yp).^2).*(y+(-1).*yp).^2)+exp(1) ...
  .^(a2+(-2).*logthetax+2.*logthetay).*(3.*exp(1).^(2.*(logthetax+ ...
  logthetay))+exp(1).^(logthetax+3.*logthetay)+(-1).*exp(1).^(3.* ...
  logthetay).*(x+(-1).*xp).^2+(-6).*exp(1).^(2.*logthetax+logthetay).*(y+( ...
  -1).*yp).^2+(-1).*exp(1).^(logthetax+2.*logthetay).*(y+(-1).*yp).^2+exp( ...
  1).^(2.*logthetay).*(x+(-1).*xp).^2.*(y+(-1).*yp).^2+exp(1).^(2.* ...
  logthetax).*(y+(-1).*yp).^4));

case 6 % logsigmap

K=dt.^2.*exp(1).^(logsigmap+(-2).*logthetaxp+(-1/2).*exp(1).^((-1).* ...
  logthetaxp).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetayp).*(y+(-1) ...
  .*yp).^2).*(exp(1).^logthetaxp+(-1).*(x+(-1).*xp).^2);

case 7 % logthetaxp

K=(-1/2).*dt.^2.*exp(1).^(logsigmap+(-3).*logthetaxp+(-1/2).*exp(1).^((-1) ...
  .*logthetaxp).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1).*logthetayp).*(y+( ...
  -1).*yp).^2).*(2.*exp(1).^(2.*logthetaxp)+(-5).*exp(1).^logthetaxp.*(x+( ...
  -1).*xp).^2+(x+(-1).*xp).^4);

case 8 % logthetayp

K=(1/2).*dt.^2.*exp(1).^(logsigmap+(-2).*logthetaxp+(-1).*logthetayp+( ...
  -1/2).*exp(1).^((-1).*logthetaxp).*(x+(-1).*xp).^2+(-1/2).*exp(1).^((-1) ...
  .*logthetayp).*(y+(-1).*yp).^2).*(exp(1).^logthetaxp+(-1).*(x+(-1).*xp) ...
  .^2).*(y+(-1).*yp).^2;

otherwise

        K = zeros(n_x, n_xp);
end

end


function [diff_dose] = dicomrt_dosediff(doseone,dosetwo,method,dose_xmesh,dose_ymesh,dose_zmesh,VOI,voi2use)
% dicomrt_dosediff(doseone,dosetwo,method,dose_xmesh,dose_ymesh,dose_zmesh,VOI,voi2use)
%
% Calculate dose difference between two 3D matrices
%
% doseone and dosetwo can be rtplan and/or monte carlo 3D dose distributions.
% method is an OPTIONAL rameter which specify the way doses are normalised
%
% 1. method=a          matrices are normalised to the value a expressed in Gy
% 2. method=[x, y, z]  matrices are independently normalised to the dose value at point (x,y,z) (in cm)
% 3. method=dmean      matrices are independently normalised to the mean dose value in VOI voi2use (key insensitive)
% 4. method=0          matrices are not normalised (default)
%
% dose_xmesh,dose_ymesh,dose_zmesh are OPTIONAL x-y-z coordinates of the center of the matrix voxels
% VOI is a cell array which contain the patients VOIs (OPTIONAL to use with option 3)
% voi2use is a vector pointing to the number of VOI (OPTIONAL to use with option 3)
%
% Examples:
%
% C=dicomrt_dosediff(A,B,0,dose_xmesh,dose_ymesh,dose_zmesh,VOI,0)
% Store in C the dose difference between B and A. C=(B-A).
%
% C=dicomrt_dosediff(A,B,60,method,dose_xmesh,dose_ymesh,dose_zmesh,VOI,voi2use)
% Store in C the dose difference between Bnorm and Anorm. C=(Bnorm-Anorm), where
% Bnorm and Anorm are normalised to 60Gy (100%).
%
% C=dicomrt_dosediff(A,B,[10.5 -18 7],method,dose_xmesh,dose_ymesh,dose_zmesh)
% Store in C the dose difference between Bnorm and Anorm. C=(Bnorm-Anorm), where
% Bnorm and Anorm are normalised to the respective dose values at dnorm=(10.5 -18 7).
%
% C=dicomrt_dosediff(A,B,'Dmean',method,dose_xmesh,dose_ymesh,dose_zmesh,VOI,3)
% Store in C the dose difference between Bnorm and Anorm. C=(Bnorm-Anorm), where
% Bnorm and Anorm are normalised to the respective mean dose values in VOI number 3
%
% See also: dicomrt_doseratio, dicomrt_loadmcdose
%
% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org)

% Check number of argument and set-up some parameters and variables
error(nargchk(2,8,nargin))

% Define parameter
voilookup=1;
filter=0;
dosenorm=0;

% Check case and set-up some parameters and variables
[doseone_dose_temp,type_doseone_dose,labeld1]=dicomrt_checkinput(doseone,1);
[dosetwo_dose_temp,type_dosetwo_dose,labeld1]=dicomrt_checkinput(dosetwo,1);
doseone_dose=dicomrt_varfilter(doseone_dose_temp);
dosetwo_dose=dicomrt_varfilter(dosetwo_dose_temp);

if exist('VOI')==1 & exist('voi2use')==1
    if strcmpi(type_doseone_dose,'mc')==1
        doseone_dose_temp=dicomrt_mask(VOI,doseone_dose_temp,dose_xmesh,dose_ymesh,dose_zmesh,voilookup,filter,'y');
    end
    if strcmpi(type_dosetwo_dose,'mc')==1
        dosetwo_dose_temp=dicomrt_mask(VOI,dosetwo_dose_temp,dose_xmesh,dose_ymesh,dose_zmesh,voilookup,filter,'y');
    end
end

% Create label for dose diff
%if type_doseone_dose=='mc' & type_dosetwo_dose=='rtplan'
%    dose_diff_label='rtplan -mc'
%elseif type_doseone_dose=='mc' & type_dosetwo_dose=='mc'
%    dose_diff_label='mc2 - mc1'
%elseif type_doseone_dose=='rtplan' & type_dosetwo_dose=='mc'
%    dose_diff_label='mc - rtplan'
%else
%    dose_diff_label='rtplan2 - rtplan1'
%end

if exist('method')==1
    if isnumeric(method)==1 & length(method)==1 & method~=0
        % normalize to a specific dose level passed through "method"
        doseone_dose=doseone_dose./method.*100;
        dosetwo_dose=dosetwo_dose./method.*100;
        diff_dose=dosetwo_dose-doseone_dose;
    elseif isnumeric(method)==1 & length(method)==1 & method==0
        % no normalisation is carried out
        diff_dose=dosetwo_dose-doseone_dose;
    elseif isnumeric(method)==1 & length(method)==3 & ...
            (exist('dose_xmesh')~=1 | exist('dose_ymesh')~=1 | exist('dose_zmesh')~=1)
        error('dicomrt_dosediff: This normalisation method requires mesh to be provided. Exit now!');
    elseif isnumeric(method)==1 & length(method)==3 & ...
            (exist('dose_xmesh')==1 | exist('dose_ymesh')==1 | exist('dose_zmesh')==1)
        % normalize to a specific point in 3D passed through "method"
        locx=dicomrt_findpointVECT(dose_xmesh,method(1));
        locy=dicomrt_findpointVECT(dose_ymesh,method(2));
        locz=dicomrt_findpointVECT(dose_zmesh,method(3));
        doseone_dose=doseone_dose./doseone_dose(locy,locx,locz).*100;
        dosetwo_dose=dosetwo_dose./dosetwo_dose(locy,locx,locz).*100;
        diff_dose=dosetwo_dose-doseone_dose;
    elseif ischar(method)==1 & strcmpi(method,'dmean')==1 & ...
            (exist('VOI')~=1 | exist('voi2use')~=1)
        error('dicomrt_dosediff: This normalisation method requires VOI and voi2use to be provided. Exit now!');
    elseif ischar(method)==1 & strcmpi(method,'dmean')==1 & ...
            (exist('VOI')==1 | exist('voi2use')==1)
        % normalize to dmean
        dmean_one=dicomrt_MDcal(doseone,0,dose_xmesh,dose_ymesh,dose_zmesh,VOI,voi2use);
        dmean_two=dicomrt_MDcal(dosetwo,0,dose_xmesh,dose_ymesh,dose_zmesh,VOI,voi2use);
        doseone_dose=doseone_dose./dmean_one.*100;
        dosetwo_dose=dosetwo_dose./dmean_two.*100;
        diff_dose=dosetwo_dose-doseone_dose;
    end
else
    % no normalisation is carried out
    diff_dose=dosetwo_dose-doseone_dose;
end

% Restore original variable format
[diff_dose]=dicomrt_restorevarformat(dosetwo_dose_temp,diff_dose);

% Label Plan and update time of creation
if iscell(diff_dose)==1
    diff_dose{1,1}{1}.RTPlanLabel=[diff_dose{1,1}{1}.RTPlanLabel,'-DDIFF'];
    diff_dose{1,1}{1}.RTPlanDate=date;
    time=fix(clock);
    creationtime=[num2str(time(4)),':',num2str(time(5))];
    diff_dose{1,1}{1}.RTPlanTime=creationtime;
end


function [Ep,Cp] = spm_dcm_sparse(DCM,field)
% Bayesian model reduction of all permutations of model parameters
% FORMAT [RCM,BMR] = spm_dcm_sparse(DCM,field
%
% DCM      - A single estimated DCM (or PEB) structure:
%
%  DCM.M.pE  - prior expectation
%  DCM.M.pC  - prior covariance
%  DCM.Ep    - posterior expectation
%  DCM.Cp    - posterior covariances
%  DCM.gamma - prior variance    of reduced parameters (default: 0)
%
% field      - parameter fields in DCM{i}.Ep to optimise [default: {'A','B'}]
%             'All' will invoke all fields (i.e. random effects)
%             If Ep is not a structure, all parameters will be considered
%
% Returns:
%  Ep    - (BMA) posterior expectation
%  Cp    - (BMA) posterior covariance
%
%--------------------------------------------------------------------------
% This routine searches over reduced (nested) models of a full model (DCM)
% using Bayesian model reduction and performs Bayesian Model Averaging.
% 'Reduced' means some free parameters (parameters with a non-
% zero prior covariance) are switched off by fixing their prior variance
% to zero.This version incorporates a sparsity  prior over models (with a
% Gaussian hyperprior). In other words, the free energy is taken to be the
% likelihood of some data under a given model. The prior on that model
% corresponds to a softmax function of the prior entropy. Finally, the
% softmax (Gibbs) parameter is equipped with a Gaussian prior. Using
% Bayesian model reduction, this routine evaluates the joint probability
% over model and softmax sparsity parameter. The marginals over model space
% are then used to form Bayesian model averaging.
%
% The greedy search in this version simply evaluates the log evidence of
% models with and without each parameter and then successively removes the
% parameters with the least evidence.
%
% See also: spm_dcm_bmr and spm_dcm_bmr_all
%__________________________________________________________________________
% Copyright (C) 2010-2014 Wellcome Trust Centre for Neuroimaging

% Karl Friston, Peter Zeidman
% $Id: spm_dcm_sparse.m 7082 2017-05-27 19:36:36Z karl $

%-Number of parameters to consider before invoking greedy search
%--------------------------------------------------------------------------
nmax  = 8;

%-specification of null prior covariance
%--------------------------------------------------------------------------
if isfield(DCM,'beta'),  beta  = DCM.beta;  else, beta  = 0; end
if isfield(DCM,'gamma'), gamma = DCM.gamma; else, gamma = 0; end

%-Check fields of parameter stucture
%--------------------------------------------------------------------------
if nargin < 2 || isempty(field)
    field = {'A','B'};
end
if ischar(field)
    field = {field};
end

%-dela with filenames stucture
%--------------------------------------------------------------------------
if ischar(DCM)
    DCM = load(DCM,'DCM');
    DCM = DCM.DCM;
end

% Get prior covariances
%--------------------------------------------------------------------------
if isstruct(DCM.M.pC), DCM.M.pC = diag(spm_vec(DCM.M.pC)); end
if spm_length(DCM.M.pE) ~= size(DCM.M.pC,1)
    DCM.M.pC = diag(spm_vec(DCM.M.pC));
end

% Get priors and posteriors
%--------------------------------------------------------------------------
qE  = DCM.Ep;
qC  = DCM.Cp;
pE  = DCM.M.pE;
pC  = DCM.M.pC;

% Remove (a priori) null space
%--------------------------------------------------------------------------
U   = spm_svd(pC);
qE  = U'*spm_vec(qE);
pE  = U'*spm_vec(pE);
qC  = U'*qC*U;
pC  = U'*pC*U;

%-Greedy search (GS) - eliminating parameters in a top down fashion
%==========================================================================

% Accumulated reduction vector (C)
%--------------------------------------------------------------------------
q   = diag(DCM.M.pC);
if sum(q < 1024)
    C   = double(q > mean(q(q < 1024))/1024);
else
    C   = double(q > 0);
end

%-Find free coupling parameters
%----------------------------------------------------------------------
if isstruct(DCM.Ep)
    k = spm_fieldindices(DCM.Ep,field{:});
else
    k = 1:spm_length(DCM.Ep);
end
k     = k(find(C(k))); %#ok<FNDSB>

% Model search over new prior without the i-th parameter
%------------------------------------------------------------------
nparam = length(k);
for i  = 1:nparam

    % Identify parameters to retain r and to remove s
    %--------------------------------------------------------------
    r    = C; r(k(i)) = 0; s = 1 - r;

    % Create reduced priors
    %--------------------------------------------------------------
    R    = U'*diag(r + s*gamma)*U;
    rC   = R*pC*R;
    F(i) = spm_log_evidence(qE,qC,pE,pC,pE,rC);

end

% Find parameters with the least evidence
%--------------------------------------------------------------------------
[F,i] = sort(-F);
k     = k(i);
M     = cell(0);
for i = 1:nparam

    % parameters to retain (r) and to remove (s)
    %----------------------------------------------------------------------
    r    = C; r(k(1:i)) = 0; s = 1 - r;

    % Create reduced prior covariance matrix
    %----------------------------------------------------------------------
    R    = U'*diag(r + s*gamma)*U;
    rC   = R*pC*R;

    % record
    %----------------------------------------------------------------------
    M(i).F  = spm_log_evidence(qE,qC,pE,pC,pE,rC)
    M(i).H  = spm_logdet(rC);
    M(i).rC = rC;

end

% Sparsity hyperpriors
%--------------------------------------------------------------------------
s     = (1:64)/64;
Ps    = exp(-((1:64) - 32).^2/(2*16));
Ps    = Ps/sum(Ps);

%  model likelihood, model prior and  sparsity hyperprior
%--------------------------------------------------------------------------
Lm    = spm_softmax(spm_vec(M.F));
for i = 1:numel(s)
    Pm      = spm_softmax(-s(i)*spm_vec(M.H));
    Qm(:,i) = Lm.*Pm*Ps(i);
end

% evidence and log evidence
%--------------------------------------------------------------------------
Qm    = Qm/sum(sum(Qm));
G     = log(sum(Qm,2));

%-Bayesian model average
%==========================================================================
qE    = DCM.Ep;
qC    = DCM.Cp;
pE    = DCM.M.pE;
pC    = DCM.M.pC;
pE    = spm_vec(pE);
Gmax  = max(G);
BMA   = {};
for i = 1:length(G)
    if G(i) > (Gmax - 4)
        [F,Ep,Cp]    = spm_log_evidence_reduce(qE,qC,pE,pC,pE,M(i).rC);
        BMA{end + 1} = struct('Ep',Ep,'Cp',Cp,'F',F);
    end
end

BMA   = spm_dcm_bma(BMA);
Ep    = BMA.Ep;
Cp    = BMA.Cp;
if isstruct(Cp) || (spm_length(Cp) == spm_length(Ep))
    Cp = diag(spm_vec(Cp));
end

% Show results
% -------------------------------------------------------------------------
GRAPHICS = 1;

if ~GRAPHICS, return, end

spm_figure('Getwin','BMR - all'); clf
subplot(3,2,1)
imagesc(log(Qm)')
title('Joint density','FontSize',16)
xlabel('model','FontSize',12)
ylabel('sparsity','FontSize',12)
axis square

subplot(3,2,2)
plot(DCM.Ep,Ep,'.',DCM.Ep,DCM.Ep,':')
title('Full and reduced expectations','FontSize',16)
xlabel('Full expectations','FontSize',12)
ylabel('Reduced expectations','FontSize',12)
axis square

subplot(3,2,3)
plot(s,sum(Qm,1))
title('Marginal over sparsity','FontSize',16)
xlabel('sparsity parameter','FontSize',12)
ylabel('probability','FontSize',12)
axis square

subplot(3,2,4)
plot(sum(Qm,2))
title('Marginal over  model','FontSize',16)
xlabel(' model','FontSize',12)
ylabel('probability','FontSize',12)
axis square
drawnow


function [w, s, h] = gp_pak(gp, param)
%GP_PAK  Combine GP parameters into one vector
%
%  Description
%    W = GP_PAK(GP, PARAM) takes a Gaussian Process structure
%    GP and string PARAM defining, which parameters are packed and
%    combines the parameters into a single row vector W. If PARAM
%    is not given the function packs all parameters.
%
%    Each of the following strings in PARAM defines one group of
%    parameters to pack:
%      covariance  - pack parameters of covariance function
%      likelihood  - pack parameters of likelihood
%      inducing    - pack inducing inputs (in sparse approximations):
%                    W = gp.X_u(:)
%
%    By combining the strings one can pack more than one group of
%    parameters. For example:
%      covariance+inducing  - pack covariance function parameters
%                             and inducing inputs
%      covariance+likelih   - pack covariance function parameters
%                             and likelihood parameters
%
%    Inside each group (such as covariance functions) the
%    parameters to be packed is defined by the existence of a prior
%    structure. For example, if GP has two covariance functions but
%    only the first one has prior for its parameters then only the
%    parameters of the first one are packed. Thus, also inducing
%    inputs require prior if they are to be optimized.
%
%    GP_PAK and GP_UNPAK functions are used, e.g., when GP
%    parameters are optimized with GP_OPTIM or sampled with GP_MC.
%    See GP_SET and option 'infer_params'.
%
%    [W, WS] = GP_PAK(GP, PARAM) returns also cell array of string
%    labels for the weight vector elements, which makes diagnostics
%    easier.
%
%    [W, WS, H] = GP_PAK(GP, PARAM) returns also hierarchy level H of
%    different parameters (0 for likelihood parameters and 1 for covariance
%    function parameters)
%
%  See also
%    GP_UNPAK, GP_SET
%
% Copyright (c) 2007-2010 Jarno Vanhatalo

% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.

  w = []; s = {}; h = [];

  if isfield(gp,'etr') && length(gp.etr) > 1
    if strcmp(gp.type, 'PIC_BLOCK') || strcmp(gp.type, 'PIC')
      ind = gp.tr_index;           % block indeces for training points
      gp = rmfield(gp,'tr_index');
    end
    ns = length(gp.etr);
    for i1 = 1:ns
      Gp = take_nth(gp,i1);
      [w(i1,:), s, h] = gp_pak(Gp);
    end
  else

    if nargin < 2
      param = gp.infer_params;
    end

    % Pack SVI variational parameters
    if isfield(gp, 'latent_method') && isequal(gp.latent_method,'SVI') ...
        && isfield(gp, 't1')
      w=[gp.t1; gp.t2(:)]';
      if length(gp.t1)>1
        s = [s; sprintf('E[u] x %d', gp.nind); ...
          sprintf('Cov[u] x %d', gp.nind^2)];
      else
        s = [s; 'E[u]'; 'Cov[u]'];
      end
    end

    % Pack the parameters of covariance functions
    if ~isempty(strfind(param, 'covariance'))
      ncf = length(gp.cf);

      for i=1:ncf
        gpcf = gp.cf{i};
        [wi, si, hi] = gpcf.fh.pak(gpcf);
        w = [w wi];
        s = [s; si];
        h = [h hi];
      end
    end

    % Pack the parameters of likelihood function
    if ~isempty(strfind(param, 'likelihood'))
      [wi, si, hi] = gp.lik.fh.pak(gp.lik);
      if isfield(gp, 'latent_method') && isequal(gp.latent_method, 'SVI') ...
          && ~isequal(gp.lik.type, 'Gaussian') && isfield(gp, 't1') ...
          && ~isempty(gp.lik.p.sigma2)
        wi=log(gp.lik.sigma2);
        si='log(sigma2)';
        hi=0;
      end
      w = [w wi];
      s = [s; si];
      h = [h hi];
    end

    % Pack the parameters of the second likelihood function (monotonic)
    if ~isempty(strfind(param, 'likelihood')) && isfield(gp, 'lik_mono')
      [wi, si, hi] = gp.lik_mono.fh.pak(gp.lik_mono);
      if isfield(gp, 'latent_method') && isequal(gp.latent_method, 'SVI') ...
           && isfield(gp, 't1') && ~isempty(gp.lik_mono.p.sigma2)
        wi=log(gp.lik_mono.sigma2);
        si='log(sigma2_mono)';
        hi=0;
      end
      w = [w wi];
      s = [s; si];
      h = [h hi];
    end

    % Pack the inducing inputs
    if ~isempty(strfind(param, 'inducing'))
      if isfield(gp,'p') && isfield(gp.p, 'X_u') && ~isempty(gp.p.X_u)
        if ~iscell(gp.p.X_u)
          % One prior for all inducing inputs
          w = [w reshape(gp.X_u', numel(gp.X_u),1)'];
%           w = [w gp.X_u'];
          s = [s; sprintf('inducing x %d',numel(gp.X_u))];
          h = [h ones(1,numel(gp.X_u))];
          [wi,si,hi]=gp.p.X_u.fh.pak(gp.p.X_u);
          w = [w wi];
          s = [s; si];
          h = [h 1+hi];
        else
          % Own prior for each inducing input
          for i=1:size(gp.X_u,1)
            w = [w gp.X_u(i,:)];
            s = [s; sprintf('inducing x %d',numel(gp.X_u(i,:)))];
            h = [h ones(1,size(gp.X_u(i,:),2))];
            [wi,si,hi]=gp.p.X_u{i}.fh.pak(gp.p.X_u{i});
            si=strcat(repmat('prior-', size(si,1),1),si);
            w = [w wi];
            s = [s; si];
            h = [h 1+hi];
          end
        end
      end
    end

    % Pack the prior weights and variances of mean functions
    if ~isempty(strfind(param, 'mean'))
      mf = length(gp.meanf);

      for i=1:mf
        gpmf = gp.meanf{i};
        [wi, si, hi] = gpmf.fh.pak(gpmf);
        w = [w wi];
        s = [s; si];
        h = [h, hi];
      end
    end

  end

end


function Ml = hmxPlus(Ml,Mr)
%+========================================================================+
%|                                                                        |
%|         OPENHMX - LIBRARY FOR H-MATRIX COMPRESSION AND ALGEBRA         |
%|           openHmx is part of the GYPSILAB toolbox for Matlab           |
%|                                                                        |
%| COPYRIGHT : Matthieu Aussal (c) 2017-2018.                             |
%| PROPERTY  : Centre de Mathematiques Appliquees, Ecole polytechnique,   |
%| route de Saclay, 91128 Palaiseau, France. All rights reserved.         |
%| LICENCE   : This program is free software, distributed in the hope that|
%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use,    |
%| redistribute and/or modify it under the terms of the GNU General Public|
%| License, as published by the Free Software Foundation (version 3 or    |
%| later,  http://www.gnu.org/licenses). For private use, dual licencing  |
%| is available, please contact us to activate a "pay for remove" option. |
%| CONTACT   : matthieu.aussal@polytechnique.edu                          |
%| WEBSITE   : www.cmap.polytechnique.fr/~aussal/gypsilab                 |
%|                                                                        |
%| Please acknowledge the gypsilab toolbox in programs or publications in |
%| which you use it.                                                      |
%|________________________________________________________________________|
%|   '&`   |                                                              |
%|    #    |   FILE       : hmxPlus.m                                     |
%|    #    |   VERSION    : 0.40                                          |
%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |
%|  ( # )  |   CREATION   : 14.03.2017                                    |
%|  / 0 \  |   LAST MODIF : 14.03.2018                                    |
%| ( === ) |   SYNOPSIS   : Sum of H-Matrix with the rule                 |
%|  `---'  |                Full > H-Matrix > Compr                       |
%+========================================================================+

% Check dimensions
if sum(size(Ml) ~= size(Mr))
    error('hmxPlus.m : matrix dimensions must agree.')
end

%%% H-Matrix + H-Matrix -> H-Matrix
if isa(Ml,'hmx') && isa(Mr,'hmx')
    % H-Matrix + H-Matrix --> H-Matrix (recursion)
    if (Ml.typ == 0) && (Mr.typ == 0)
        % Construction
        for i = 1:4
            Ml.chd{i} = hmxPlus(Ml.chd{i},Mr.chd{i});
        end

        % Fusion
        Ml = hmxFusion(Ml);

    % H-Matrix + Compr -> H-Matrix
    elseif (Ml.typ == 0) && (Mr.typ == 1)
        Ml = hmxPlusAB(Ml,Mr.dat{1},Mr.dat{2});

    % H-Matrix + Full -> Unavailable
    elseif (Ml.typ == 0) && (Mr.typ == 2)
        error('hmxPlus : unvailable case')

    % Compr + --- -> ---
    elseif (Ml.typ == 1)
        Ml = hmxPlusAB(Mr,Ml.dat{1},Ml.dat{2});

    % Full + H-Matrix -> Unavailable
    elseif (Ml.typ == 2) && (Mr.typ == 0)
        error('hmxPlus : unvailable case')

    % Full + Compr -> Full
    elseif (Ml.typ == 2) && (Mr.typ == 1)
        Ml = hmxPlusAB(Ml,Mr.dat{1},Mr.dat{2});

    % Full + Full -> Full
    elseif (Ml.typ == 2) && (Mr.typ == 2)
        Ml.dat = Ml.dat + Mr.dat;

    else
        error('hmxPlus : unvailable case')
    end

%%% H-Matrix + Matrix -> H-Matrix
elseif isa(Ml,'hmx')
    Ml = Ml + hmx(Ml.pos{1},Ml.pos{2},Mr,Ml.tol);

%%% Matrix + H-Matrix -> Matrix
elseif isa(Mr,'hmx')
    Ml = hmx(Mr.pos{1},Mr.pos{2},Ml,Mr.tol) + Mr;

%%% Unavailable
else
    error('hmxPlus.m : unavailable case')
end
end


 function y = mtimes(ob, x)
%function y = mtimes(ob, x)
%	y = G * x	or x = G' * y
%	Copyright 2002-2-20	Jeff Fessler	The University of Michigan

%
%	scalar * G
%
if isa(ob, 'double') & length(x) == 1 & isa(x, 'Gtomo2_dsc')
	y = x;
	y.scale = ob;
	return
end

if ob.apower ~= 1, error notdone, end

%
%	partial projection or backprojection (for ordered subsets)
%
if ob.is_subset
	%
	%	Gt(:,ii)' * x		partial forward projection
	%
	if ~ob.is_transpose
		if ob.is_masked
			x = embed(x, ob.mask);
		end
		y = wtfmex('dsc,proj', ob.arg', single(x), ob.mask, ...
			int32(ob.ia_start), int32(ob.ia_inc), ...
			int32(ob.nthread), ob.chat);
		y = y(:,(ob.ia_start+1):ob.ia_inc:ob.na);

	%
	%	Gt(:,ii) * y		partial back projection
	%
	else
		y = zeros(ob.nb,ob.na);
		ia = (ob.ia_start+1):ob.ia_inc:ob.na;
		y(:,ia) = reshape(x, ob.nb, length(ia));
		y = wtfmex('dsc,back', ob.arg', single(y), ob.mask, ...
			int32(ob.ia_start), int32(ob.ia_inc), ...
			int32(ob.nthread), ob.chat);
		if ob.is_masked
			y = y(ob.mask);
		end
	end

%
%	full projection
%
elseif ~ob.is_transpose
	if ob.is_masked
		x = embed(x, ob.mask);
	end
	y = wtfmex('dsc,proj', ob.arg', single(x), ob.mask, ...
		int32(0), int32(1), int32(ob.nthread), ob.chat);

%
%	full back-projection
%
else
	y = wtfmex('dsc,back', ob.arg', single(x), ob.mask, ...
		int32(0), int32(1), int32(ob.nthread), ob.chat);
	if ob.is_masked
		y = y(ob.mask);
	end
end

y = ob.scale * double(y(:));


function [pos,picon,picoff,janelas,messages]=twave3D(w,timenew,i,freq,S,QRSoff,samp,rrmed,messages)
%
%[pos,picon,picoff,janelas]=twave3D(w,timenew,i,freq,S,QRSoff,samp,rrmed)
%
% multilead T wave delineation
%
%Input Parameters:
%   w: matrix with WT scales 1 to 5
%   timenew:  QRS times in inedexes refering the interval included in the current excerpt (borders excluded)
%   i: beat number
%   freq: sampling frequency (heasig.freq)
%   S: lattest S wave position found in any lead
%   QRSoff: lattest QRS end position found in any lead
%   samp: samples included in the current excerpt (borders excluded)
%   rrmed: Exponentially averaged RR
%
%Output Parameters:
%   pos: fiducial marks structure (position)
%   picon: position of the first relevant modulos maximum in the wavelet
%   picoff: position of the last relevant modulos maximum in the wavelet
%   janelas: T wave seach windows
%
% Rute Almeida
% Last update: Rute Almeida  05AGO2011
%
% Designed for MATLAB Version R12; tested with MATLAB Version R13
%

%%%%%% Constants and Thresholds  !!!!!!!!!!!!!!!!!!!!!!!!!
if ~isfield(messages.setup.wavedet,'umbraldetT')
    messages.setup.wavedet.umbraldetT = 0.25;  % We use umbraldet*sqrt(mean(w(time(i):time(i+1),4).^2))
end
if ~isfield(messages.setup.wavedet,'umbralsig')
    messages.setup.wavedet.umbralsig  =  1/8;
end
if ~isfield(messages.setup.wavedet,'Kton')
    messages.setup.wavedet.Kton = 4;      % 2 4!
end
if ~isfield(messages.setup.wavedet,'inivent_tol')
    messages.setup.wavedet.inivent_tol  =  0.1;
end
if ~isfield(messages.setup.wavedet,'inivent_tol_S')
    messages.setup.wavedet.inivent_tol_S=0.05; % sec
end
if ~isfield(messages.setup.wavedet,'finvent_tol')
    messages.setup.wavedet.finvent_tol=0.240;% sec
end
if ~isfield(messages.setup.wavedet,'finvent_max')
    messages.setup.wavedet.finvent_max=0.6;% sec
end
if ~isfield(messages.setup.wavedet,'min_vent')
    messages.setup.wavedet.min_vent=0.1;%sec
end
if ~isfield(messages.setup.wavedet,'Tmax_Tmin_time_min')
    messages.setup.wavedet.Tmax_Tmin_time_min=0.15;%sec
end
if ~isfield(messages.setup.wavedet,'Tmax_Tmin_bifasic')
    messages.setup.wavedet.Tmax_Tmin_bifasic=2.5;
end

Kton=messages.setup.wavedet.Kton;
Ktoff=messages.setup.wavedet.Kton;
messages.warnings=[messages.warnings {'Recall that in twave3D ktoff=kton.'}];
umbraldetT = messages.setup.wavedet.umbraldetT;
umbralsig = messages.setup.wavedet.umbralsig;
inivent_tol= messages.setup.wavedet.inivent_tol;
inivent_tol_S=messages.setup.wavedet.inivent_tol_S;
finvent_tol=messages.setup.wavedet.finvent_tol;
finvent_max= messages.setup.wavedet.finvent_max;
min_vent=messages.setup.wavedet.min_vent;
Tmax_Tmin_time_min= messages.setup.wavedet.Tmax_Tmin_time_min;%sec
Tmax_Tmin_bifasic=messages.setup.wavedet.Tmax_Tmin_bifasic;% extra criteria
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
janelas=[];%%31May05
% Initialization of auxiliary variables
T = []; Tprima=[]; picon=[]; picoff=[]; Ton=[]; Toff=[]; tipoT=[];
% minapos = []; minppos=[]; maxapos=[]; maxppos=[]; mina=[]; minp=[]; maxa=[];
% maxp=[];
picon_keep=[];%multileadchange
picoff_keep=[];%multileadchange
lead_keep=[];%multileadchange

inivent = round(inivent_tol*freq);   % Begining of window
if ~isempty(S),              % If there is an S wave
    inivent = max(inivent, S-timenew(i)+round(inivent_tol_S*freq));
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% changed 13/06/02 Rute
if rrmed <= freq,
    %if rrmed >= freq,
    finvent = round(finvent_max*freq);     % End of window
else
    finvent = round(rrmed*finvent_max);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  %% changed 13/06/02 Rute

% using timenew from diffferent leads ty ca dist less tahn 0.24 sec!!!
if i~=length(timenew),                 % For last beat in the segment
    finvent = min(finvent,timenew(i+1)-timenew(i)-round(finvent_tol*freq));
else
    finvent = min(finvent,timenew(i)-timenew(i-1)-round(finvent_tol*freq));
end

% We work at scale scale (in general).
if isempty(QRSoff),   % Should never happen, but...
    % begwin = inivent + timenew(i);
    begwin = inivent;
else
    %  begwin = max(inivent + timenew(i), QRSoff+1);
    begwin = max(inivent , QRSoff+1-timenew(i));
end
%endwin = min(finvent + timenew(i),length(w)); %% Rute 20/05/02
endwin = min(finvent ,length(w)); %% Rute 20/05/02
janelas=[janelas; i begwin endwin];%31May05
if ~isempty(begwin+1:endwin ) % 22.04.05

    % Positive maxima and negative minima in the window
    maxpos = begwin + modmax(w(begwin+1:endwin ),2,0,+1);
    minpos = begwin + modmax(w(begwin+1:endwin ),2,0,-1);
    [maxim ind] = max(w(maxpos ));   % The biggest of the positive
    maxpos = maxpos(ind);
    [minim ind] = min(w(minpos ));   % The biggest of the negative
    minpos = minpos(ind);

    if isempty(maxpos),               % If no local positive maximum
        % The maximum will be the first
        % or the last sample
        if (w(begwin )>=w(endwin )) && w(begwin )>0,
            maxpos = begwin; maxim = w(maxpos );
        elseif (w(endwin )>=w(begwin )) && w(endwin )>0,
            maxpos = endwin; maxim = w(maxpos );
        end
    end
    if isempty(minpos),               % if no local negative minimum
        % the minimum will be the first
        % or the last sample
        if (w(begwin )<=w(endwin )) && w(begwin )<0,
            minpos = begwin; minim = w(minpos );
        elseif (w(endwin )<=w(begwin )) && w(endwin )<0,
            minpos = endwin; minim = w(minpos );
        end
    end

    absmax = abs(maxim);
    absmin = abs(minim);

    if i<length(timenew),
        veficaz = sqrt(mean(w .^2)); % all w 03.Dec.04 interval was restricted before
    else                        % if last beat of the segment
        veficaz = sqrt(nanmean(w.^2)); % all w 03.Dec.04 interval was restricted before
    end

    hay_onda = ((absmax>umbraldetT*veficaz)|(absmin>umbraldetT*veficaz));

    % Rute 18/06/02
    if endwin-begwin<(min_vent*freq) % se a janela tem amplitude menor do que min_vent seg enato nao existe onda T
        hay_onda =0;
    end

    % Is there a wave?
    if hay_onda,
        if absmax >= absmin,    % the greatest modulus maximum is the maximum
            % Now we search the two minima nearest to maxpos, one before and one after
            minapos = max(modmax(w(begwin+1:maxpos-1 ),2,0,-1));
            minapos = begwin + minapos; % Position of the negative minimum before the maximum
            if isempty(minapos) && (maxpos ~= begwin) && (w(begwin )<0),
                minapos = begwin;% If no local minimum before the maximum, take the first sample
            end
            minppos = min(modmax(w(maxpos+1:endwin ),2,0,-1));
            minppos = maxpos + minppos; % Position of the positive maximum after the minimum
            if isempty(minppos) && (maxpos ~= endwin) && (w(endwin )<0),
                minppos = endwin;        % If no local minimum after the maximum, take the last sample
            end

            mina = abs(w(minapos ));     % Amplitude of minimum before maximum
            minp = abs(w(minppos ));     % Amplitude of minimum after maximum

            if (mina < umbralsig*absmax), % If mina is not big enough
                mina =[];                  % forget it
            elseif (maxpos-minapos>Tmax_Tmin_time_min*freq), %or if ther are more than 150 ms to maxpos
                mina = [];
            end
            if (minp < umbralsig*absmax), % If minp is not big enough
                minp =[];                  % forget it
            elseif (minppos-maxpos>Tmax_Tmin_time_min*freq), % and also if there are more than 150 ms to maxpos
                minp =[];
            end

            if ~isnan(mina)&~isnan(minp),      %#ok<AND2> %%% NUEVO JP
                if (mina >= minp)&&(minp < umbralsig*absmax*Tmax_Tmin_bifasic),
                    minp = [];
                elseif (minp> mina)&&(mina < umbralsig*absmax*Tmax_Tmin_bifasic),
                    mina = [];
                end
            end

            % Test which modulus maxima are significative and find zero crossings
            if isempty(mina),
                if isempty(minp),
                    tipoT = 2;      % only upwards T wave
                    if maxpos - minapos > 2,         % if not !!!!!!!!!!!
                        ind = zerocros(flipud(w(minapos:maxpos )));   %Scale 3 !!! % also in scale 4!!!!!!! 03.Dec.04
                        T = maxpos - ind +1;                           % Zero crossing = T wave position
                        picoff = maxpos;                               %wavelet  peak to detect offset
                    elseif isempty(minapos);  % If there were no minimum, there is no zero crossing
                        T = picant (w(begwin:maxpos ),maxpos);       % Take the minimum at scale 4
                        if ~isempty(T) %%%%%%%%%%%% 14/06/02 Rute
                            picoff = maxpos;
                        else
                            picoff = []; % if did not exist a peak in scale 4 there is no T
                        end %%%%%%%%%%%% 14/06/02 Rute
                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute
                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];
                    end
                else      % minp exists (is significative) but mina not
                    tipoT = 0;  		%normal T wave
                    if minppos -maxpos >2,       % if not!!!!!!???
                        ind = zerocros(w(maxpos:minppos ));  %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04
                        %                         if isempty(ind) %%%%%%%%%%%%%%Rute 03/09/02
                        %                             ind = zerocros(w(maxpos:minppos));
                        %                         end %%%%%%%%%%%%%%Rute 03/09/02
                        T = maxpos + ind -1;
                        picon = maxpos;		% For determining onset and offset
                        picoff = minppos;
                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute
                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];
                    end
                end
            else
                if isempty(minp),   %  mina exists (is significative) but minp not
                    tipoT = 1;  	%inverted T wave
                    if maxpos -minapos >2,  % if not !!!!!!!!!
                        ind = zerocros(w(minapos:maxpos));  % wavelet zero crossing is T wave peak  %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04
                        %                         if isempty(ind)%%%%%%%%%%%%%%Rute 03/09/02
                        %                             ind = zerocros(w(minapos:maxpos ));  % wavelet zero crossing is T wave peak  %% 03/09/02 Rute
                        %                         end %%%%%%%%%%%%%%Rute 03/09/02
                        T = minapos + ind -1;
                        picon = minapos;
                        picoff = maxpos;
                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute
                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];
                    end
                else    % both mina and minp are significative.  Biphasic wave.
                    tipoT = 5;	% biphasic neg-pos T wave
                    if maxpos - minapos > 2,    %!!!!!!!!!!!!
                        ind = zerocros(flipud(w(minapos:maxpos ))); %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04
                        %                         if isempty(ind) %%%%%%%%%%%%%%Rute 03/09/02
                        %                             ind = zerocros(flipud(w(minapos:maxpos ))); %% 03/09/02 Rute
                        %                         end%%%%%%%%%%%%%%Rute 03/09/02
                        T = maxpos - ind +1;
                        picon = minapos;
                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute
                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];
                    end
                    if minppos - maxpos > 2,    %!!!!!!!!!!!!
                        ind = zerocros(flipud(w(maxpos:minppos ))); %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04
                        %                         if isempty(ind)%%%%%%%%%%%%%%Rute 03/09/02
                        %                             ind = zerocros(flipud(w(maxpos:minppos ))); %% 03/09/02 Rute
                        %                         end %%%%%%%%%%%%%%Rute 03/09/02
                        %Tprima = maxpos + ind -1; %18.11.05
                        Tprima = minppos- ind +1;
                        picoff = minppos;
                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute
                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];
                    end
                end
            end
        else        % If the greatest modulus maximum is the minimum
            % Search two maxima, one before and one after the minimum
            maxapos = max(modmax(w(begwin+1:minpos-1 ),2,0,1));
            maxapos = begwin + maxapos;
            if isempty(maxapos) && (minpos ~= begwin) && (w(begwin )>0),
                maxapos = begwin;
            end
            maxppos = min(modmax(w(minpos+1:endwin ),2,0,1));
            maxppos = minpos + maxppos;
            if isempty(maxppos) && (minpos ~= endwin) && (w(endwin )>0),
                maxppos = endwin;
            end
            maxa = abs(w(maxapos ));
            maxp = abs(w(maxppos )) ;                                   % See if they are significative
            if (maxa < umbralsig*absmin)
                maxa =[];
            elseif (minpos-maxapos>Tmax_Tmin_time_min*freq),
                maxa = [];
            end
            if (maxp < umbralsig*absmin),
                maxp =[];
            elseif (maxppos-minpos>Tmax_Tmin_time_min*freq),
                maxp = [];
            end
            if ~isnan(maxa)&~isnan(maxp),      %#ok<AND2> %%% NUEVO JP
                if (maxa >= maxp)&&(maxp < umbralsig*absmin*Tmax_Tmin_bifasic),
                    maxp = [];
                elseif (maxp> maxa)&&(maxa < umbralsig*absmin*Tmax_Tmin_bifasic),
                    maxa = [];
                end
            end
            % Test which modulus maxima are significative and find zero crossings
            if isempty(maxa),
                if isempty(maxp),
                    tipoT = 3;      % only downwards T wave
                    if minpos - maxapos > 2, %!!!!!!!!
                        ind = zerocros(flipud(w(maxapos:minpos )));   %Scale 3 % also in scale 4!!!!!!! 03.Dec.04
                        %                         if isempty(ind) %%%%%%%%%%%%%%Rute 03/09/02
                        %                             ind = zerocros(flipud(w(maxapos:minpos )));
                        %                         end %%%%%%%%%%%%%%Rute 03/09/02
                        T = minpos - ind +1;
                        picoff = minpos;
                    elseif isempty(maxapos);  % If there were no maximum, there is no zero crossing.
                        T = picant (w(begwin:minpos ),minpos);  % menimo en escala 4.
                        if ~isempty(T) %%%%%%%%%%%% 14/06/02 Rute
                            picoff = minpos;
                        else
                            picoff = []; % if did not exist a peak in scale 4 there is no T
                        end %%%%%%%%%%%% 14/06/02 Rute
                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute
                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];
                    end
                else      % maxp is signficative, but not maxa
                    tipoT = 1;  %inverted T wave
                    if maxppos -minpos >2,  % !!!!!!
                        ind = zerocros(w(minpos:maxppos ));  %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04
                        %                         if isempty(ind) %%%%%%%%%%%%%%Rute 03/09/02
                        %                             ind = zerocros(w(minpos:maxppos ));  %% 03/09/02 Rute
                        %                         end %%%%%%%%%%%%%%Rute 03/09/02
                        T = minpos + ind -1;
                        picon = minpos;		% For calculating onset and offset
                        picoff = maxppos;
                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute
                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];
                    end
                end
            else
                if isempty(maxp),   % maxa is significative, but not maxp
                    tipoT = 0;       %normal T wave
                    if minpos -maxapos >2,
                        ind = zerocros(w(maxapos:minpos )); %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04
                        %                         if isempty(ind) %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute
                        %                             ind = zerocros(w(maxapos:minpos )); %% 03/09/02 Rute
                        %end %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute
                        T = maxapos + ind -1;
                        picon = maxapos;
                        picoff = minpos;
                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute
                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];
                    end
                else    % both maxa and maxp are significative.  Biphasic wave.
                    tipoT = 4;	% biphasic pos-neg T wave
                    if minpos - maxapos > 2,  %!!!!!!!!!!!
                        ind = zerocros(flipud(w(maxapos:minpos ))); %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04
                        %                         if isempty(ind) %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute
                        %                             ind = zerocros(flipud(w(maxapos:minpos ))); %% 03/09/02 Rute
                        %                         end %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute
                        T = minpos - ind +1;
                        picon = maxapos;
                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute
                        %                         [i tipoT]
                        disp('caso nao previsto; onda T nao marcada!')
                    end
                    if maxppos - minpos > 2,    %!!!!!!!!!!!!
                        ind = zerocros(flipud(w(minpos:maxppos ))); %% 07/06/02 Rute % also in scale 4!!!!!!! 03.Dec.04
                        %                         if isempty(ind) %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute
                        %                             ind = zerocros(flipud(w(minapos:maxpos ))); %% 03/09/02 Rute
                        %                         end %%%%%%%%%%%%%%%%%%%% 03/09/02 Rute
                        %Tprima = minpos + ind -1; %18.11.05 DUVIDA
                        Tprima = maxppos- ind +1;
                        picoff = maxppos;
                    else %%%%%%%%%%%%%%%%%%%%% nao faz nada!!!!!!! % 12/06/02  Rute
                        messages.warnings=[messages.warnings {'unknown case: unable to classify T wave.'}];
                    end
                end
            end
        end

        % T wave onset and offset detection
        %if isempty(T), picon=[]; picoff=[]; end

        picon_keep=[picon_keep picon]; %multileadchange
        picoff_keep=[picoff_keep picoff];%multileadchange
        lead_keep=[lead_keep 4];%multileadchange

        if ~isempty(picon),
            Ton = searchon (picon, w(max(begwin,picon-0.12*freq):picon ), Kton);
        end
        if ~isempty(picoff),
            Toff=searchoff(picoff, w(picoff:min([size(w,1) picoff+0.12*freq ])  ) , Ktoff);
            if (Toff > endwin),
                Toff = endwin;
            end
        end
    else
        tipoT=9;
        messages.warnings=[messages.warnings {'unknown case: unable to find T wave in multilead approach using scale 4.'}];
    end       %% utilizar a escala 5 07/06/02 Rute %%%%%%%%%%%%%%%%%%%%%%%%%%%

end
% Filling the structure with positions
if isempty(Ton), Ton = NaN; end;
if isempty(Toff), Toff = NaN;  end;
if isempty(T), T=NaN; end;
if isnan(T),
    picon_keep=[picon_keep NaN]; %multileadchange
    picoff_keep=[picoff_keep NaN];%multileadchange
    lead_keep=[lead_keep NaN];%#ok<NASGU> %multileadchange
end
if isempty(Tprima), Tprima=NaN; end;
if isempty(tipoT), tipoT=NaN; end;
pos.Ton= Ton+samp(1)-1+timenew(i)-1;
pos.Toff= Toff+samp(1)-1+timenew(i)-1;
pos.T= T+samp(1)-1+timenew(i)-1;
pos.Tprima= Tprima+samp(1)-1+timenew(i)-1;
pos.Ttipo= tipoT;
% T = []; Tprima=[]; picon=[]; picoff=[]; Ton=[]; Toff=[]; tipoT=[];
% minapos = []; minppos=[]; maxapos=[]; maxppos=[]; mina=[]; minp=[]; maxa=[];
% maxp=[];
%end
% position.Ton(intervalo(1):intervalo(2)) = pos.Ton+samp(1)-1;
% position.Toff(intervalo(1):intervalo(2))= pos.Toff+samp(1)-1;
% position.T(intervalo(1):intervalo(2)) = pos.T+samp(1)-1;
% position.Tprima(intervalo(1):intervalo(2)) = pos.Tprima+samp(1)-1;
% position.Ttipo(intervalo(1):intervalo(2)) = pos.Ttipo;
% pos.Ton
% Ton = pos.Ton(i)
% Toff= pos.Toff(i)
% T= pos.T(i)
% Tprima = pos.Tprima(i)
% Ttipo= pos.Ttipo(i);
%timenew(i)
%picon_keep
picoff=picoff_keep+timenew(i)-1;
picon=picon_keep+timenew(i)-1;