Some refactoring and bug fix