Added better error handling and logging. Fixed a couple of bugs in previous commits.