Lots of cleanup and refactoring