Some refactoring to get rid of some code duplication

Still more needed