Refactored code to be easier to understand