Patch is based on earlier patch from Matthew Wilcox.