%
% x is the partition, 
% uh is the coefficient vector of the solution,
% ufun is a function handle to exact solution. 
%

function L2error = fem1d_error(x,u,ufun)
    val = 0;

    for i=1:(length(x)-1)
        
        % Gaussian quadrature rule. 
        [t,w] = gaussint(2,x(i),x(i+1));
        
        % evaluate the finite element solution at points t. 
        
        uh_tk = zeros(1,length(t));
        u_tk = zeros(1,length(t));
        
        for k=1:length(t)
            uh_tk(k) = u(i)*( x(i+1)-t(k))/(x(i+1)-x(i));
            uh_tk(k) = uh_tk(k) + u(i+1)*( x(i)-t(k))/(x(i)-x(i+1));
            u_tk(k) = ufun(t(k));
        end
        
        % evaluate the integral
        val = val + (uh_tk - u_tk).^2*w(:);
    end

    L2error = sqrt(val);
end