function Sol = GalerkinSolution(X,T,Conv,W,w,s,Element,nu,sigma,Accd1,bccd1,c,dt,nstep, nodesDir0, nodesDir1)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This function computes the Galerkin solution of the transient convection
% diffusion reaction equation for a multistage scheme (Pade type)
%
% Inputs:
%  X --> nodal coordinates
%  T --> nodal connectivities
%  Conv --> convective velocity of the problem
%  W --> Pade matrix
%  w --> Pade vector
%  s --> source term reference
%  Element --> data structure containing element information such as shape
%  functions, derivatives, Gauss points, etc...
%  nu --> diffusion parameter
%  sigma --> reaction coefficient
%  Accd1 --> matrix of boundary conditions
%  bccd1 --> r.h.s of boundary conditions
%  c --> initial condition
%  dt --> time step
%  nstep --> number of steps for time integration
%  nodesDir0 --> nodes on the boundary where the solution is u=0
%  nodesDir1 --> nodes on the boundary wher the solution is u=1
%
% Outputs:
%  Sol --> solution of the Galerkin formulation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

f = SourceTerm(s); %obtain the value of the source term
npoin = size(X,1);% Number of points used in the discretization

%FEM Matrices obtained by discretizing the Galerking weak form

[M,K,C] = FEM_matrices(X,T,Conv,Element); 
f = f * ones(size(M,1),1); 

% Integration matrix
[n,m] = size(W);
Id = eye(n,m);

% Computation of the matrix necessary to obtain solution at each time-step: A du = F
  
A = [];
for i = 1:n
    row = [];
    for j = 1:m
        row = [row, Id(i,j)*M  + dt*W(i,j)*(C+nu*K+sigma*M)];
    end
    A = [A; row];
end

% Adjust boundary conditions matrix in case is needed (for instance for the
% 4th order Pade where the system is enlarge
nccd = size(Accd1,1);
Accd = []; bccd = [];
for i = 1:n
    row = [];
    for j = 1:m
        row = [row, Id(i,j)*Accd1];
    end
    Accd = [Accd; row];
    bccd = [bccd; bccd1];
end

% Set the whole system for the solution
nccd = n*nccd;
Atot = [A Accd'; Accd zeros(nccd)];

% Initial condition
Sol = c;

% Loop to compute the transient solution
disp(' ')
disp('Transient analysis: computation of the solution at each time step')
for i=1:nstep
    aux = dt*(-(C+nu*K+sigma*M)*c);
    F = [];
    for j =1:n
        F = [F; w(j)*aux];
    end
    F = [F;bccd];  % r.h.s of the system
    dc  = Atot\F; % get the multistage solution
    dc = reshape(dc(1:n*npoin),npoin,n);
    for k = 1 : size(dc,1)
        if any(nodesDir1 == k )
            c(k) = 1; % To avoid summing in the boundary condition nodes
        elseif any(nodesDir0 ==k)
            c(k) = 0; % Same here
        else
            c(k) = c(k) + sum(dc(k,:),2);
        end
    end
    Sol = [Sol c];    
end
end