more refactoring and bug fix