Cherrypicked from Michał Zubkowiczs pull request