Code refactored and comments added.