
args=commandArgs(TRUE)

# Packages to load #######
library(gtools)
library(foreach)
library(doParallel)
library(data.table)

indir <- args[1]#"brain-hprd/dyn-net-norm-diff-output"#args[1]#
onehop <- args[2]#"brain-hprd/dyn-net-norm-diff-feat/onehop"#args[2]#
one_onehop <- args[3]#"brain-hprd/dyn-net-norm-diff-feat/one_onehop"#args[3]#
twohop <- args[4]#"brain-hprd/dyn-net-norm-diff-feat/twohop"#args[4]#
two_twohop <- args[5]#"brain-hprd/dyn-net-norm-diff-feat/two_twohop"#args[5]#


# Min. amd max of edge weights among all network snapshots
adirs <- mixedsort(list.dirs(indir, full.names=TRUE, recursive=FALSE))

allwts <- c()
tt <- list()

for(k in 1:length(adirs)){

  tt[[k]] <- list.files(adirs[k], full.names=TRUE)

  for(j in 1:1){
  
    temp <- fread(tt[[k]][j], sep=' ')
    allwts <- union(allwts, temp[[1]])

  }

}

allwts <- data.frame(V1=sort(allwts))


# parralel for loop for efficieny #############################
cores=detectCores()
cl <- makeCluster(cores[1]) 
registerDoParallel(cl)


foreach(i=1:length(tt[[1]])) %dopar% {

  library(data.table)

  tempn <- strsplit(basename(tt[[1]][i]), '[_]')
  node_name <- tempn[[1]][length(tempn[[1]])]

  age <- length(tt)+1

  # gene1 <- vector(mode = "list", length = age)
  gene2 <- vector(mode = "list", length = age)
  # gene3 <- vector(mode = "list", length = age)
  # gene4 <- vector(mode = "list", length = age)

  # gene1[[1]] <- allwts
  gene2[[1]] <- allwts
  # gene3[[1]] <- allwts
  # gene4[[1]] <- allwts

  # for each age
  for(k in 1:length(tt)){

      temp <- fread(tt[[k]][i], sep=' ')
      temp1 <- merge(allwts, temp, by='V1', all.x=TRUE)

      j <- k+1
      # replace NA with 0
      temp1[is.na(temp1)] <- 0

      # gene1[[j]] <- temp1[[2]]
      gene2[[j]] <- temp1[[3]]
      # gene3[[j]] <- temp1[[4]]
      # gene4[[j]] <- temp1[[5]]

  }

  # save features
  # fwrite(t(data.frame(matrix(unlist(gene1), nrow=length(gene1), byrow=T))), paste0(onehop,'/',node_name,'.txt'),  col.names=FALSE, row.names=FALSE, quote=FALSE)
  fwrite(t(data.frame(matrix(unlist(gene2), nrow=length(gene2), byrow=T))), paste0(one_onehop,'/',node_name,'.txt'),  col.names=FALSE, row.names=FALSE, quote=FALSE, sep=' ')
  # fwrite(t(data.frame(matrix(unlist(gene3), nrow=length(gene3), byrow=T))), paste0(twohop,'/',node_name,'.txt'),  col.names=FALSE, row.names=FALSE, quote=FALSE)
  # fwrite(t(data.frame(matrix(unlist(gene4), nrow=length(gene4), byrow=T))), paste0(two_twohop,'/',node_name,'.txt'),  col.names=FALSE, row.names=FALSE, quote=FALSE)

}

stopCluster(cl)

