Refactored logic to be more readable