{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76bdd6af",
   "metadata": {},
   "outputs": [],
   "source": [
    "#! /usr/bin/Rscript"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b204f2d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "library(Spectra)\n",
    "library(stringr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b2aeac62",
   "metadata": {},
   "outputs": [],
   "source": [
    "args <- commandArgs(trailingOnly=TRUE)\n",
    "#print(args)\n",
    "\n",
    "input_dir <- as.character(args[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f781bb92",
   "metadata": {},
   "outputs": [],
   "source": [
    "## Specifying a function for creating result directories for each input mzml\n",
    "# input for the function:\n",
    "# input directory\n",
    "ms2_rfilename<- function(input_dir){\n",
    "    \n",
    "    input_dir <- dirname(input_dir)\n",
    "    \n",
    "    if (dir.exists(input_dir)){\n",
    "        #list_ms2_files <- intersect(list.files(input_dir, pattern = \"_PRM_\"), list.files(input_dir, pattern = \".mzML\"))\n",
    "        list_ms2_files <- list.files(input_dir, pattern = \".mzML\")\n",
    "        mzml_file <- paste(input_dir, \"/\", list_ms2_files, sep = \"\")\n",
    "\n",
    "        #store the result file names to return to this function as output\n",
    "        mzml_files <- c()\n",
    "        ResultFileNames <- c()\n",
    "        File_id <- c()\n",
    "        nx <- 0\n",
    "        # x is mzML files\n",
    "        for (i in 1:length(mzml_file)){\n",
    "            nx <- nx+1\n",
    "            # remove .mzML to extract just the names\n",
    "            mzml_filex <- str_replace(mzml_file[i], input_dir, \".\")\n",
    "            name_mzmls <- str_remove(as.character(mzml_filex), \".mzML\")\n",
    "            name_mzmlsd <- str_remove(mzml_file[i], \".mzML\")\n",
    "            if (!file.exists(name_mzmlsd)){\n",
    "                dir.create(name_mzmlsd) ##create folder\n",
    "            }\n",
    "            ResultFileNames<- c(ResultFileNames, name_mzmls)\n",
    "            mzml_files <- c(mzml_files, mzml_filex)\n",
    "            File_id <- c(File_id, paste(\"file_\", nx, sep = \"\"))\n",
    "        }\n",
    "        input_table <- cbind(mzml_files, ResultFileNames, File_id)\n",
    "\n",
    "        write.csv(input_table, paste(input_dir, \"/input_table.csv\", sep = \"\"))\n",
    "        return(data.frame(input_table))\n",
    "    }\n",
    "    else{\n",
    "        stop(\"Your input_dir is incorrect. Please provide the directory where all your input files are stored. An example would be: '/Users/my_name/input_dir/'. don't forget the '/' at the end : ) Good Luck\")\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c96ed001",
   "metadata": {},
   "outputs": [],
   "source": [
    "spec_Processing <- function(input_dir, x, result_dir){\n",
    "    \n",
    "    input_dir <- dirname(input_dir)\n",
    "    \n",
    "    x <- paste(input_dir, str_remove(x, \".\"), sep = \"\")\n",
    "    \n",
    "    result_dir <- paste(input_dir, str_remove(result_dir, \".\"), sep = \"\")\n",
    "    \n",
    "    if (file.exists(x) && substring(x, nchar(x)) == \"L\"){\n",
    "        if (dir.exists(result_dir)){\n",
    "            # read the spectra\n",
    "            sps_all <- Spectra(x, backend = MsBackendMzR())\n",
    "            #' Change backend to a MsBackendDataFrame: load data into memory\n",
    "            #sps_all <- setBackend(sps_all, MsBackendDataFrame())\n",
    "            #' Filter Empty Spectra\n",
    "            sps_all <- filterEmptySpectra(sps_all)\n",
    "            #' Extract Precursor m/z(s) in each file\n",
    "            pre_mz <- unique(precursorMz(sps_all))\n",
    "            #' Remove any NAs\n",
    "            pre_mz <- na.omit(pre_mz)\n",
    "            export(sps_all, backend = MsBackendMzR(), file = paste(result_dir, \"/processedSpectra.mzML\", sep = \"\"))\n",
    "            write.table(pre_mz, file = paste(result_dir, \"/premz_list.txt\", sep = \"\"), sep = \"/t\", row.names = FALSE, col.names = FALSE)\n",
    "            spsall_pmz <- list(sps_all, pre_mz)\n",
    "            return(spsall_pmz)\n",
    "        }\n",
    "        else{\n",
    "            stop(\"Seems like it is not the result directory of the input .mzML file which is provided as x. Please use the function ms2_rfilename to generate a result directory or create one yourself with the same name as the .mzML input file.\")\n",
    "        }\n",
    "    }\n",
    "    else{\n",
    "        stop(\"Are you sure x is an mzML input file?\")\n",
    "    }\n",
    "    \n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "046f6c90",
   "metadata": {},
   "outputs": [],
   "source": [
    "input_table <- data.frame(ms2_rfilename(input_dir))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d388b15f",
   "metadata": {},
   "outputs": [],
   "source": [
    "spec_pr <- spec_Processing(input_dir,\n",
    "                           input_table[1, \"mzml_files\"], \n",
    "                           input_table[1, \"ResultFileNames\"])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "R",
   "language": "R",
   "name": "ir"
  },
  "language_info": {
   "codemirror_mode": "r",
   "file_extension": ".r",
   "mimetype": "text/x-r-source",
   "name": "R",
   "pygments_lexer": "r",
   "version": "4.2.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
