function [ESTs, ESTc]= kalMeasUpdate(m,M,ESTstate,ESTcov,StateEstimate,CovEstimate,i,NT,NP,nDim,runs,allgamma,idx)

for j=1:NT % go through each measurment
    
    X=StateEstimate;
    IM =StateEstimate ; %mean
    P=CovEstimate;
    B=repmat(M(:,:,1,idx(j),:),1,1,1,1,1,NP);
    B=permute(B,[1,2,3,4,6,5]);
    R=squeeze(repmat(B,1,1,1,NT,1,1));
    R(:,:,:,:,1);
    tmp=repmat(m(:,1,idx(j),:),1,1,1,1,NP);
    tmp=permute(tmp,[1,2,3,5,4]);
    y=(repmat(tmp,1,1,NT,1,1));
    IS = (R + P);
    
    %% kalman gain for all objects and particles
    K = mtimesx(1,mmx('backslash',IS,P),'C');
    X= X + mmx('mult',K, (y-IM));
    P= P- mmx('mult',mmx('mult',K,IS),K,'nt');   %ndfun('mult',(repmat(eye(size(P,1)),1,1,size(P,3),NP)- K),P);
    
    
    %assign to objects
    for r=1:runs
        for e=1:NP
            ESTstate(:,:,allgamma(i(e,r),j),e,r)=X(:,:,allgamma(i(e,r),j),e,r); %Update object where we think this measurment came from
            ESTcov(:,:,allgamma(i(e,r),j),e,r)=P(:,:,allgamma(i(e,r),j),e,r);
        end
        
    end
end
ESTs=ESTstate;
ESTc=ESTcov;
