function est = kest_asyn_pto4(N,A,C,Q,R,x0_,x0,P0,T,u,sys,t,gamma)


% ASYMPTOTIC
fprintf('\nAsymptotic Kalman filtering\n')

    e_post=zeros(4,N);
    fprintf('Compute parameters...')
    [P,eigenvalues,L] = dare(A',C',Q,R); L = L';
    K=A*P*C'*pinv(C*P*C'+R);
    fprintf('done\n')
    fprintf('Compute estimate...')
    
    [y,t,x] = lsim(sys,squeeze(u(:,:)),t,x0); y = y'; x = x';
    
    y_ = [0 0]';
    for j = 1:N
        if( gamma(j) == 1 )
            y_ = y(:,j);
        else
            y(:,j) = y_;
        end
    end
    
    % figure(1000), plot(y(2,:))
    
    x0_post = x0_ + P0*C'*pinv(C*P0*C' + R)*( y(:,1) - C*x0_ ); % da xo a priori a x0 a posteriori
    x_post=x;
    x_post(:,1)=x0_post;
    for j=2:N        
        x_post(:,j)=A*x_post(:,j-1)+K*(y(:,j)-C*A*x_post(:,j-1));
    end
    e_post(:,:)=x-x_post; %Errore di stima a posteriori
    
    fprintf('done\n')
    
    est.P_prior = P;
    est.P_post = P;
    est.L = L;
    est.x_prior = 0;
    est.x_post = x_post;
    
    est.NP_prior=zeros(N,1);
    for j = 1:N
        est.NP_prior(j)=trace(est.P_prior);
    end
    est.OK=1;



