Refactoring and fixing code