refactoring and bug fixed