fix of a couple race conditions --- but the whole logic of this part should be remade