library(Seurat)
library(SCENIC)
library(SCopeLoomR)
library(dplyr)

args <- commandArgs(trailingOnly = TRUE)

# Input Seurat RDS file
in_rds <- args[1]
# Output
out_loom <- args[2]

in_obj <- readRDS(in_rds)
assay_name <- "RNA"
if (!assay_name %in% names(in_obj@assays)) {
  assay_name <- names(in_obj@assays)[1]
  print("'RNA' assay not found!")
  print(paste0("Using ", assay_name, " as assay."))
}

umap_vars <- grep("umap", names(in_obj@reductions), value = T)
umap_name <- grep("harmony", umap_vars, value = T)
if (length(umap_name == 0)) {
  umap_name <- umap_vars[1]
}
umap <- as.data.frame(in_obj@reductions[[umap_name]]@cell.embeddings)
colnames(umap) <- c("X", "Y")
cm <- in_obj@assays[[assay_name]]
cm <- as.matrix(cm$counts)
loom <- build_loom(file.name = out_loom, dgem = cm, default.embedding = umap, default.embedding.name = "umap")
loom <- add_cell_annotation(loom = loom, cellAnnotation = in_obj@meta.data)
close_loom(loom = loom)
