Added several error checks to the script to try and prevent crashes