Add missing changes for 98ccba0c1de34e1aa1708e4811189632c219d701
A lot of refactoring for #528