
function [y_out,A_YW,mean_y_out,LAMBDA,prf]=learning_BIS_YW(std_y,y,mean_y,A_YW,Mshall,t,epsilon,A1,A2,A3,LAMBDA,neq,nsh,truenonzero,truezeros,njump,gain,picknonzero,picknojumps);
% learning based on solution 0=A1*Pi2*PHI2^2+A2*Pi2*PHI2+A3*Pi2;
% Then 0=A1*Pi2*PHI2*y(t)+A2*y(t)+A3*y(t-1);
% where PLM=> E y(t+1)=Pi2*PHI2*y(t)


y_out=y;
mean_y_out=mean_y(:,end);
prf=0;

%% ALM
% note that the order of variables has changed, Thus the reordering of
% Mshall relative to RE solution(end:-1:1,end:-1:1)
try
y(:,t)=(A1*picknojumps*A_YW*picknonzero+A2)\(-A3*y(:,t-1)+Mshall*epsilon);
catch
    keyboard
end
% mean recursion
if t<3
    mean_y(:,t)=gain*y(:,t)+gain*(1-gain)*y(:,t-1);
else
    mean_y(:,t)=mean_y(:,t-1)+gain*(y(:,t)-mean_y(:,t-1));
end

yhat=y;%-repmat(mean_y(:,t),1,size(y,2));
% yhat(:,end)=yhat(:,end)+randn(neq,1)/1000;
%% regressors
states_all=yhat(truenonzero,:);
if any(isnan(states_all(:,end))) || any(isinf(states_all(:,end)))
    prf=1;
    y_out=y;
    return
end
states=LAMBDA'*states_all;

% if prod(size(LAMBDA))==1;
%     if LAMBDA==0;
%         states=states_all;
%     else
%         [states,LAMBDA]=extract(states_all',nsh-1);
%     states=states';
%     end
% else
%     [states,LAMBDA]=extract(states_all',nsh-1);
%     states=states';
% end
nst=size(states,1);
yhat(:,end)=yhat(:,end)+randn(neq,1)/10; %measurement errors
% correlation recursion
Z=zeros(length(njump),nst);
V=zeros(nst,nst);
kk=2;
Z(:,:,kk)=gain*yhat(njump,kk)*states(:,kk-1)';
V(:,:,kk)=  gain*states(:,kk)*states(:,kk)'+gain*(1-gain)*states(:,kk-1)*states(:,kk-1)';

for kk=3:t
    
    Z(:,:,kk)=Z(:,:,kk-1)+gain*(yhat(njump,kk)*states(:,kk-1)'-Z(:,:,kk-1));
    V(:,:,kk)=V(:,:,kk-1)+gain*(states(:,kk)*states(:,kk)'-V(:,:,kk-1));
end
tmpA=sqrt((1-gain))*Z(:,:,end)/V(:,:,end)*LAMBDA';
tmp=(A1*picknojumps*tmpA*picknonzero+A2)\(-A3*y(:,t-1)+Mshall*epsilon);



if rcond(V(:,:,end))<1e-12;%|| any(tmp(njump,end)>20*std_y(njump));
   
    prf=1;
    
else
    A_YW=sqrt((1-gain))*Z(:,:,end)/V(:,:,end)*LAMBDA';
end


%% update parameters

y_out=y;
mean_y_out=mean_y(:,end);

return
end