clear;

%% Data

rng(2022);

T = 1;
nSteps_vec = 2.^12;
dt = T/nSteps_vec;
P = 0:dt:T;

Nmin = 3;
Nmax = 10;
N = Nmin:Nmax;

%% Approximated Brownian motion

xi = randn(2^(Nmax+1), 1); 
schauder_t = evalSchauderFunction(Nmax, P);
haar_t = evalHaarFunction(Nmax, P);

W = nan(length(N), length(P));
D = nan(length(N), length(P));
V = nan(1, length(N));
for i = 1:length(N)
    n = N(i);
    W(i,:) = sum(xi(1:2^(n+1)).*schauder_t(1:2^(n+1), :));
    D(i,:) = sum(xi(1:2^(n+1)).*haar_t(1:2^(n+1), :));
    V(i) = sum(abs(W(i,2:end) - W(i,1:end-1)));
end

%% Figures

figure;
plot(P, flip(W), 'Linewidth', 1);
xlabel('t', 'Fontsize', 20);
title('W_n', 'Fontsize', 20);
set(gca, 'FontSize', 20);
saveas(gcf, 'figures/exercise5W.png');

figure;
plot(N, V, 'o-', 'Linewidth', 2);
xlabel('n', 'Fontsize', 20);
title('V_n', 'Fontsize', 20);
set(gca, 'FontSize', 20);
saveas(gcf, 'figures/exercise5V.png');

figure;
plot(P, flip(D), 'Linewidth', 1);
xlabel('t', 'Fontsize', 20);
title('D_n', 'Fontsize', 20);
set(gca, 'FontSize', 20);
saveas(gcf, 'figures/exercise5D.png');