
library(stringr)

#######################################################
############## Get Masschroq results ##################
#######################################################
{% if  mcqml == NULL%}
  masschroq_paths = list.files("{{ mcqml }}", pattern="*.RData", full.names="TRUE")
  for (masschroq in masschroq_paths){
    load(masschroq)
  }

  #### Get full list of peptide dataframes
  masschroq_env = ls(envir = .GlobalEnv)
  peptides.df.list = data.frame(str_match(masschroq_env, pattern = "(.*\\.peptides)\\.[0-9]{1,2}"))
  peptides.df.list = na.omit(peptides.df.list)

  #### Get unique final peptide dataframe names
  final.peptide.dfs = str_match(masschroq_env, pattern = "(.*\\.peptides)\\.[0-9]{1,2}")[,2]
  final.peptide.dfs = unique(final.peptide.dfs[!is.na(final.peptide.dfs)])

  #### Merge peptide dataframes with same prefix and assign to the final dataframe
  for (df in final.peptide.dfs) {
    merged = data.frame()
    for(i in 1:dim(peptides.df.list)[1]){
      if (peptides.df.list[i,2] == df) {
        merged = rbind(merged, eval(parse(text = as.character(peptides.df.list[i,1]))))
      }
    }
    rownames(merged) = c(1:nrow(merged))
    assign(df, merged)
  }

  #### Remove unwanted objects
  rm(list=as.character(peptides.df.list[,1]))
  remove(df, final.peptide.dfs, i, peptides.df.list, masschroq, masschroq_paths, masschroq_env, merged)
{% endif %}
#######################################################
########### Get X!tandemPipeline results ##############
#######################################################
rdata_paths = list.files("{{ tmp_path }}", pattern="*.RData", full.names="TRUE")

for (path in rdata_paths) {
  load(path)
}  

remove(rdata_paths, path)

#######################################################
############ Write the final RData file ###############
#######################################################
save.image(file = "{{ final_path }}")
