Re #8635. Added tests and fixed the bugs they exposed.

As per Russell's requests.