Added refactored code. Hope this helps.