Some refactoring and improvements