Added a bit more error checking