minor refactoring and bug fixing