added comments, refactored to aid readability