Some small cleanups and refactoring. Fixed minor potential concurrency issue