fixed error handling and cleanup