fix memory leak, clean up some error handling