Refactored code to be more readable, added comments