Added some error checking so the code is more robust