Refactored for better separation of concerns