backporting changes from 85a3bb to 5e45c