Various refactoring and improvements.