try to do proper cleanup to avoid memory errors on close