Contributed by Thomas Marquardt. (cherry picked from commit cb4679261097e729b433a523e3a65779fdc83841)