[pr19635] Revert most of r170537, and add new testcase.

Patch provided by Andrey Kuharev.

Sorry, r170537 was obviously wrong.