% r-adaptivity
% for a given mesh and solution we generate a new adapted mesh by moving
% the existing nodes within the mesh; they get moved to a position in order
% to equally distribute the error over the intervall
% we use the De Boor's algorithm (Huang, Russell; Adaptive Moving Mesh
% Methods; $ 2.2.1)

function mesh = adapt_r(nodes,u,lambda)
    n_nodes = length(nodes);
    flux_jumps = abs(jumps_flux(nodes,u,lambda));
    p = 1/2*(flux_jumps(1:end-1) + flux_jumps(2:end));  % has values for each element
    h_vec = nodes(2:end) - nodes(1:end-1);
    P = cumsum(h_vec'.*p);
    P = [0;P];
    xi = linspace(0,1,n_nodes);
    mesh = nodes;
    for j=2:n_nodes-1
        idx_k = find(xi(j)*P(end) <= P, 1, 'first');
        if idx_k > 1
            x_j = nodes(idx_k-1) + xi(j)*(P(end)-P(idx_k -1))/p(idx_k -1);
            mesh(j) = x_j;
        end
    end
end