Lots of improvements and refactorings.