Cleanup part 1.

Cleaned up some code, plus minor bug fixes.