Reapply r108378, with bugfixes, testcase, and improved comment formatting.