refactoring and bug fixing