I have been doing something similar for many years. Someone ported this to Bash... I'll try to get that port up on github.
EDIT: https://raw.githubusercontent.com/jakobi/script-archive/mast...