{% if step == "libraries" %}


  capture.output(library("MCQR", verbose=FALSE), file=stderr())
  message(paste("MCQRInfo: MCQR version :", packageVersion("MCQR")))
  library("xtable")
  library("svglite")
  library("readODS")

pimg_srcsvg <- function(path,prefix) {
  for(file_svg in list.files(path = path, pattern=paste(prefix,".*\\.svg",sep=""))){
    cat(paste("<p><img src=\"",path, file_svg, "\" /></p>\n",sep=""));
  }
}

pimg_srcpng <- function(path,prefix) {
  for(file_svg in list.files(path = path, pattern=paste(prefix,".*\\.png",sep=""))){
    cat(paste("<p><img src=\"",path, file_svg, "\" /></p>\n",sep=""));
  }
}

{% elif step == "load" %}

  cat("<h1>MCQR Spectral Count Analysis</h1>")
  cat("<p>working directory: {{ tmp_path }}</p>")

  cat("<h2>Load spectral count data</h2>")
  
  SC <- mcq.read.spectral.counting("{{ tmp_path }}spectral_count.tsv", specificPeptides={{ specific_peptides }})

  cat("<p>Overview of the content of the 'SC' object</p>")
  summary (SC)
  save(SC, file="{{ tmp_path }}sc_nometadata.rdata")
  

{% elif step == "merge_metadata" %}
  load(file="{{ tmp_path }}sc_nometadata.rdata")
  
  cat("<h1>Reading metadata file</h1>")
  cat("<p>Importing the filled in metadata file</p>")
  capture.output(META <- mcq.read.metadata("{{ tmp_path }}metadata.ods"), file=stderr())
  
  cat("<p>Attaching metadata to spectral count data</p>")
  cat("<h1>Merging metadata</h1>")
  SC <- mcq.add.metadata(SC, metadata=META)

  cat("<p>Overview of the content of the 'XICRAW' object</p>")
  summary (SC)
  
  
  message("MCQRInfo: Data loaded to MCQR")

  
  cat("<h1>Checking data quality</h1>")
  cat("<h2>Checking the total number of spectra for each sample</h2>")

  svglite("{{ tmp_path }}sc_count.svg", width=14, height=12);
  capture.output(mcq.plot.counts(SC), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="sc_count");

  
  save(SC, file="{{ tmp_path }}sc.rdata")
  unlink("{{ tmp_path }}a3a1_backup_sc.rdata")
  unlink("{{ tmp_path }}a4a2_backup_xic.rdata")
{% elif step == "a2a2_mcqr_pca" %}
  load(file="{{ tmp_path }}sc.rdata")

  
  cat("<h2>Checking the experiment by a principal component analysis (PCA).</h2>")
  cat("<p>Checking the experiment by a principal component analysis (PCA). Is there any outlier ? PCA using all the injections as individuals</p>")
  
  capture.output(SC_PCA <- mcq.compute.pca(SC), file=stderr());
  cat("<p>Display of the PCA on the screen. Possibility to modify the 'factorToColor' and 'labels' arguments to change the colors and the labels of the individuals represented on the PCA.</p>")
  svglite("{{ tmp_path }}sc_pca_%d.svg", width=14, height=12);
  capture.output(mcq.plot.pca(SC_PCA, factorToColor=c({{ factors_color }}), labels=c({{ factors_label }}), tagType="label", labelSize=4), file=stderr())
  capture.output(dev.off(), file=stderr());
  
  pimg_srcsvg(path="{{ tmp_path }}",prefix="sc_pca_");
  
{% elif step == "a3a1_mcqr_remove_msrun" %}
  if(file.exists("{{ tmp_path }}a3a1_backup_sc.rdata")){
    load(file="{{ tmp_path }}a3a1_backup_sc.rdata")
  } else {
    load(file="{{ tmp_path }}sc.rdata")
  }
  save(SC, file="{{ tmp_path }}a3a1_backup_sc.rdata");
  cat("<h3>remove unneeded MSrun from MCQR analysis</h3>")
  summary(SC)
  
  test_list <- c({{ msrun_list_drop }})
  if (length(test_list) > 0) {
    SC <- mcq.drop(SC, factor="msrun", levels=c({{ msrun_list_drop }}))
  }
  summary(SC)
  save(SC, file="{{ tmp_path }}sc.rdata")
  unlink("{{ tmp_path }}a3a2_backup_sc.rdata")
{% elif step == "a4_mcqr_filter_protein" %}
  if(file.exists("{{ tmp_path }}a4_backup_sc.rdata")){
    load(file="{{ tmp_path }}a4_backup_sc.rdata")
  } else {
    load(file="{{ tmp_path }}sc.rdata")
  }
  save(SC, file="{{ tmp_path }}a4_backup_sc.rdata");
  cat("<h1>Filtering proteins</h1>")
  cat("<p>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.</p>")
  
  SC <- mcq.drop.low.counts(SC, cutoff={{ prot_cutoff }})

  cat("<p>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.</p>")
  
  SC <-  mcq.drop.low.fold.changes(SC, cutoff={{ foldchange_cutoff }}, flist=c({{ factors_list }}))
  
  save(SC, file="{{ tmp_path }}sc.rdata")
  
