Added (slightly modified) patch from #2806