This is ready for commit.

But... don't you think code this could be more readable moving some code to a new helper function? The existing code is already a bit convoluted, and this fix adds lines and indent levels that make it worth some refactoring.