Some minor bug fixes and refactoring of some weird things.