N = 128;
PhysicalDomain = [0, 2*pi];                     % Physical Domain scaled to a 2*pi interval
h = (PhysicalDomain(2) - PhysicalDomain(1))/N;

x = linspace(0,2*pi-h,N);
k = [0:N/2 -N/2+1:-1]';

%dt = 0.5*h^2;
dt = 0.001;
tf = 10;
t = 0:dt:tf;

% System Definition
% int the form u_t = G(u)
c = 1; 
u = cell(length(t));
u{1} = zeros(length(x),2);
%Senoidal wave
auxX = [zeros(N/4,1)',x(1:N/2),zeros(N/4,1)'];
u{1}(:,1) = sin(auxX).^2;
u{1}(:,2) = 2.*sin(auxX).*cos(auxX);

%Gaussian wave
%a = 1/2;
%u{1}(:,1) = exp(-((x-pi).^2)/(2*a^2));
%u{1}(:,2) = -((x-pi)./a^2).*exp(-(x-pi).^2);

% Create video object
video = VideoWriter('WaveN128.avi','Uncompressed AVI');
% Change video object options 
video.FrameRate = 10;
% Open video object 
open(video);

figura = figure; set(figura,'units','pixels','position',[10,10,440,340]); 
plot(x,u{1}(:,1))
xlim([0 2*pi]); ylim([-1 1])

frame = getframe(figura);
writeVideo(video,frame);

G = @(t,x) WaveEquation(t,x,k,c);
counter = 0;
for i = 2:length(t);
    counter = counter + 1;
    k1 = G(t(i-1), u{i-1});
    k2 = G(t(i-1), u{i-1} + 0.5.*dt.*k1);
    k3 = G(t(i-1), u{i-1} + 0.5.*dt.*k2);
    k4 = G(t(i-1), u{i-1} + dt.*k3);

    u{i} = u{i-1} + (dt/6).*(k1 + 2.*k2 + 2.*k3 + k4);
    %u{i}(1,1) = 0;
    %u{i}(end,1) = 0;
    
    if counter == 10
        counter = 0;
        plot(x,u{i}(:,1))
        xlim([0 2*pi]); ylim([-1 1])
        title(sprintf('t = %g',t(i)))
        xlabel('x'); zlabel('u')
    
        frame = getframe(figura);
        writeVideo(video,frame);
    end
end

close(video)