Refactoring and correct some code