refactoring and bug fix