Note There was a minor error in the code which has now been changed. See source for details. Thanks to Kelley for the sharp eyes.