tweaked parameters and added some robustness to code