This is cleaner. Note this was broken out of a much larger piece of work I did, so if there's any problems, I apologise!