Ported v3.1 fixes for #2007 to v3.0.
Resolved merge conflicts.