Added some more error checking and handling