This little script is very much the product of me making my first steps in programming a while ago. I didn't know what I was doing back then and it shows in the code. It would most likely look very different if I did the same thing today. That being said, it seems to work(*) and even landed me a citation in someone else's master thesis, so go nuts.
*no guarantees on that. You have been warned.