

convert_to_dictionary <- function(df, mapping=NULL){

  if(is.null(mapping)){
    path  <- system.file("extdata", "etcsl_mapping.txt", package = "sumer")
    mapping <- read.csv2(path, sep=";", na.strings="")
  }

  signs <- list(cuneiform=as.cuneiform(df$sign_name, mapping=mapping), sign_name=df$sign_name)

  df <- aggregate(
    list(count = rep(1, nrow(df))),
    by = list(sign_name = df$sign_name, type = df$type, meaning = df$meaning),
    FUN = sum
  )

  df <- data.frame(sign_name=df$sign_name, row_type="trans.", count=df$count, type=df$type, meaning=df$meaning)

  df_signs <- as.data.frame(signs)
  df_signs <- df_signs[!duplicated(df_signs$cuneiform),]
  df_signs$reading <- ""
  for(i in 1:nrow(df_signs)){
    sign_names <- split_sumerian(df_signs$sign_name[i])$signs
    n <- length(sign_names)
    this_reading <- rep("?", n)
    for(j in 1:n){
      k <- which(mapping$name == sign_names[j])
      if(length(k)>0){
        k <- k[1]
        syllables <- mapping$syllables[k[1]]
        if(n>1){syllables <- str_replace(syllables, "^((?:[^,]*,){2}[^,]*),.*$", "\\1, \u2026")}
        if(str_count(syllables, fixed(","))>0){
          syllables <- paste0("{",syllables,"}")
        }
        this_reading[j] <- syllables
      }
      df_signs[i,"reading"] <- paste0(this_reading, collapse="-")
    }
  }

  df_names    <- data.frame(sign_name=df_signs$sign_name, row_type="cunei.", count=NA, type="", meaning=df_signs$cuneiform)
  df_readings <- data.frame(sign_name=df_signs$sign_name, row_type="reading", count=NA, type="", meaning=df_signs$reading)

  df <- rbind(df, df_names, df_readings)

  ord <- order(df$sign_name, df$row_type,  -df$count)
  df <- df[ord,]
  rownames(df) <- 1:nrow(df)

  return(df)
}
