function [ok,globalerr,res]=l2test(ni,x,u,xold,uold,d,Dd,c,r,f,tol,ad,al,ar,bctype)
disp('test')
xcopy=x;
adcopy=ad;
niold=size(xold,2)-1;
ndf=ni-1+sum(bctype);
h=x(2:ni+1)-x(1:ni);
%
for i=1:ni;
res(i)=f(i)+(Dd(i)-c(i))*(u(i+1)-u(i))/h(i)-r(i)*(u(i+1)+u(i))/2;
res(i)=abs(res(i));
end
%
cint=1/sqrt(30)/2;    %interpolation error constant
%
%setting up dual problem
%
x=xcopy(1)+h(1)/2;
wl=(xold(2)-x)/(xold(2)-xold(1));
wr=(x-xold(1))/(xold(2)-xold(1));
ee=(u(2)+u(1))/2-(wl*uold(1)+wr*uold(2));
eefirst=ee;
l2e=ee*ee*h(1);
e(1)=ee*h(1)/2;
index=1;
for i=2:ni-1;
x=xcopy(i)+h(i)/2;
while xold(index)<x;
index=index+1;
end
wl=(xold(index)-x)/(xold(index)-xold(index-1));
wr=(x-xold(index-1))/(xold(index)-xold(index-1));
ee=(u(i+1)+u(i))/2-(wl*uold(index-1)+wr*uold(index));
l2e=l2e+ee*ee*h(i);
e(i-1)=e(i-1)+ee*h(i)/2;
e(i)=ee*h(i)/2;
end
x=xcopy(ni)+h(ni)/2;
wl=(xold(niold+1)-x)/(xold(niold+1)-xold(niold));
wr=(x-xold(niold))/(xold(niold+1)-xold(niold));
ee=(u(ni)+u(ni+1))/2-(wl*uold(niold)+wr*uold(niold+1));
eelast=ee;
l2e=l2e+ee*ee*h(ni);
l2e=sqrt(l2e);
e(ni-1)=e(ni-1)+ee*h(ni)/2;
%
if bctype(1)==1;
e=[eefirst*h(1)/2,e];
end
if bctype(2)==1;
e=[e,eelast*h(ni)/2];
end
%
%solving dual problem
%
adcopy=ad;
for i=2:ndf;
ad(i)=ad(i)-al(i-1)*ar(i-1)/ad(i-1);
e(i)=e(i)-e(i-1)*ar(i-1)/ad(i-1);
end
z(ndf)=e(ndf)/ad(ndf);
for i=ndf-1:-1:1;
e(i)=e(i)-e(i+1)*al(i)/ad(i+1);
z(i)=e(i)/ad(i);
end
%
if bctype(1)==0
z=[0,z];    %given boundary value
end
if bctype(2)==0
z=[z,0];    %given boundary value
end
%
%computing D2z and cstab
%
Dz=(z(2:ni+1)-z(1:ni))./h;
DDz=abs(Dz(2:ni)-Dz(1:ni-1));
DDz=[DDz(1),DDz,DDz(ni-1)];
DDz=(DDz(2:ni+1)+DDz(1:ni))/2;
DDz=DDz./h;
cstab=sqrt(sum(DDz.*DDz.*h))/l2e
%
res=cstab*cint*res;
globalerr=sqrt(sum((h.*h.*res).*(h.*h.*res)));
%
%setting ok flag
%
if globalerr<tol
ok=1;
else
ok=-1;
end
x=xcopy;
ad=adcopy;
