Refactored by Simon Marlow's suggestion