Backporting bug fixes from 1.6.2 branch