I don't have time to search for it right now, nor do I recall the name of it, but I do know there's a plugin that does this already. I believe JGHG wrote it. That's his name abbreviated. Don't recall either how he spelled it.
Maybe I gave enough clues that someone else can point you to it, or perhaps you can find it yourself.