Backport fix for Bug#6571 from trunk. NOTE: May cause merge conflicts.