refactored to be more readable and reusable