Cleaning up and refactoring the code