Refactoring and minor optimizations
Fix dialog box race condition