Ported from 1.6.4 to 1.7.2.