% Data
dof=zeros(1,4);
hmesh=zeros(1,4);
err=zeros(1,4);
tt=1;

%No refinment
load('Heat1.mat');
n=1;
dof(n)=length(p(1,:));
%[ATmesh]=pdetrg(p,t);
%hmesh(n) = max(sqrt(2*ATmesh));
hmesh(n) = 0.1;
X = p(1,:)';
Y = p(2,:)';
Sol = u(:,tt+1);
SolA = X.^2+Y.*X-Y.^2+exp(-3*tt);
err(n) = max(abs(Sol-SolA));

%1st refinment
load('Heat2.mat');
n=2;
dof(n)=length(p(1,:));
%[ATmesh]=pdetrg(p,t);
%hmesh(n) = max(sqrt(2*ATmesh));
hmesh(n) = 0.05;
X = p(1,:)';
Y = p(2,:)';
Sol = u(:,tt+1);
SolA = X.^2+Y.*X-Y.^2+exp(-3*tt);
err(n) = max(abs(Sol-SolA));

%2nd refinment
load('Heat3.mat');
n=3;
dof(n)=length(p(1,:));
%[ATmesh]=pdetrg(p,t);
%hmesh(n) = max(sqrt(2*ATmesh));
hmesh(n) = 0.025;
X = p(1,:)';
Y = p(2,:)';
Sol = u(:,tt+1);
SolA = X.^2+Y.*X-Y.^2+exp(-3*tt);
err(n) = max(abs(Sol-SolA));

%3rd refinment
load('Heat4.mat');
n=4;
dof(n)=length(p(1,:));
%[ATmesh]=pdetrg(p,t);
%hmesh(n) = max(sqrt(2*ATmesh));
hmesh(n) = 0.0125;
X = p(1,:)';
Y = p(2,:)';
Sol = u(:,tt+1);
SolA = X.^2+Y.*X-Y.^2+exp(-3*tt);
err(n) = max(abs(Sol-SolA));

%4th refinment
load('Heat5.mat');
n=5;
dof(n)=length(p(1,:));
%[ATmesh]=pdetrg(p,t);
%hmesh(n) = max(sqrt(2*ATmesh));
hmesh(n) = 0.00625;
X = p(1,:)';
Y = p(2,:)';
Sol = u(:,tt+1);
SolA = X.^2+Y.*X-Y.^2+exp(-3*tt);
err(n) = max(abs(Sol-SolA));

%h   = [0.1 0.05 0.025 0.0125 0.00625];
%err = [7.5959e-003 2.5097e-003 7.8935e-004 2.3664e-004 6.8844e-005];
% example 2
%h   = [0.1 0.05 0.025 0.0125];
%err=[0.007557580544144   0.002509677385508   0.000789346196147   0.000236635650353];
% Post-process
figure(1)
loglog(hmesh,err,'kx-')
xlabel('h')
ylabel('Error')
title('Convergence plot (t=1s)')
figure(2)
loglog(dof,err,'kx-')
xlabel('Degrees of Freedom')
ylabel('Error')
title('Convergence plot (t=1s)')
% Compute slopes
n = length(hmesh);
slopes=zeros(n-1,1)
averageslope=0
for i=1:n-1
    slopes(i) = log10(err(i+1)/err(i)) / log10(hmesh(i+1)/hmesh(i));
    averageslope=averageslope+slopes(i)/(n-1);
end
slopes
averageslope