Simplified the script, and added error checks.