
function [y_out,A_YW,LAMBDA,Z,V,prf]=learning_BIS_YW(Z,V,std_y,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;

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(y(:,end))) || any(isinf(y(:,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



try
    
    Z(:,:,t)=Z(:,:,t-1)+gain*(yhat(njump,t)*states(:,t-1)'-Z(:,:,t-1));
    V(:,:,t)=V(:,:,t-1)+gain*(states(:,t)*states(:,t)'-V(:,:,t-1));
catch
    keyboard;
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-15%|| any(tmp(njump,end)>20*std_y(njump));
   
    prf=1;
    V(:,:,end)=V(:,:,end-1);
    Z(:,:,end)=Z(:,:,end-1);
    
%     keyboard
    
else
    A_YW=sqrt((1-gain))*Z(:,:,end)/V(:,:,end)*LAMBDA';
end


%% update parameters

y_out=y;


return
end