propagated some refactoring from master