Fixed errors and improved robustness of program script. Faster might be possible but at least this works!