Refactored code + added comments