#!/usr/bin/env Rscript

suppressPackageStartupMessages({
    library(data.table)
})

setDTthreads(8)

#====================================================
# INPUT
#====================================================

summary_file <-
"/BLUES/eric/ONT_WGBS/Heatmap/W3_TEsubfamily_RNAseq_summary_meanFPKM_no_rRNA_tRNA.tsv"

#====================================================
# OUTPUT
#====================================================

out_file <-
"/BLUES/eric/ONT_WGBS/Heatmap/RNAseq_matrix_FULL_log2FPKMp1_no_rRNA_tRNA.tsv"

#====================================================
# LOAD
#====================================================

dt <- fread(summary_file)

#====================================================
# WIDE MATRIX
#====================================================

mat <- dcast(
    dt,
    subfamily ~ sample,
    value.var = "mean_fpkm",
    fill = NA_real_
)

# keep column order
wanted <- c("subfamily","Primed","Naive","TSC")

for (x in wanted[-1]) {
    if (!x %in% names(mat))
        mat[, (x) := NA_real_]
}

setcolorder(mat, wanted)

#====================================================
# log2(FPKM + 1)
#====================================================

conds <- c("Primed","Naive","TSC")

for (cc in conds) {
    mat[, (cc) := log2(get(cc) + 1)]
}

#====================================================
# SAVE
#====================================================

fwrite(
    mat,
    out_file,
    sep = "\t",
    quote = FALSE
)

cat("Wrote:", out_file, "\n")
