I haven't coded this recently but this is a wheel that's been invented so many times that I assume there are now turn-key packages available to accomplish it. Maybe our local Perl/Python aficionados can confirm...