Taken from issue #807 reported by @focalintent.
