Cleanup, removal of most unused code, and various minor optimizations.