Fixed an error and refactored code