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

[outs,states] = size(C);

S = equilibrioS(A,C,Q,R,lambda,1e-8);

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


e_post=zeros(4,N);
fprintf('Compute parameters...')
K=S*C'*pinv(C*S*C'+R);
fprintf('done\n')
fprintf('Compute estimate...')

[y,t,x] = lsim(sys,squeeze(u(:,:)),t,x0); y = y'; x = x';
x0_post = x0_ + gamma(1)*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;

P_prior = zeros(states,states,N);
P_prior(:,:,1) = P0;
P_prior_media = zeros(states,states,N);
P_prior_media(:,:,1) = P0;
P_post = zeros(states,states,N);
P_post(:,:,1) = (eye(states)-gamma(1)*K*C)*P_prior(:,:,1)*(eye(states)-gamma(1)*K*C)'+ gamma(1)*K*R*K';
for j=2:N
    x_post(:,j)=A*x_post(:,j-1)+gamma(j-1)*K*(y(:,j)-C*A*x_post(:,j-1));
    P_prior(:,:,j) = A*(eye(states)-gamma(j-1)*K*C)*P_prior(:,:,j-1)*(eye(states)-gamma(j-1)*K*C)'*A' + gamma(j-1)*A*K*R*K'*A' +Q;
    P_post(:,:,j) = (eye(states)-gamma(j)*K*C)*P_prior(:,:,j)*(eye(states)-gamma(j)*K*C)'+ gamma(j)*K*R*K';
    P_prior_media(:,:,j) = lambda*A*(eye(states)-K*C)*P_prior_media(:,:,j-1)*(eye(states)-K*C)'*A'+ (1-lambda)*A*P_prior_media(:,:,j-1)*A'+lambda*A*K*R*K'*A' +Q;
end
e_var=x-x_post(:,1:end); %Errore di stima a posteriori

fprintf('done\n')
est.P_prior = P_prior;
est.P_prior_media=P_prior_media;
est.P_post = P_post;
est.K = K;
est.x_prior = 0;
est.x_post = x_post;


est.NP_prior = zeros(N,1);
est.NP_post = zeros(N,1);
est.NP_prior_media = zeros(N,1);
for j = 1:N
    est.NP_prior_media(j) = trace(est.P_prior_media(:,:,j));
    est.NP_prior(j) = trace(est.P_prior(:,:,j));
    est.NP_post(j) = trace(est.P_post(:,:,j));
end
est.OK=1;

