
function [err0,err1,Err,RM,R2M,D,S]=CompErr(Mod,gtrue,htrue,Ind,err0,err1,ytest_tot,ytest,Utest,p2,nt,VarTest,Multi);%ff è per l'u

nM=size(Multi,2);

stima=Mod;

m=min(size(gtrue));
T = 300; %length of impulse response to compute L2 norm

if size(gtrue,1)>size(gtrue,2);
    gtrue=gtrue';
end
if size(htrue,1)>size(htrue,2);
    htrue=htrue';
end
gtrue=gtrue(:,1:(T+1));
htrue=htrue(:,1:(T+1));

C=stima.c;
BB=stima.b;
A=stima.a;
if size(A,2)<size(C,2) | size(A,2)<size(BB,2)
    ma=max(size(C,2),size(BB,2)-size(A,2));
    A=[A zeros(1,ma)];
end
    
ll1=size(A,2)-size(BB,2);ll2=size(A,2)-size(C,2);
for i=1:m
    B(i,:)=BB(i,:);
end
B=[B zeros(m,ll1)];
C=stima.c;C=[C zeros(1,ll2)];
Lambda=stima.noisevariance;

for i=1:m;
    gh(i,:)=impulse(tf(B(i,:),A,1),T);
end
hh=impulse(tf(C*sqrt(Lambda),A,1),T)';

off0=size(err0,2);
off1=size(err1,2);
err1(1+off1)=norm(htrue-hh)/norm(htrue);%l'htrue potrebbe essere un impulso ma non è mai nulla
t1=1;
t0=0;
for i=1:m;
    if Ind(i+1)==1;
        t1=t1+1;
        err1(t1+off1)=norm(gtrue(i,:)-gh(i,:))/norm(gtrue(i,:));
    else
        t0=t0+1;
        err0(t0+off0)=norm(gtrue(i,:)-gh(i,:));
    end
end

err(1)=norm(htrue-hh)/norm(htrue);
Err1=norm(htrue-hh);
Err2=norm(htrue);
for i=1:m;
    err(i+1)=norm(gtrue(i,:)-gh(i,:))/norm(gtrue(i,:));
    Err1=Err1+norm(gtrue(i,:)-gh(i,:));
    Err2=Err2+norm(gtrue(i,:));
end
Err=Err1/Err2;

for gi=1:nM;
    pred=predict(Mod,[ytest_tot Utest],Multi(gi));pred=iddata(pred);pred=pred.y;
    RM(gi)=norm(pred((p2+1):(p2+nt))-ytest)/sqrt(nt);
    R2M(gi)=1-sum([pred((p2+1):(p2+nt))-ytest].^2)/VarTest;%norm([pred((p2+1):(p2+nt))-ytest]./ytest,1)/nt;
end
S=hh';%parte stocastica
D=gh';%parte determistica


% l1=m+1-size(err0,2);
% err0=[err0 inf*ones(1,l1)];
% l2=m+1-size(err1,2);
% err1=[err1 inf*ones(1,l2)];
