Backport of 0ed7d15563 from master
0ed7d15563
Thanks awsum for the suggestion and Pavel Ponomarev and Florian Hahn for the patch.