Refactored to integrate feedback from @intuitivepixel