function structdecomp= make_resdecomp_MAIARSV(Y_actual,x_bul,b0_tilde_h,a_h,gamma_h,g_h,sigma_h,fblks,lagsMA)

[n,T]=size(sigma_h);
r=length(fblks);
nrp=length(a_h);
p=nrp/(n*r);

ind_diag_n_T=vec(logical(repmat(eye(n),[1,1,T])));
ind_diag_r_T=vec(logical(repmat(eye(r),[1,1,T])));

B0h=make_B0_restricted(b0_tilde_h,fblks);



A_h=transpose(reshape(a_h,[r*p,n]));

y_hat_insample=make_insampleFit_MAIAR(B0h,A_h,gamma_h,x_bul);

totresids= Y_actual - y_hat_insample;
omegaresids=full(B0h)*totresids;

Omegas=make_TV_RF_covar_matrix(g_h,sigma_h);
Omegasdiag=reshape(Omegas(ind_diag_n_T),[n,T]);
CHIs=mtimesx(mtimesx(full(B0h),Omegas), full(B0h)');
CHISdiag=reshape(CHIs(ind_diag_r_T),[r,T]);


comresMaker=mtimesx(Omegas ,mtimesx(full(B0h)',inv3d(CHIs) ) );
comresids=squeeze(mtimesx(comresMaker, reshape(omegaresids,[r,1,T])));


comresidsVar=mtimesx(mtimesx(comresMaker,CHIs),permute(comresMaker,[2,1,3]));
diagcomresidsVar=reshape(comresidsVar(ind_diag_n_T),[n,T]);


idioresids=totresids-comresids;

idioresidsVar=Omegas-comresidsVar;
diagidioresidsVar=reshape(idioresidsVar(ind_diag_n_T),[n,T]);

%%


CommRegrCommComponent=lagmatrix(omegaresids',[0:lagsMA]);

Y_ComComp=nan(size(Y_actual));
RsqCom=zeros(n,1);

LocalProjComm=nan(n,lagsMA+1); % only if r=1!!!

for jv=1:n
    
    
    
    [~,yfittedjv,~,Rsqjv]=quickOLS_Nointercept_omitNan(CommRegrCommComponent,vec(Y_actual(jv,:)));
    Y_ComComp(jv,:)=vec(yfittedjv,1);
    RsqCom(jv)=Rsqjv;
    
    
    if r<=1
        LeadsYjv=lagmatrix(vec(Y_actual(jv,:)),0:-1:-lagsMA);
        for jlag=1:lagsMA+1
            betajlag=quickOLS_Nointercept_omitNan(CommRegrCommComponent,LeadsYjv(:,jlag));
            LocalProjComm(jv,jlag)=betajlag(1);
        end
    end
    
    
end

Y_Idio=Y_actual-Y_ComComp;


%%


structdecomp.totresids=totresids;
structdecomp.Omegasdiag=Omegasdiag;
structdecomp.CHISdiag=CHISdiag;
structdecomp.comresids=comresids;
structdecomp.diagcomresidsVar=diagcomresidsVar;
structdecomp.idioresids=idioresids;
structdecomp.diagidioresidsVar=diagidioresidsVar;
structdecomp.Y_ComComp=Y_ComComp;
structdecomp.RsqCom=RsqCom;
structdecomp.Y_Idio=Y_Idio;
structdecomp.LocalProjComm=LocalProjComm;




