Lots of refactoring and code cleanup