Moved some code from shell-script to python; much faster now.