## Load library
library(dropbead)

## Set cell names
cell_IDs <- colnames(expression_seurat@data)

## Create a new single species object
test <- new("SingleSpeciesSample", 
           species1="human", ## Change to mouse if working with mouse data!
           cells=cell_IDs,
           genes=rownames(expression_seurat@data),
           dge=as.data.frame(as.matrix(expression_seurat@data)))


## Cell cycle phase with Dropbead
phases <- assignCellCyclePhases(test,gene.file="./cell_cycle_genes.xlsx") ## Point towards cell cycle gene list supplied with Dropbead

sorted_phases <- phases %>%
  arrange(rownames(phases))
  
sorted_phases <- phases %>%
  arrange(rownames(phases))

## For each cell, check which phase has highest score and assign this to the cell
## Code by akrun (https://stackoverflow.com/questions/36274867/getting-column-names-for-max-value-in-each-row)
j1 <- max.col(sorted_phases, "first")
value <- sorted_phases[cbind(1:nrow(sorted_phases), j1)]
cluster <- names(sorted_phases)[j1]
res <- data.frame(cluster)
rownames(res) <- cell_IDs

## Add the cell cycle phase to the Seurat object as Metadata
expression_seurat <- AddMetaData(expression_seurat,
                                             metadata=res)