{% if mcqr_step == 0 %} # SdsAnalysisStep::analyzing_sc see grantlee_context
  message("MCQRBegin: analyzing_sc")
  cat("<h1>MCQR SDS Analysis</h1>")

  setwd("{{ mcqr_working_directory }}")
  cat(paste("working directory: ", getwd()))
  capture.output(library("MCQR", verbose=FALSE), file=stderr())
  message(paste("MCQRInfo: MCQR version :", packageVersion("MCQR")))
  library("xtable")
  library("svglite")
  library("readODS")

  #**************************************************************************************************************************************************
  #**************************************************************************************************************************************************
  #******************************************************   2. Analyzing spectral counting (SC) data
  #**************************************************************************************************************************************************
  #**************************************************************************************************************************************************
  cat("<h2>Analyzing spectral counting (SC) data</h2>")
  #********************************************************
  #--------------------------------------------------------
  # 			2.1. Data and metadata loading
  #--------------------------------------------------------
  #********************************************************
  message("MCQRInfo: Loading data to MCQR")

  load("{{ rdata_path }}")
  write.table(sc.data, sep = '\t', row.names = FALSE,  "spectral_counting.tsv")
  write_ods(metadata.data, "metadata.ods")
  # Loading spectral counting data
  capture.output(SC <- mcq.read.spectral.counting("spectral_counting.tsv", specificPeptides={{ specific_peptides }}), file=stderr())
  # Importing the filled in metadata file
  capture.output(META <- mcq.read.metadata("metadata.ods"), file=stderr()) 
  # Attaching metadata to spectral counting data
  capture.output(SC <- mcq.merge.metadata(SC, META), file=stderr())
  # Overview of the content of the data
  summary (SC)

  message("MCQRInfo: Data loaded to MCQR")

  #********************************************************
  #--------------------------------------------------------
  # 			2.2. Checking data quality
  #--------------------------------------------------------
  #********************************************************
  
  #****************************************************************************************************************
  # 2.2.1. Checking the total number of spectra for each sample 	
  #****************************************************************************************************************
  cat("<h3>Total number of spectra for each sample</h3>")

  message("MCQRInfo: Computing the number of spectra for each sample")

  # Display of the graph on the screen
  svglite("{{ tmp_path }}/sc_count.svg", width=14, height=12)
  capture.output(mcq.plot.counts(SC), file=stderr())
  capture.output(dev.off(), file='/dev/null')
  cat("<p><img src=\"{{ tmp_path }}/sc_count.svg\" /></p>")


  message("MCQRInfo: Computing the number of spectra for each sample ended")


{% if mcqr_load_data_mode == 1 or mcqr_load_data_mode == 2 %}
  #****************************************************************************************************************
  # 2.2.2. Reconstituting samples from fractions
  #****************************************************************************************************************
  cat("<h3>Reconstituting samples from fractions</h3>")
  # Computing counts by track as the sum of the spectral counts of all fractions for each track
  capture.output(SC <- mcq.compute.quantity.by.track(SC), file=stderr())
  summary(SC)
  cat("<h3>Metadata</h3>")
  metadata.by.track <- mcq.get.metadata(SC)
  print(xtable(metadata.by.track), type="html")
{% endif %}

  #****************************************************************************************************************
  # 2.2.3. Checking the experiment	
  #****************************************************************************************************************
  cat("<h3>Checking the experiment by a principal component analysis (PCA).</h3>")
  # Checking the experiment by a principal component analysis (PCA). Is there any outlier ?
  # PCA using all the injections as individuals
  capture.output(SC_PCA <- mcq.compute.pca(SC, flist=c("{{ factors_list }}")), file=stderr())
  # Display of the PCA on the screen. Possibility to modify the 'factorToColor', 'labels' and 'labeltype' arguments to change the colors and the labels of the 
  # Exporting the graph in a .pdf file in '/path/to/my_working_directory'
  svglite("{{ tmp_path }}/pca_%01d.svg", width=14, height=12)
  capture.output(mcq.plot.pca(SC_PCA, factorToColor=c("{{ factors_color }}"), labels = c("{{ factors_label }}"), tagType="both", labelSize=4), file=stderr())


  capture.output(dev.off(), file=stderr())
  cat("<p><img src=\"{{ tmp_path }}/pca_1.svg\" /></p>")
  cat("<p><img src=\"{{ tmp_path }}/pca_2.svg\" /></p>")
  cat("<p><img src=\"{{ tmp_path }}/pca_3.svg\" /></p>")
  # message("MCQRInfo: PCA done")
  message("MCQREnd: analyzing_sc")
  
