UPDATED refactored the code.