Major refactoring and cleaning up