function dJdp = adjointMethod(p,shapeDisplacement,gridDisplacement,xinit,e,ey,ID,IDD,IDD1,IDD2,Ishape,A,u,B,dIdB,dIdx)

% dJdp = adjointMethod(p,shapeDisplacement,gridDisplacement,xinit,e,ey,ID,IDD,
%		       IDD1,IDD2,Ishape,A,u,B,dIdB,dIdx)
%          calculates gradient of the cost functional
%          by means of the adjoint variable method


[tau1,lambda] = adjointCurl(xinit+gridDisplacement,e,u,dIdB);
delta = A\lambda;
tau2 = adjointAssemble(xinit+gridDisplacement,e,ID,ey,u,delta);
tau = dIdx + tau1 + tau2;
theta = adjointShapeMap(xinit,e,IDD,IDD1,IDD2,Ishape,shapeDisplacement,tau);
dJdp = adjointDesignMap(Ishape,p,theta);
