This is a packaged version of code by @jpkotta, taken from a comment on http://tromey.com/blog/?p=831.