+static void init_trace_collection(struct trace_collection *tc)
+{
+ tc->array = g_ptr_array_sized_new(DEFAULT_FILE_ARRAY_SIZE);
+}
+
+/*
+ * finalize_trace_collection() closes the opened traces for read
+ * and free the memory allocated for trace collection
+ */
+static void finalize_trace_collection(struct trace_collection *tc)
+{
+ int i;
+
+ for (i = 0; i < tc->array->len; i++) {
+ struct trace_descriptor *temp =
+ g_ptr_array_index(tc->array, i);
+ fmt_read->close_trace(temp);
+ }
+ g_ptr_array_free(tc->array, TRUE);
+}
+
+static void trace_collection_add(struct trace_collection *tc,
+ struct trace_descriptor *td)
+{
+ g_ptr_array_add(tc->array, td);
+}
+
+int convert_trace(struct trace_descriptor *td_write,
+ struct bt_context *ctx)
+{
+ struct babeltrace_iter *iter;
+ struct ctf_stream *stream;
+ struct ctf_stream_event *event;
+ struct ctf_text_stream_pos *sout;
+ struct trace_collection_pos begin_pos;
+ int ret;
+
+ sout = container_of(td_write, struct ctf_text_stream_pos,
+ trace_descriptor);
+
+ begin_pos.type = BT_SEEK_BEGIN;
+ iter = babeltrace_iter_create(ctx, &begin_pos, NULL);
+ if (!iter) {
+ ret = -1;
+ goto error_iter;
+ }
+ while (babeltrace_iter_read_event(iter, &stream, &event) == 0) {
+ ret = sout->parent.event_cb(&sout->parent, stream);
+ if (ret) {
+ fprintf(stderr, "[error] Writing event failed.\n");
+ goto end;
+ }
+ ret = babeltrace_iter_next(iter);
+ if (ret < 0)
+ goto end;
+ }
+ ret = 0;
+
+end:
+ babeltrace_iter_destroy(iter);
+error_iter:
+ return ret;
+}
+
+
+/*
+ * traverse_dir() is the callback functiion for File Tree Walk (nftw).
+ * it receives the path of the current entry (file, dir, link..etc) with
+ * a flag to indicate the type of the entry.
+ * if the entry being visited is a directory and contains a metadata file,
+ * then open it for reading and save a trace_descriptor to that directory
+ * in the read trace collection.
+ */
+static int traverse_dir(const char *fpath, const struct stat *sb,
+ int tflag, struct FTW *ftwbuf)
+{
+ int dirfd;
+ int fd;
+ struct trace_descriptor *td_read;
+
+ if (tflag != FTW_D)
+ return 0;
+ dirfd = open(fpath, 0);
+ if (dirfd < 0) {
+ fprintf(stderr, "[error] unable to open trace "
+ "directory file descriptor.\n");
+ return -1;
+ }
+ fd = openat(dirfd, "metadata", O_RDONLY);
+ if (fd < 0) {
+ close(dirfd);
+ } else {
+ close(fd);
+ close(dirfd);
+ td_read = fmt_read->open_trace(opt_input_path,
+ fpath, O_RDONLY, ctf_move_pos_slow,
+ NULL);
+ if (!td_read) {
+ fprintf(stderr, "Error opening trace \"%s\" "
+ "for reading.\n\n", fpath);
+ return -1; /* error */
+ }
+ trace_collection_add(&trace_collection_read, td_read);
+ }
+ return 0; /* success */
+}
+