Fix a bunch of bugs and cleanup.