Misc fixes

This fixes a bunch of different bugs, cleans up cyclomatic complexity, adds some test coverage, etc.