Made some checks to make sure the script doesn't go out of bounds