{% elif mcqr_step == 1 %} #SdsAnalysisStep::filtering_sc
  message("MCQRBegin: filtering")
  #****************************************************************************************************************
  # 2.2.4. Filtering dubious data	
  #****************************************************************************************************************
  {% if msrun_to_remove != "" %}
    cat("<h2>Data after filtering</h2>")
    cat("The injection(s) \"{{ msrun_to_remove }}\" are removed from the analysis")
    #  If necessary, removal of dubious injections

    # E.g. in the factor 'msrun', removal of the level 'msruna1_P2' 
    # Take a look at the help (help(mcq.drop)) to see the factors you can remove 
    # You can also select a few injections for the analyze with the mcq.select function. It's the reverse function of mcq.drop.
    capture.output(SC <- mcq.drop(SC, factor="msrun", levels=c("{{ msrun_to_remove }}")), file=stderr())
    
      
    #  If necessary, removal of dubious samples
    # Display of a summary of the 'protPep' object after removal of dubious injections
    summary(SC)
  {% endif %}
  
  #****************************************************************************************************************
  # 2.3. Filtering proteins
  #****************************************************************************************************************

  #  Removing proteins showing low numbers of spectra (< 5) in all the injections (the protein abundances are not reliable when the number of spectra is less than 5) 
  #  For an example, if cutoff = 5, all the proteins quantified with only 0, 1, 2, 3 or 4 spectra in each of the injections will be removed.
  capture.output(SC <- mcq.drop.low.counts(SC, cutoff={{ prot_cutoff }}), file=stderr())

  #  Removing proteins showing little variation in their number of spectra. The selection criteria is the ratio between the minimal and the maximal mean abundance values computed for a factor or a combination of factors of interest.
  capture.output(SC <-  mcq.drop.low.fold.changes(SC, cutoff={{ foldchange_cutoff }}, flist=c("{{ factors_list }}")), file=stderr())
  message("MCQREnd: filtering")
  
{% elif mcqr_step == 2 %} #SdsAnalysisStep::heatmap_abundance
  message("MCQRBegin: heatmap_abundance")
  #****************************************************************************************************************
  # 2.4. Overview of protein abundances
  #****************************************************************************************************************

  # Plotting a heatmap
  cat("<h2>Heatmap of the protein abundance</h2>")
  # Display of the graph on the screen. Possibility to change the color, the method of aggregation ('method' argument) and the method to compute the distances ('distfun' argument). See help for details
  png("{{ tmp_path }}/prot_heatmap.png", width=500, height=500)
  mcq.plot.heatmap(SC, flist=c("{{ factors_list }}"), factorToColor=c("{{ factors_color }}"), distfun="{{ distance_fun }}", method="{{ agg_method }}")
  capture.output(dev.off(), file=stderr())
  cat("<p><img src=\"{{ tmp_path }}/prot_heatmap.png\" /></p>")

  message("MCQREnd: heatmap_abundance")
  
{% elif mcqr_step == 3 %} #SdsAnalysisStep::protein_clustering
  message("MCQRBegin: protein_clustering")
  # Clustering the proteins
  cat("<h2>Protein clustering</h2>")
  # Cluster for the factor(s) of interest
  capture.output(SC_cluster <- mcq.compute.cluster(SC, flist=c("{{ factor_list }}"), nbclust={{ nb_cluster }}), file=stderr())

  # Display of the graph on the screen
  svglite("{{ tmp_path }}/prot_cluster.svg", width=14, height=12)
  mcq.plot.cluster(SC_cluster)
  capture.output(dev.off(), file=stderr())
  cat("<p><img src=\"{{ tmp_path }}/prot_cluster.svg\" /></p>")
  message("MCQREnd: protein_clustering")
  
