+ return messages;
+}
+
+/* Glib objects force use to use a talloc destructor as well, (but not
+ * nearly as ugly as the for messages due to C++ objects). At
+ * this point, I'd really like to have some talloc-friendly
+ * equivalents for the few pieces of glib that I'm using. */
+static int
+_notmuch_threads_destructor (notmuch_threads_t *threads)
+{
+ g_ptr_array_free (threads->threads, TRUE);
+
+ return 0;
+}
+
+notmuch_threads_t *
+notmuch_query_search_threads (notmuch_query_t *query)
+{
+ notmuch_threads_t *threads;
+ notmuch_thread_t *thread;
+ const char *thread_id;
+ notmuch_messages_t *messages;
+ notmuch_message_t *message;
+ GHashTable *seen;
+
+ threads = talloc (query, notmuch_threads_t);
+ if (threads == NULL)
+ return NULL;
+
+ threads->notmuch = query->notmuch;
+ threads->threads = g_ptr_array_new ();
+ threads->index = 0;
+
+ talloc_set_destructor (threads, _notmuch_threads_destructor);
+
+ seen = g_hash_table_new_full (g_str_hash, g_str_equal,
+ free, NULL);
+
+ for (messages = notmuch_query_search_messages (query);
+ notmuch_messages_has_more (messages);
+ notmuch_messages_advance (messages))
+ {
+ message = notmuch_messages_get (messages);
+
+ thread_id = notmuch_message_get_thread_id (message);
+
+ if (! g_hash_table_lookup_extended (seen,
+ thread_id, NULL,
+ (void **) &thread))
+ {
+ thread = _notmuch_thread_create (query, query->notmuch,
+ thread_id);
+
+ g_hash_table_insert (seen, xstrdup (thread_id), thread);
+
+ g_ptr_array_add (threads->threads, thread);
+ }
+
+ _notmuch_thread_add_message (thread, message);
+
+ notmuch_message_destroy (message);
+ }
+
+ g_hash_table_unref (seen);
+
+ return threads;