Re-implement 72c9c16d in a way that can be merged to master