Add a lock and clean up handling of some error conditions,