More refactoring, fix race conditions