Reapply r186316 with a fix for one bug where the code could walk off the