Numerous cleanups, refactorings, and fixes.