Much refactoring and improvements.