{% elif step == "a5_mcqr_heatmap" %}
  load(file="{{ tmp_path }}sc.rdata")
  
  cat("<h1>Overview of protein abundances</h1>")
  cat("<h2>Plotting a heatmap</h2>")
  cat("<p>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</p>")
   
  png("{{ tmp_path }}prot_heatmap.png", width=1000, height=1000);
  heatmap.prot.list <- mcq.plot.heatmap(SC, flist=c({{ factors_list }}), factorToColor=c({{ factors_color }}), distfun="{{ distance_fun }}", method="{{ agg_method }}", getProtlist = TRUE)
  capture.output(dev.off(), file=stderr());
  pimg_srcpng(path="{{ tmp_path }}",prefix="prot_heatmap");
{% elif step == "a6_mcqr_cluster" %}
  
  load(file="{{ tmp_path }}sc.rdata")
  cat("<h1>Protein clustering</h1>")
  cat("<h2>Cluster for the factor(s) of interest</h2>")
  SC_cluster <- mcq.compute.cluster(SC, flist=c({{ factors_list }}), nbclust={{ nb_cluster }})

  svglite("{{ tmp_path }}prot_cluster.svg", width=14, height=12);
  mcq.plot.cluster(SC_cluster, method="{{ cluster_method }}")
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="prot_cluster");

{% elif step == "a7_mcqr_anova" %}
  load(file="{{ tmp_path }}sc.rdata")
  
  cat("<h1>Analyzing protein abundance variations</h1>")
  cat("<p>Removing proteins showing little abundance variations. 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.</p>")
  SC <- mcq.drop.low.fold.changes(SC, cutoff={{ fc_cutoff }}, flist=c({{ factors_list }}))

  cat("<h4>Differential analysis</h4>")
  cat("<p>ANOVA for the factors of interest.</p>")
  SC_ANOVA <- mcq.compute.anova(SC, flist=c({{ factors_list }}), inter={{ inter_bool }})

  svglite("{{ tmp_path }}anova.svg", width=14, height=12);
  mcq.plot.pvalues(SC_ANOVA)
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="anova");
  
  save(SC_ANOVA, file="{{ tmp_path }}sc_anova.rdata");
  
  save(SC, file="{{ tmp_path }}a7_backup_sc.rdata")
{% elif step == "a8_mcqr_plot_protein_abundance" %}
  load(file="{{ tmp_path }}sc_anova.rdata")
  load(file="{{ tmp_path }}a7_backup_sc.rdata")
  
  cat("<h4>Tukey test</h4>")
  cat("<p>Analyzing the proteins showing significant variations</p>")
  {% for factor in factors_string_list %}
    cat("<h4>Analyse the {{ factor }} factor</h4>")
    cat("<p>Retrieving the proteins showing significant abundance variations for a given factor</p>")
    capture.output(SC_PROTEINS_selected_{{factor}} <- mcq.select.pvalues(SC_ANOVA, padjust={{ padjust }}, alpha={{ alpha }}, flist=c("{{ factor }}")), file=stderr())

    cat("<p>Retrieving of the abundance data for the selected proteins</p>")
    capture.output(SC_selected_{{ factor }} <- mcq.select.from.protlist(SC, SC_PROTEINS_selected_{{ factor }}), file=stderr())
      
      
    cat("<h4>Tukey test</h4>")
    cat("<p>(the URL provide in the PAPPSO site it's an unstable version, waiting for the stable one)</p>")
    capture.output(SC_selected_tukey <- mcq.compute.tukey(SC_ANOVA, flist=c("{{ factor }}"), selected_list=SC_PROTEINS_selected_{{ factor }}), file=stderr())

    # Display of the graph on the screen
    svglite("{{ tmp_path }}tukey_{{ factor }}_%d.svg", width=14, height=12);
    capture.output(mcq.plot.tukey(SC_selected_tukey, qprot=SC), file=stderr())
    capture.output(dev.off(), file=stderr());
    
    
    pimg_srcsvg(path="{{ tmp_path }}",prefix="tukey_{{ factor }}_");
  {%endfor%}
  
  factor_list <- c({{ factors_list_join }})
  if (length(factor_list) == 1) {
    union_list <- {% for factor in factors_string_list %}SC_PROTEINS_selected_{{factor}}{% endfor %}
  } else {
    capture.output(union_list <- union({% for factor in factors_string_list %}
                        SC_PROTEINS_selected_{{factor}}
                        {%if factor != factors_string_list|last %}, {%endif%}
                      {% endfor %}), file=stderr())
  }
  capture.output(SC_selected <- mcq.select.from.protlist(SC, protlist = union_list), file=stderr())
  
  cat("<h3>Plot of individual protein abundances</h3>")
  svglite("{{ tmp_path }}prot_abundance%d.svg", width=14, height=12);
  capture.output(mcq.plot.protein.abundance(SC_selected, factorToColor=c({{ factors_color }}), flist=c({{ factors_list_join }})), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="prot_abundance");
  
  save(SC_selected, file="{{ tmp_path }}sc_selected.rdata");
   
{% elif step == "a9_mcqr_protein_abundance_fold_change" %}
  
  load (file="{{ tmp_path }}sc_selected.rdata");
  cat("<h3>Protein abundance ratios</h3>")
  cat("<p>Computing ratios between two levels of a factor of interest</p>")
  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());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="abundance_ratio");

{% endif %}
