function tau2 = adjointAssemble(gridNodes,e,ID,ey,u,delta)

% tau2 = adjointAssemble(gridNodes,u,delta)
%          It assembles tau2 = G(gridNodes,u)'*delta,
%          where G(x,u) = [-dAdx11*u, ... -dAdxn2*u]
%          and A denotes the system (permeability) matrix.


tau2 = zeros(size(gridNodes,1)*size(gridNodes,2),1);

% number of nodes (= number of degrees of freedom)
n = max(size(gridNodes));

dAdx = sparse(n,n);

% number of elements
ne = max(size(e));

% permeability of the air
mu0 = 4*pi*1e-7;
% permeability of the ferromagnetic
mur = mu0*5100;

for i=1:ne    
    ei = e(i,:);
    
    if in(ey,i)
        mui = mur;
    else
        mui = mu0;
    end
    
    % size(gradAei) = [3,3*(3*2)]
    gradAei = gradAloc_mu(mui,gridNodes,ei);
        
%    nei = max(size(Aei));
    nei = 3;
    
    for j=1:nei
        for k=1:nei          
            if j==k | (~in(ID,ei(j)) & ~in(ID,ei(k)))
                tau2(2*ei(1)-1) = tau2(2*ei(1)-1) - u(ei(k))*gradAei(j,k)*delta(ei(j));
                tau2(2*ei(1)) = tau2(2*ei(1)) - u(ei(k))*gradAei(j,3+k)*delta(ei(j));
                tau2(2*ei(2)-1) = tau2(2*ei(2)-1) -u(ei(k))*gradAei(j,6+k)*delta(ei(j));
                tau2(2*ei(2)) = tau2(2*ei(2)) - u(ei(k))*gradAei(j,9+k)*delta(ei(j));
                tau2(2*ei(3)-1) = tau2(2*ei(3)-1) - u(ei(k))*gradAei(j,12+k)*delta(ei(j));
                tau2(2*ei(3)) = tau2(2*ei(3)) - u(ei(k))*gradAei(j,15+k)*delta(ei(j));

%                A(ei(j),ei(k)) = A(ei(j),ei(k)) + Aei(j,k);
            end
        end
    end
end
