Refactored and added comments.