function Cv = CreConv(velo,X,IEN,elem)
% Cv = CreConv(velo,X,IEN,elem);
% This function computes convection matrix
% for a two-dimensional Navier-Stokes problem
%
% Input:
%
%   velo:   velocity field
%   X:      nodal coordinates (velocity)
%   IEN:    connectivities (velocity)
%   elem:   type of element (0: quadrilateral, 1: triangle)
%


% Total number of elements and element node's number
[numel,nen] = size(IEN); 
% Total number of nodes
if elem == 1 & nen == 4
    numnp = size(X,1) + numel;
else
    numnp = size(X,1);     
end
% Degrees of freedom
ndofn = 2*nen; nunk  = 2*numnp; 

% Number of Gauss points used in the numerical quadrature (ngaus)
% and number of nodes to interpolate the geometry (ngeom)
if elem == 0
    if nen == 4
        ngaus = 4; nnodes = 4;
    elseif nen == 9
        ngaus = 9; nnodes = 9;
    end
else
   if nen == 3
        ngaus = 7; nnodes = 3;
   elseif nen == 6 
        ngaus = 7; nnodes = 6;
   elseif nen == 4 
       ngaus = 12; nnodes = 3;
   end
end

% Quadrature and shape functions on the Gauss points
[pospg,pespg] = Quadrature(elem,ngaus);
[N,Nxi,Neta] = ShapeFunc(elem,nen,pospg);

% Allocates storage for matrices
if nen <= 4
    Cv = spalloc(nunk,nunk,10*nunk); 
else
    Cv = spalloc(nunk,nunk,20*nunk); 
end

% Loop on elements
for ielem = 1:numel
    % Te: current velocity element
    Te = reshape([2*IEN(ielem,:)-1; 2*IEN(ielem,:)],1,ndofn); 
    % Xe: element nodes' coordinates 
    Xe = X(IEN(ielem,1:nnodes),:); 
    % Ve: element nodes' velocity
    Ve = velo(IEN(ielem,:),:); 
    % element matrix
    Cve = zeros(ndofn,ndofn);
    % Loop on Gauss points
    for igaus = 1:ngaus
        % Shape functions on Gauss point igaus
        N_igaus    = N(igaus,:);  
        Nxi_igaus  = Nxi(igaus,:);   
        Neta_igaus = Neta(igaus,:);
        % Jacobian matrix on the Gauss point
        Jacob = [Nxi_igaus(1:nnodes)*(Xe(1:nnodes,1))	Nxi_igaus(1:nnodes)*(Xe(1:nnodes,2))   
                 Neta_igaus(1:nnodes)*(Xe(1:nnodes,1))	Neta_igaus(1:nnodes)*(Xe(1:nnodes,2))];
        % 
        dvolu=pespg(igaus)*det(Jacob); 
        % Shape functions' derivatives in global coordinates
        res = Jacob\[Nxi_igaus;Neta_igaus]; 
        % Shape functions in 2D
        Ngp = [reshape([1;0]*N_igaus,1,ndofn); reshape([0;1]*N_igaus,1,ndofn)];
        % Gradient
        Nx = [reshape([1;0]*res(1,:),1,ndofn); reshape([0;1]*res(1,:),1,ndofn)];
        Ny = [reshape([1;0]*res(2,:),1,ndofn); reshape([0;1]*res(2,:),1,ndofn)];
        % Velocity on point igaus
        v_igaus = Isopar(Ve,N_igaus);
        % Contribution to element matrix
        Cve = Cve + Ngp'*(v_igaus(1)*Nx+v_igaus(2)*Ny)*dvolu; 
    end
    % Assembly
    Cv(Te,Te) =Cv(Te,Te) + Cve; 
end 
clear Cve; 
Cv = sparse(Cv);