Lots of refactorings and a few minor improvements.