Much work cleaning up the code for bug #8377.