I've had a version of this for years. Your post made me take another look at the code. I had to clean it up a little, but here it is:
https://gist.github.com/anonymous/32b1e619bc9e7fbe0eaa
(The cleanup might have introduces some subtle bugs, but a quick test showed no issues. Let me know if you find some!)