+/**
+ * \brief Checks if the FileData is referenced
+ *
+ * Checks the refcount and whether the FileData is locked.
+ */
+static gboolean file_data_check_has_ref(FileData *fd)
+{
+ return fd->ref > 0 || fd->locked;
+}
+
+/**
+ * \brief Consider freeing a FileData.
+ *
+ * This function will free a FileData and its children provided that neither its parent nor it has
+ * a positive refcount, and provided that neither is locked.
+ */
+static void file_data_consider_free(FileData *fd)
+{
+ GList *work;
+ FileData *parent = fd->parent ? fd->parent : fd;
+
+ g_assert(fd->magick == FD_MAGICK);
+ if (file_data_check_has_ref(fd)) return;
+ if (file_data_check_has_ref(parent)) return;
+
+ work = parent->sidecar_files;
+ while (work)
+ {
+ FileData *sfd = work->data;
+ if (file_data_check_has_ref(sfd)) return;
+ work = work->next;
+ }
+
+ /* Neither the parent nor the siblings are referenced, so we can free everything */
+ DEBUG_2("file_data_consider_free: deleting '%s', parent '%s'",
+ fd->path, fd->parent ? parent->path : "-");
+
+ work = parent->sidecar_files;
+ while (work)
+ {
+ FileData *sfd = work->data;
+ file_data_free(sfd);
+ work = work->next;
+ }
+
+ g_list_free(parent->sidecar_files);
+ parent->sidecar_files = NULL;
+
+ file_data_free(parent);
+}
+