

merge_dictionaries <- function(...) {

  dics <- list(...)

  # Falls eine einzige Liste übergeben wurde, entpacken
  if (length(dics) == 1 && is.list(dics[[1]]) && !is.data.frame(dics[[1]]))
    dics <- dics[[1]]

  # Dateipfade laden
  for (i in seq_along(dics)) {
    if (is.character(dics[[i]]) && length(dics[[i]]) == 1)
      dics[[i]] <- read_dictionary(dics[[i]])
  }

  # Alle zusammenfügen
  all_df <- do.call(rbind, dics)

  # cunei./reading: erste Vorkommen behalten (= aus dem 1. Wörterbuch)
  meta <- all_df[all_df$row_type %in% c("cunei.", "reading"), ]
  meta <- meta[!duplicated(meta[, c("sign_name", "row_type")]), ]

  # trans.: Einträge mit gleicher sign_name + type + meaning verschmelzen
  trans <- all_df[all_df$row_type == "trans.", ]
  trans <- aggregate(
    list(count = trans$count),
    by = list(sign_name = trans$sign_name, type = trans$type,
              meaning = trans$meaning),
    FUN = sum, na.rm = TRUE
  )
  trans <- data.frame(sign_name = trans$sign_name, row_type = "trans.",
                      count = trans$count, type = trans$type,
                      meaning = trans$meaning)

  # Zusammenführen und sortieren
  result <- rbind(meta, trans)
  ord <- order(result$sign_name, result$row_type, -result$count)
  result <- result[ord, ]
  rownames(result) <- seq_len(nrow(result))

  result
}
