Based on an original patch by Neitrino Photonov <neitrinoph@gmail.com> PR#3439 (cherry picked from commit 66816c53)