minor refactoring and bug fix