code cleanup and race condition fix