function [Ke,fe] = MatEl(Xe,nnode,pospg,wpg,N,Nxi,Neta,tau) 
% [Ke,fe] = MatEl(Xe,nnode,pospg,wpg,N,Nxi,Neta) 
% 
% Element stiffness matrix Ke and r.h.s vector fe
%   Xe:         nodal coordinates
%   nnode:      number of nodes
%   pospg, wpg: Gauss points and weigths on the reference element
%   N,Nxi,Neta: shape functions and its derivatives (using local coordinates)
%               on the Gauss points
%   tau:        stabilization parameter
%


global velo  diffusion  reaction  h  method

ax = velo(1); 
ay = velo(2); 
nu = diffusion; 
sigma = reaction;
a = norm (velo);


Ke = zeros(nnode,nnode); 
fe = zeros(nnode,1); 
 
% Number of Gauss point on each element
ngaus = size(pospg,1); 
 
% Loop on Gauss points (numerical integration)
for igaus = 1:ngaus 
    N_igaus = N(igaus,:);  
    Nxi_igaus = Nxi(igaus,:);   
    Neta_igaus = Neta(igaus,:);   
    Jacob = [Nxi_igaus*(Xe(:,1))	Nxi_igaus*(Xe(:,2))   
             Neta_igaus*(Xe(:,1))	Neta_igaus*(Xe(:,2))]; 
    dvolu=wpg(igaus)*det(Jacob); 
    res = Jacob\[Nxi_igaus;Neta_igaus]; 
    Nx = res(1,:); 
    Ny = res(2,:); 

    if method == 1          % Galerkin
        convi = ax*Nx+ay*Ny;
        Ke = Ke + (N_igaus'*convi + nu*(Nx'*Nx+Ny'*Ny) + sigma*N_igaus'*N_igaus)*dvolu; 
        aux = Isopar(Xe,N_igaus);
        f_igaus = SourceTerm(aux); 
        fe = fe + N_igaus'*(f_igaus*dvolu); 
    elseif method == 2      % SUPG
        convi = ax*Nx+ay*Ny;
        Ke = Ke + (N_igaus'*convi + nu*(Nx'*Nx+Ny'*Ny) + sigma*N_igaus'*N_igaus  ...
                + tau*(convi'*convi + convi'*sigma*N_igaus))*dvolu ;
        aux = Isopar(Xe,N_igaus);
        f_igaus = SourceTerm(aux); 
        fe = fe + (N_igaus + tau*(ax*Nx+ay*Ny))'*(f_igaus*dvolu); 
    elseif method == 3      % GLS
        convi = ax*Nx + ay*Ny;
        Ke = Ke + (N_igaus'*convi + nu*(Nx'*Nx+Ny'*Ny) + sigma*N_igaus'*N_igaus ...
                + tau*((convi + sigma*N_igaus)'*(convi + sigma*N_igaus)))*dvolu ;
        aux = Isopar(Xe,N_igaus);
        f_igaus = SourceTerm(aux); 
        fe = fe + (N_igaus + tau*(convi+sigma*N_igaus))'*(f_igaus*dvolu); 
    else                    % SGS
        convi = ax*Nx + ay*Ny;
        Ke = Ke + (N_igaus'*convi + nu*(Nx'*Nx+Ny'*Ny) + sigma*N_igaus'*N_igaus ...
                + tau*((convi - sigma*N_igaus)'*(convi + sigma*N_igaus)))*dvolu ;
        aux = Isopar(Xe,N_igaus);
        f_igaus = SourceTerm(aux); 
        fe = fe + (N_igaus + tau*(convi - sigma*N_igaus))'*(f_igaus*dvolu); 
    end
end 
