Ported refactorings and changes from 7.x-1.x.