Some code cleanups and error handling additions