Refactored to be slightly less awful