Major refactoring and clean up