Slightly different code structure to the original version in 7578d2fe83a5c8797f8e5f2f5f4852257d224850, but equivalent. Only mentioned as I don't know this bit of the code and I am just comparing to the original.