{% elif mcqr_step == 4 %} #SdsAnalysisStep::protein_anova
  message("MCQRBegin: protein_anova")
  #****************************************************************************************************************
  # 2.5. Analyzing protein abundance variations
  #****************************************************************************************************************

  # Differential analysis 
  cat("<h2>Differential analysis</h2>")
  cat("<h3>ANOVA</h3>")
  # ANOVA for the factors of interest
  # Run anova without interaction term, if you want to perform tukey test with counting data
  capture.output(SC_ANOVA <- mcq.compute.anova(SC, flist=c("{{factor_list}}"),inter={{ interaction }}), file=stderr())

  # Display the distribution of the p-values for a factor of interest on the screen
  svglite("{{ tmp_path }}/anova.svg", width=14, height=12)
  mcq.plot.pvalues(SC_ANOVA)
  capture.output(dev.off(), file=stderr())
  cat("<p><img src=\"{{ tmp_path }}/anova.svg\" /></p>")
  message("MCQREnd: protein_anova")
  
  {% elif mcqr_step == 5 %} #SdsAnalysisStep::protein_abundance
  message("MCQRBegin: protein_abundance")
  cat("<h3>Tukey test</h3>")
  {% for factor in factors_list %}
    cat("<h4>Analyse on {{ factor }} factor</h4>")
    # Retrieving the list of proteins showing significant abundance variations for a given factor
    capture.output(SC_PROTEINS_selected_{{factor}} <- mcq.select.pvalues(SC_ANOVA, padjust={{ padjust }}, alpha={{ alpha }}, flist="{{ factor }}"), file=stderr())

    # Retrieving spectral counts for the selected proteins  
    capture.output(SC_selected_{{ factor }} <- mcq.select.from.protlist(SC, SC_PROTEINS_selected_{{ factor }}), file=stderr())
      
    # Tukey test
    # WARNING : Verify your packageVersion of agricolae (with the R function packageVersion("agricolae")), it must be the 1.2.9 version 
    #(the URL provide in the PAPPSO site it's an unstable version, waiting for the stable one)
    capture.output(SC_selected_tukey <- mcq.compute.tukey(SC_ANOVA, flist="{{ factor }}", protlist=SC_PROTEINS_selected_{{ factor }}), file=stderr())

    # Display of the graph on the screen
    svglite("{{ tmp_path }}/tukey_{{ factor }}_%01d.svg", width=14, height=12)
    capture.output(mcq.plot.tukey(SC_selected_tukey, qprot=SC), file=stderr())
    capture.output(dev.off(), file=stderr())
    
    nb_proteins = dim(SC_selected_{{ factor }}@proteins)[1]
    nb_pages = nb_proteins%/%4
    if(nb_proteins%%4 != 0) {
      nb_pages = nb_pages + 1
    }
    for(i in 1:nb_pages){
      cat(paste0("<p><img src=\"{{ tmp_path }}/tukey_{{ factor }}_", i, ".svg\" /></p>"))
    }
  {%endfor%}
  
  
  capture.output(union_list <- union({% for factor in factors_list%}
                        SC_PROTEINS_selected_{{factor}}
                        {%if factor != factors_list|last %}, {%endif%}
                      {% endfor %}), file=stderr())
                      
  capture.output(SC_selected <- mcq.select.from.protlist(SC, protlist = union_list), file=stderr())
  
  cat("<h3>Protein abundance</h3>") 
  nb_proteins <- length(SC_selected@proteins$protein)
  svglite("{{ tmp_path }}/prot_abundance%01d.svg", width=14, height=12)
  capture.output(mcq.plot.protein.abundance(SC_selected, factorToColor=c("{{ factor_color }}"), flist=c("{{ factors_list_join }}")), file=stderr())
  capture.output(dev.off(), file=stderr())
  
  nb_pages = nb_proteins%/%4
  if(nb_proteins%%4 != 0) {
    nb_pages = nb_pages + 1
  }
  for(i in 1:nb_pages){
    cat(paste0("<p><img src=\"{{ tmp_path }}/prot_abundance", i, ".svg\" /></p>"))
  }
  message("MCQREnd: protein_abundance")
  
{% elif mcqr_step == 6 %} #SdsAnalysisStep::protein_fc_abundance
  message("MCQRBegin: protein_fc_abundance")
  #Analyzing protein abundance ratios
  cat("<h3>Protein abundance ratios</h3>")
  # Computing ratios between two levels of a factor of interest
  capture.output(SC_RATIO <- mcq.compute.fold.change(SC_selected, flist="{{ fc_factor }}", numerator="{{ num }}", denominator="{{ denom }}"), file=stderr())

  svglite("{{ tmp_path }}/abundance_ratio.svg", width=14, height=12)
  capture.output(mcq.plot.fold.change(SC_RATIO), file=stderr())
  capture.output(dev.off(), file=stderr())
  cat("<p><img src=\"{{ tmp_path }}/abundance_ratio.svg\" /></p>")

  message("MCQREnd: protein_fc_abundance")
  
{% elif mcqr_step == 7 %} #SdsAnalysisStep::last
  message("MCQRBegin: export_rdata")
  
  save.image(file="{{ rdata_file }}")
  
  message("MCQREnd: export_rdata")
{% endif %}
