Backport changes made by @ednapiranha