Fix a set of bugs

Sorry about the code dump, let me know if you want this broken up.