updated function and refactored code and logic