function U = burgers_ex(X,T,At,nTimeSteps,u0,uxa,uxb,E)
%
% U = burgers_ex(X,T,At,nTimeSteps,u0,uxa,uxb,E)
% Solution of modified Burgers' equation u_t + u?u_xx = E?u_xx
% on (a,b) with Dirichlet boundary conditions on both endpoints,
% using finite differences and an explicit method.
%
% m:        number of subintervals used in the discretization
% At:       time step
% nTimeSteps:    number of time steps
% u0:       initial conditions (it can be a constant value or a (m+1)-dimensional vector)
% uxa, uxb: essential boundary conditions (they can be a constant value or
%           a (nTimeSteps+1)-dimensional vector corresponding to the conditions at each time step)

m = length(X)-1; 

% Allocate memory for the solution matrix
U = zeros(m+1,nTimeSteps+1);

% Initial condition
U(:,1) = u0;

% Boundary conditions
U(1,:) = uxa';
U(m+1,:) = uxb';

M = computeMassMatrix(X,T); 
% K = computeDiffussionMatrix(X,T); 

Accd = zeros(2,m+1); Accd(1,1) = 1; Accd(2,m+1) = 1;  bccd = [uxa; uxb]; 
M_T = [M, Accd'; Accd, zeros(size(Accd,1))]; 
for n = 1:nTimeSteps
    C = computeConvectionMatrix(X,T,U(:,n));
    f=flux(u0,X);
    f = (M - 0.5*At*C)*U(:,n)+f'; 
    f_T = [f; bccd]; 
    sol = M_T\f_T; 
    U(:,n+1) = sol(1:m+1);     
end

function f = flux(u0,X)

    for i=1:length(X)-1
    f(i)=0.5*(u0(i+1)+u0(i));
    end
    
    f(length(X))=(u0(length(X))+u0(length(X)-1))*0.5;



