Lots of refactoring and improvements