Some logic refactoring and improvements