Various bug fixes and error handling