Cleaning up some code and improving error reporting.