lots of refactoring and improvements