Code refactored, added comments.