Eworm, I apologise if you have already written the solution somewhere on your website, I rarely open external links on public forums. I didn't mean to disrespect anyone. :)
I have a collection of script, one of them does what plisken wants - and a lot more. But it is complex and depends on other scripts. If you want something that just works - use my scripts.
Looks like plisken wants a simple script he can maintain himself. That's fine and I am glad you teach him.
(Still there's not a lot of knowledge required to use
my scripts. Everything is documented and you just have to follow the instructions in README. So everybody is invited to try it.)