Minor refactoring and code cleanup
Fixed race condition