Refactored (thanks to @gakuzzzz)