function [K,f] = CreateMatrix(X,T,pospg,wpg,N,Nxi,Neta) 
% [K,f] = CreateMatrix(X,T,pospg,wpg,N,Nxi,Neta) 
%
% Stiffness matrix K and r.h.s vector f obtained by discretizing 
% a convection-diffusion-reaction equation in 2D
%   X:          nodal coordinates
%   T:          connectivities (elements)
%   pospg, wpg: Gauss points an weights in the reference element
%   N,Nxi,Neta: shape functions on the Gauss points 
%


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

% Total number of elements and number of nodes in aech one
[numel,nen] = size(T); 
% Total number of nodes
numnp = size(X,1); 
 
% Allocate storage
K = zeros(numnp,numnp); 
f = zeros(numnp,1); 

if method == 1
    disp('Galerkin formulation');
    tau = 0;
elseif method == 2 
    disp ('SUPG formulation');
    Pe = a*h/(2*nu);
    % alpha = coth(Pe)-1/Pe; 
    % tau_p = alpha*h/(2*a);
    tau_p = h*(1 + 9/Pe^2 +(h*sigma/(2*a))^2)^(-1/2)/(2*a);
    disp(strcat('Recommended value for the stabilization parameter = ',num2str(tau_p)));
    tau = input('Stabilization parameter to be used (press return for using the recommended one)= ');
    if isempty(tau)
        tau = tau_p;
    end
elseif method == 3
    disp('GLS formulation');
    Pe = a*h/(2*nu);
    % alpha = coth(Pe)-1/Pe; 
    % tau_p = alpha*h/(2*a);
    tau_p = h*(1 + 9/Pe^2 +(h*sigma/(2*a))^2)^(-1/2)/(2*a);
    disp(strcat('Recommended value for the stabilization parameter = ',num2str(tau_p)));
    tau = input('Stabilization parameter to be used (press return for using the recommended one)= ');
    if isempty(tau)
        tau = tau_p;
    end
elseif method == 4
    disp('SGS formulation');
    Pe = a*h/(2*nu);
    % alpha = coth(Pe)-1/Pe; 
    % tau_p = alpha*h/(2*a);
    tau_p = h*(1 + 9/Pe^2 +(h*sigma/(2*a))^2)^(-1/2)/(2*a);
    disp(strcat('Coeficiente aconsejado para la estabilización =',num2str(tau_p)));
    tau = input('Coeficiente para la estabilización (return para utilizar el recomendado)= ');
    if isempty(tau)
        tau = tau_p;
    end
else
   error ('Unavailable method')
end 

% Loop on the elements
for ielem = 1:numel 
    % Te: global number of the nodes in the current element
    % Xe: coordenates of the nodes in the current element
    Te = T(ielem,:); 
    Xe = X(Te,:); 
    [Ke,fe] = MatEl(Xe,nen,pospg,wpg,N,Nxi,Neta,tau); 
    % Assemble the element matrices
    K(Te,Te)=K(Te,Te)+Ke; 
    f(Te)=f(Te)+fe; 
    clear Ke; clear fe; 
end 
 
 
 
