Contributed by Kihwal Lee and Lukas Majercak. (cherry picked from commit 9e96ac666d783376a8cdea9c3cc84098c5bdcb56)