Refactoring and bug fix