Lots of refactoring and clean-ups