rownames2col <- function(df, rn = "rowname") {
    stopifnot(is.data.frame(df))
    df[[rn]] <- rownames(df)
    rownames(df) <- NULL
    return(df)
}

col2rownames <- function(df, rn = "rowname") {
    stopifnot(is.data.frame(df))
    df <- as.data.frame(df)
    rownames(df) <- df[[rn]]
    df[[rn]] <- NULL
    return(df)
}

col.spec <- c(
    "#D53E4F", "#F46D43", "#FDAE61",
    "#FEE08B", "#FFFFBF", "#E6F598", "#ABDDA4",
    "#66C2A5", "#3288BD", "#5E4FA2"
)

col.pMedium <- c(
    "#729ECE", "#FF9E4A", "#67BF5C", "#ED665D", "#AD8BC9",
    "#A8786E", "#ED97CA", "#A2A2A2", "#CDCC5D", "#6DCCDA"
)

col.pDark <- c(
    "#1F77B4", "#FF7F0E", "#2CA02C", "#D62728", "#9467BD",
    "#8C564B", "#E377C2", "#7F7F7F", "#BCBD22", "#17BECF"
)

col.pLight <- c(
    "#AEC7E8", "#FFBB78", "#98DF8A", "#FF9896", "#C5B0D5",
    "#C49C94", "#F7B6D2", "#C7C7C7", "#DBDB8D", "#9EDAE5"
)

col.p10 <- col.pMedium
col.p20 <- c(col.pDark, col.pLight)
col.p30 <- c(col.pDark, col.pLight, col.pMedium)

selectColor <- function(n) {
    if (n <= 10) {
        return(col.p10[seq_len(n)])
    } else if (n <= 20) {
        return(col.p20[seq_len(n)])
    } else if (n <= 30) {
        return(col.p30[seq_len(n)])
    } else {
        return(rep_len(col.p30, n))
    }
}

col.lisa <- c("#eeeeee", "#FF0000", "#0000FF", "#a7adf9",
              "#f4ada8", "#464646", "#999999")
col.pval <- c("#3644E5", "#FFFFBF", "#FF5D53")

contour_brks <- getFromNamespace("contour_breaks", "ggplot2")
unique00 <- getFromNamespace("unique0", "ggplot2")
data_frame00 <- getFromNamespace("data_frame0", "ggplot2")

colsum <- function(x, group, reorder = TRUE,...){
  return(t(rowsum(t(x), group, reorder = reorder, ...)))
}

# Clean up vector of names. If "overall" is in names (after cleaning up) then 
# also removes "overall" from it if more than 1 names.
cleanName <- function(names) {
  names <- janitor::make_clean_names(names)
  names <- gsub("^density_|_contour$|_roi$","",names)
  if ("overall" %in% names && length(names)>1) names <- names[names!="overall"]
  names <- sort(names)
  return(names)
}