clc; clear; close all;

N = 15;

fileID = fopen('LebesgueConstant2D.txt','w');
fprintf(fileID,'\\begin{tabular}{ccc}\n');
fprintf(fileID,'N & $\\alpha$-optimized nodes & equidistant nodes \\\\ \\hline\n');

tic;
r1 = -1:0.002:1; s1 = r1; N1 = length(r1);
n_points = (N1 * N1 + N1) / 2;
dr = r1;
ds = -1 * ones(1,N1);
for i = 2:N1
    r_old = dr;
    s_old = ds;
    clear dr ds;
    r_temp = r1(1:(N1 - (i - 1)));
    s_temp = s1(i) * ones(1,N1 - (i - 1));
    dr = [r_old, r_temp];
    ds = [s_old, s_temp];
end
[da,db] = rstoab(dr,ds);

for n = 1:N
    N_p = ((n + 1) * (n + 2)) / 2;
    
    [x_opt,y_opt] = OptimalNodes2D(n);
    [x_equi,y_equi] = EquidistantNodes2D(n);
    
    [r_opt,s_opt] = xytors(x_opt,y_opt);
    [r_equi,s_equi] = xytors(x_equi,y_equi);
    
    values_mode = zeros(N_p,n_points);
    temp = 1;
    for i = 0:n
        for j = 0:(n - i)
            values_mode(temp,:) = ModalBaseValues2D(da,db,i,j);
            temp = temp + 1;
        end
    end
    
    V_opt = VandermondeMatrix2D(n,r_opt,s_opt);
    V_equi = VandermondeMatrix2D(n,r_equi,s_equi);
    
    values_node_opt = inv(V_opt') * values_mode;
    values_node_equi = inv(V_equi') * values_mode;
    
    LebConstPoints_opt = sum(abs(values_node_opt),1);
    LebConstPoints_equi = sum(abs(values_node_equi),1);

    LebConst_opt = max(LebConstPoints_opt);
    LebConst_equi = max(LebConstPoints_equi);
    
    fprintf(fileID,'%d & ',n);
    fprintf(fileID,'%f & ',LebConst_opt);
    fprintf(fileID,'%f',LebConst_equi);
    if n < N
        fprintf(fileID,' \\\\');
    end
    fprintf(fileID,'\n');
end
fprintf(fileID,'\\end{tabular}');
fclose(fileID);
toc;