Made code more DRY, added comments