Added some error checking to code