A more radical refactoring, attempt to fix unreachable code.

Totally untested, needs review.