Various refactoring and improvements