Refactored code (from user dmarx)