Added some error checking and handling.

This change resulted in some chunks of code being un-indented, sorry
about it being hard to identify changes in the commit.  :(