Some serious refactoring.

And some stylistic fixes.