Refactored to clean up the code