{% if step == "libraries" %}


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

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 XIC Analysis</h1>")
  cat("<p>working directory: {{ tmp_path }}</p>")

  cat("<h2>Load XIC data</h2>")
  
  cat("<p>Loading MassChroq data. NB: peptide intensities measured as peak areas are automatically log10-transformed.</p>")
  cat("<p>Directory names must not include a trailing backslash or slash on Windows</p>")
  
  XICRAW <- mcq.read.masschroq(protFile = "{{protein_tsv_file}}", pepFile = "{{peptide_tsv_file}}")

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

{% elif step == "merge_metadata" %}
  load(file="{{ tmp_path }}xicraw_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 quantification data</p>")
  cat("<h1>Merging metadata</h1>")
  XICRAW <- mcq.add.metadata(XICRAW, metadata=META)

  cat("<p>Overview of the content of the 'XICRAW' object</p>")
  summary (XICRAW)
  save(XICRAW, file="{{ tmp_path }}xicraw.rdata")
  cat("<h3>Chromatography checking</h3>")
  cat("<h4>Plot distribution of the width of chromatographic peaks</h4>")
  cat("<p>Checking the distribution of the width of chromatographic peaks. Are there many very large peaks?</p>")
  svglite("{{ tmp_path }}peak_width.svg", width=14, height=12);
  capture.output(mcq.plot.peak.width(XICRAW, byFraction = FALSE), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="peak_width");
  
  cat("<h4>Plot distribution of the standard deviation of RT</h4>")
  cat("<p>Checking the variability of the peptide-mz retention time (RT) by plotting the distribution of the standard deviation of RT. Are there many peptides-mz showing huge variations of their RT?</p>")
  svglite("{{ tmp_path }}rt_variability.svg", width=14, height=12);
  capture.output(mcq.plot.rt.variability(XICRAW, limit={{ upper_x_axis }}), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="rt_variability");

  cat("<h3>Plot injections checking</h3>")
  cat("<h4>Plot number of peptides by tracks and fraction</h4>")
  cat("<p>Checking the number of chromatographic peaks quantified in each injection. Are there injections with much fewer peaks?</p>")
  svglite("{{ tmp_path }}injection_counts.svg", width=14, height=12);
  capture.output(mcq.plot.counts(XICRAW, overlay=TRUE), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="injection_counts");
  
  cat("<h4>Plot intensity profiles for selected factors</h4>")
  cat("<p>Checking the median intensity along the chromatography. Are there injections showing abnormal intensity profiles?</p>")
  svglite("{{ tmp_path }}intensity_profile.svg", width=14, height=12);
  capture.output(mcq.plot.intensity.profile(XICRAW, factorToColor=c({{ factors_color }}), RTinterval={{ rt_interval }}), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="intensity_profile");
  
  cat("<h4>Plot distribution of peptide intensities for each injection</h4>")
  cat("<p>Checking the distribution of the peptide-mz log-intensities in each injection. Are there injections where intensities are not normally distributed?</p>")
  svglite("{{ tmp_path }}intensity_distribution%d.svg", width=14, height=12);
  capture.output(mcq.plot.intensity.distribution(XICRAW), file=stderr())
  capture.output(dev.off(), file=stderr());
  
  pimg_srcsvg(path="{{ tmp_path }}",prefix="intensity_distribution");

  unlink("{{ tmp_path }}a3a1_backup_xicraw.rdata")
  unlink("{{ tmp_path }}a4a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a4a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a5a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a5a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a6a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a6a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a7_backup_xic.rdata")
  
{% elif step == "a2a2_mcqr_pca" %}
  load(file="{{ tmp_path }}xicraw.rdata")
  cat("<h4>Principal Component Analysis</h4>")
  cat("<p>PCA using all the samples as individuals</p>")
  capture.output(XIC_PCA <- mcq.compute.pca(XICRAW), 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 }}a2a2_xic_pca_%d.svg", width=14, height=12);
  capture.output(mcq.plot.pca(XIC_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="a2a2_xic_pca_");
{% elif step == "a3a1_mcqr_removeMsrun" %}
  if(file.exists("{{ tmp_path }}a3a1_backup_xicraw.rdata")){
    load(file="{{ tmp_path }}a3a1_backup_xicraw.rdata")
  } else {
    load(file="{{ tmp_path }}xicraw.rdata")
  }
  save(XICRAW, file="{{ tmp_path }}a3a1_backup_xicraw.rdata");
  cat("<h3>remove unneeded MSrun from MCQR analysis</h3>")
  summary(XICRAW)
  
  test_list <- c({{ msrun_list_drop }})
  if (length(test_list) > 0) {
    XICRAW <- mcq.drop(XICRAW, factor="msrun", levels=c({{ msrun_list_drop }}))
  }
  summary(XICRAW)
  save(XICRAW, file="{{ tmp_path }}xicraw.rdata")
  unlink("{{ tmp_path }}a3a2_backup_xicraw.rdata")
  unlink("{{ tmp_path }}a4a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a4a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a5a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a5a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a6a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a6a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a7_backup_xic.rdata")
{% elif step == "a3a2_mcqr_dubiousDataFilter" %}
  
  if(file.exists("{{ tmp_path }}a3a2_backup_xicraw.rdata")){
    load(file="{{ tmp_path }}a3a2_backup_xicraw.rdata")
  } else {
    load(file="{{ tmp_path }}xicraw.rdata")
  }
  save(XICRAW, file="{{ tmp_path }}a3a2_backup_xicraw.rdata");
  cat("<h3>before MCQR dubious data filter</h3>")
  summary(XICRAW)
  
  cat("<p>#############  If necessary, removing dubious chromatographic data</p>")
  cat("<p>Removing peptides-mz showing too much variations of their retention time. These peptides-mz may occur from mis-identifications. Use the plot produced by the mcq.plot.rt.variability function to decide on the cut-off of standard deviation to use (e.g. here, 20 seconds).</p>")
  capture.output(XIC <- mcq.drop.variable.rt(XICRAW, cutoff={{ cutoff_rt }}), file=stderr())
  
  cat("<p>Removing peptides-mz associated to very large chromatographic peaks. Use the plot produced by the mcq.plot.peak.width function to decide on the cut-off to use (e.g. here, 200 seconds). Don't be too stringent with this filter because the peak width is proportional to the peak height. A large peak may therefore simply correspond to a peptide-mz that is particularly intense in a given injection.</p>")
  capture.output(XIC <- mcq.drop.wide.peaks(XIC, cutoff={{ cutoff_peaks }}), file=stderr())

  cat("<p>############# Display of a summary of the 'XIC' object after removal of dubious peptides</p>")
 
  cat("<h3>after MCQR dubious data filter</h3>")
  summary(XIC)
  save(XIC, file="{{ tmp_path }}xic.rdata")
  unlink("{{ tmp_path }}a4a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a4a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a5a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a5a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a6a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a7_backup_xic.rdata")
{% elif step == "a4a1_mcqr_normalization" %}
  if(file.exists("{{ tmp_path }}a4a1_backup_xic.rdata")){
    load(file="{{ tmp_path }}a4a1_backup_xic.rdata")
  } else if(file.exists("{{ tmp_path }}xic.rdata")){
    load(file="{{ tmp_path }}xic.rdata")
  } else {
    load(file="{{ tmp_path }}xicraw.rdata")
    XIC <- XICRAW
  }
  save(XIC, file="{{ tmp_path }}a4a1_backup_xic.rdata");

  cat("<h3>Normalizing peptide-mz intensities</h3>")
  
  cat("<p>Normalizing peptide-mz intensities to take into account possible global quantitative variations between LC-MS runs</p>")
  cat("<p>############# Normalizing peptide-mz intensities</p>")
  {% if msrun_reference == "" %}
  capture.output(XIC <- mcq.compute.normalization(XIC, method="{{ norm_method }}"), file=stderr())
  {% else %}
  capture.output(XIC <- mcq.compute.normalization(XIC, method="{{ norm_method }}", ref="{{ msrun_reference }}"), file=stderr())
  {% endif %}
  
  cat("<h4>Control the normalization effets</h4>")
  cat("<p>Checking the median intensity along the chromatography after normalization.</p>")
  svglite("{{ tmp_path }}intensity_profile_after_norm.svg", width=14, height=12);
  capture.output(mcq.plot.intensity.profile(XIC, factorToColor=c({{ factors_color }}), RTinterval={{ rt_interval }}), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="intensity_profile_after_norm");
  
  cat("<p>############# Controling the effect of normalization on intensities distribution</p>")
  cat("<p># Display of the graph of intensity distributions on the screen</p>")
  svglite("{{ tmp_path }}norm_violin.svg", width=14, height=12);
  mcq.plot.intensity.violin(XIC, factorToColor=c({{ factors_color }})) ;
  capture.output(dev.off(), file=stderr());
 
  pimg_srcsvg(path="{{ tmp_path }}",prefix="norm_violin");
  
  cat("<h4>Principal Component Analysis</h4>")
  cat("<p>PCA using all the samples as individuals</p>")
  capture.output(XIC_PCA <- mcq.compute.pca(XIC), 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 }}xic_pca_%d.svg", width=14, height=12);
  capture.output(mcq.plot.pca(XIC_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="xic_pca_");
  
  save(XIC, file="{{ tmp_path }}xic.rdata");
  unlink("{{ tmp_path }}a4a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a5a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a5a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a6a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a6a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a7_backup_xic.rdata")
{% elif step == "a4a2_mcqr_norm_remove_msrun" %}
  if(file.exists("{{ tmp_path }}a4a2_backup_xic.rdata")){
    load(file="{{ tmp_path }}a4a2_backup_xic.rdata")
  } else {
    load(file="{{ tmp_path }}xic.rdata")
    save(XIC, file="{{ tmp_path }}a4a2_backup_xic.rdata");
  }
  cat("<h3>remove unneeded MSrun from MCQR analysis after normalization</h3>")
  cat("<p>XIC summary before removing MSrun</p>")
  summary(XIC)
  
  
  test_list <- c({{ msrun_list_drop }})
  if (length(test_list) > 0) {
    XIC <- mcq.drop(XIC, factor="msrun", levels=c({{ msrun_list_drop }}))
  }
  cat("<p>XIC summary after removing MSrun</p>")
  summary(XIC)
  save(XIC, file="{{ tmp_path }}xic.rdata")
  unlink("{{ tmp_path }}a5a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a5a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a6a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a6a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a7_backup_xic.rdata")

{% elif step == "a5a1_mcqr_filter_shared" %}
  if(file.exists("{{ tmp_path }}a5a1_backup_xic.rdata")){
    load(file="{{ tmp_path }}a5a1_backup_xic.rdata")
  } else {
    load(file="{{ tmp_path }}xic.rdata")
    save(XIC, file="{{ tmp_path }}a5a1_backup_xic.rdata");
  }
  cat("<h3>Filtering for shared peptides-mz</h3>")
  
  
  cat("<h4>initial XIC summary before removing shared peptides</h4>")
  summary(XIC)
  cat("<p>############# Checking the distribution of the number of proteins to which a peptide-mz belongs. Remark : a peptide that belongs to only one protein in the dataset is not proteotypic to this protein. It is in fact specific of a sub-group of i2MassChroQ</p>")
  
  cat("<h4>Plot peptide sharing</h4>")
  svglite("{{ tmp_path }}peptide_sharing.svg", width=14, height=12);
  mcq.plot.peptide.sharing(XIC) 
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="peptide_sharing");
  
  cat("<h4>Removing shared peptides</h4>")
  capture.output(XIC <- mcq.drop.shared.peptides(XIC), file=stderr())
  
  cat("<h4>XIC summary after removing shared peptides</h4>")
  summary(XIC)

  
  save(XIC, file="{{ tmp_path }}xic.rdata");
  unlink("{{ tmp_path }}a5a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a6a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a6a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a7_backup_xic.rdata")
{% elif step == "a5a2_mcqr_filter_unreproducible" %}
  if(file.exists("{{ tmp_path }}a5a2_backup_xic.rdata")){
    load(file="{{ tmp_path }}a5a2_backup_xic.rdata")
  } else {
    load(file="{{ tmp_path }}xic.rdata")
    save(XIC, file="{{ tmp_path }}a5a2_backup_xic.rdata");
  }
  cat("<h3>Filtering for unreproducible peptides-mz</h3>")
  
    
  cat("<h4>XIC summary before removing unreproducible peptides</h4>")
  summary(XIC)

  cat("<h4>Checking the reproducibility of the peptides-mz</h4>")
  cat("<h4>Plot reproducibility of peptides</h4>")
  svglite("{{ tmp_path }}peptide_reproducible_%d.svg", width=14, height=12);
  mcq.plot.peptide.reproducibility(XIC)
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="peptide_reproducible_");
  
  
  cat("<p>############# Removing peptides-mz showing too many missing data (here two conditions \"mutant\" WT and KO, 4 replicates. With percentNA=0.5, peptides-mz showing 2 or more missing values per \"mutant\" condition are therefore removed. We tolerate 4 missing values.</p>")

  
  capture.output(XIC <- mcq.drop.unreproducible.peptides(XIC, method="{{ drop_method }}", percentNA={{ percent_na }}), file=stderr())

  cat("<p># Display of a summary of the 'XIC' object after removal of peptides that are absent in more than a given proportion of the injections</p>")
  
  cat("<h4>XIC summary after filtering shared and unreproducible peptides</h4>")
  summary(XIC)

  {% if nb_factor_levels > 4 %}
    cat("<p>############# Checking of the correlation of the peptides-mz belonging to a same protein</p>")
    cat("<h4>Plot the peptide intensity to choose correlation cutoff</h4>")
    svglite("{{ tmp_path }}peptide_intensity_corr.svg", width=14, height=12);
    capture.output(PROTS <- mcq.plot.peptide.intensity(XIC, flist=c({{ factors_list }}), rCutoff = {{ corr_cutoff }},  nprot={{ n_prot_corr }}, getProtlist=TRUE, showImputed={{ filter_imputed }}, log = {{ filter_log }}), file=stderr())
    capture.output(dev.off(), file=stderr());
    pimg_srcsvg(path="{{ tmp_path }}",prefix="peptide_intensity_corr");
  {% else %}
    cat("<h4>The factor or the combination of factors chosen should have at least 5 levels to compute correlations. There are only {{ nb_factor_levels }} for :</h4>")
    c({{ factors_list }});
  {% endif %}
  
  save(XIC, file="{{ tmp_path }}xic.rdata");
  unlink("{{ tmp_path }}a6a1_backup_xic.rdata")
  unlink("{{ tmp_path }}a6a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a7_backup_xic.rdata")

{% elif step == "a6a1_mcqr_filter_uncorrelated" %}
  
  if(file.exists("{{ tmp_path }}a6a1_backup_xic.rdata")){
    load(file="{{ tmp_path }}a6a1_backup_xic.rdata")
  } else {
    load(file="{{ tmp_path }}xic.rdata")
    save(XIC, file="{{ tmp_path }}a6a1_backup_xic.rdata");
  }
  cat("<h4>XIC summary before filtering uncorrelated peptides</h4>")
  summary(XIC)
  cat("<p>############# Removing the peptides-mz whose intensity profile deviates from the average profile of the peptides-mz from the same protein. This filter must be applied only if the number of levels within one of the factors of interest (factors like replicates not included) is superior or equal to 5 because it is based on the correlation between peptides-mz belonging to the same protein.</p>")
      
  capture.output(XIC <- mcq.drop.uncorrelated.peptides(XIC, flist=c({{ factors_list }}), rCutoff = {{ cor_cutoff }}), file=stderr())


  # Display of a summary of the 'XIC' object after removal of uncorrelated peptides
  cat("<h4>XIC summary after filtering uncorrelated peptides</h4>")
  summary(XIC)
  save(XIC, file="{{ tmp_path }}xic.rdata");
  unlink("{{ tmp_path }}a6a2_backup_xic.rdata")
  unlink("{{ tmp_path }}a7_backup_xic.rdata")

{% elif step == "a6a2_mcqr_filter_few_peptides" %}
  
  if(file.exists("{{ tmp_path }}a6a2_backup_xic.rdata")){
    load(file="{{ tmp_path }}a6a2_backup_xic.rdata")
  } else {
    load(file="{{ tmp_path }}xic.rdata")
    save(XIC, file="{{ tmp_path }}a6a2_backup_xic.rdata");
  }
  cat("<h4>XIC summary before filtering proteins with a small number of peptides-mz</h4>")
  summary(XIC)
  cat("<p>############# Removing proteins quantified by a small number of peptides-mz. When the minimal number of peptides-mz required is 2, this filter is automatically included in the mcq.drop.uncorrelated.peptides function. The function mcq.drop.proteins.with.few.peptides is therefore unnecessary.</p>")

  
  capture.output(XIC <- mcq.drop.proteins.with.few.peptides(XIC, npep = {{ nb_pep }}), file=stderr())

  # Display of a summary of the 'XIC' object after removal of uncorrelated peptides
  cat("<h4>XIC summary after filtering proteins with a small number of peptides-mz</h4>")
  summary(XIC)
  save(XIC, file="{{ tmp_path }}xic.rdata");
  unlink("{{ tmp_path }}a7_backup_xic.rdata")

{% elif step == "a7_mcqr_imputation" %}
  if(file.exists("{{ tmp_path }}a7_backup_xic.rdata")){
    load(file="{{ tmp_path }}a7_backup_xic.rdata")
  } else {
    load(file="{{ tmp_path }}xic.rdata")
    save(XIC, file="{{ tmp_path }}a7_backup_xic.rdata");
  }
  load(file="{{ tmp_path }}xic.rdata")
  cat("<h3>Imputing missing peptide intensities and protein abundance</h3>")
  cat("<p># Imputing missing peptide-mz intensities. No imputation is made for peptide-mz intensity when a protein is completely absent from a sample.</p>")

  capture.output(XIC <- mcq.compute.peptide.imputation(XIC, method="{{ imputation_method }}"), file=stderr())

  # Display of a summary of the 'XIC' object after peptides imputation
  cat("<h4>XIC summary after imputing missing peptide intensities</h4>")
  summary(XIC)

  
  cat("<h3>Computing protein abundances</h3>")
  cat("<p>Computation of the protein abundances as the sum of the peptide intensities</p>")

  capture.output(XICAB <- mcq.compute.protein.abundance(XIC, method="{{ abundance_method }}"), file=stderr())

  # Display of a summary of the 'XICAB' object  
  cat("<h4>XIC summary after computing protein abundance</h4>")
  summary(XICAB)

  cat("<h3>Imputing missing protein abundances</h3>")
  cat("<p>Imputing missing protein abundances by the minimum abundance obtained for each protein in the whole experiment</p>")
  capture.output(XICAB <- mcq.compute.protein.imputation(XICAB), file=stderr())

  cat("<h4>XIC summary after imputing protein abundance</h4>")
  summary(XICAB)
 
  cat("<h2>Overview of the protein abundance data</h2>")

  cat("<h3>Principal Component Analysis</h3>")
  cat("<p>PCA using a factor or a combination of factors as individuals (in this case, average abundances are computed for the factor or for the combination of factors)</p>")
  capture.output(XICAB_PCA <- mcq.compute.pca(XICAB, flist=c({{ factors_list }})), 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 }}xic_ab_pca_%d.svg", width=14, height=12);
  capture.output(mcq.plot.pca(XICAB_PCA, factorToColor=c({{ factors_color }}), labels = c({{ factors_label }}), tagType="both", labelSize=4), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="xic_ab_pca");

  save(XIC, file="{{ tmp_path }}xic.rdata");
  save(XICAB, file="{{ tmp_path }}xicab.rdata");
  
{% elif step == "a8_mcqr_protein_heatmap" %}
  load(file="{{ tmp_path }}xicab.rdata")
  cat("<h4>Protein abundance heatmap</h4>")
  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(XICAB, 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 == "a9_mcqr_protein_cluster" %}
  load(file="{{ tmp_path }}xicab.rdata")
  
  cat("<h4>Protein clustering</h4>")
  cat("<p>Cluster for the factor(s) of interest</p>")
  
  capture.output(XICAB_cluster <- mcq.compute.cluster(XICAB, flist=c({{ factor_list }}), nbclust={{ nb_cluster }}), file=stderr())

  svglite("{{ tmp_path }}prot_cluster.svg", width=14, height=12);
  mcq.plot.cluster(XICAB_cluster, method="{{ cluster_method }}")
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="prot_cluster");
  
  
{% elif step == "b10_mcqr_protein_anova" %}
  load(file="{{ tmp_path }}xicab.rdata")
  
  cat("<h3>Analyzing protein abundance variations</h3>")
  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>")
  XICAB <- mcq.drop.low.fold.changes(XICAB, cutoff={{ fc_cutoff }}, flist=c({{ factors_list }}))

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

  svglite("{{ tmp_path }}anova.svg", width=14, height=12);
  mcq.plot.pvalues(XICAB_ANOVA)
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="anova");
  
  save(XICAB_ANOVA, file="{{ tmp_path }}xicab_anova.rdata");
  save(XICAB, file="{{ tmp_path }}xicab.rdata");
{% elif step == "b11_mcqr_plot_protein_abundance" %}
  load(file="{{ tmp_path }}xicab_anova.rdata")
  load(file="{{ tmp_path }}xicab.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(XICAB_PROTEINS_selected_{{factor}} <- mcq.select.pvalues(XICAB_ANOVA, padjust={{ padjust }}, alpha={{ alpha }}, flist=c("{{ factor }}")), file=stderr())

    cat("<p>Retrieving of the abundance data for the selected proteins</p>")
    capture.output(XICAB_selected_{{ factor }} <- mcq.select.from.protlist(XICAB, XICAB_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(XICAB_selected_tukey <- mcq.compute.tukey(XICAB_ANOVA, flist=c("{{ factor }}"), selected_list=XICAB_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(XICAB_selected_tukey, qprot=XICAB), 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 %}XICAB_PROTEINS_selected_{{factor}}{% endfor %}
  } else {
    capture.output(union_list <- union({% for factor in factors_string_list %}
                        XICAB_PROTEINS_selected_{{factor}}
                        {%if factor != factors_string_list|last %}, {%endif%}
                      {% endfor %}), file=stderr())
  }
  capture.output(XICAB_selected <- mcq.select.from.protlist(XICAB, 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(XICAB_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(XICAB_selected, file="{{ tmp_path }}xicab_selected.rdata");
  
{% elif step == "b12_mcqr_protein_abundance_fold_change" %}
  
  load (file="{{ tmp_path }}xicab_selected.rdata");
  cat("<h3>Protein abundance ratios</h3>")
  cat("<p>Computing ratios between two levels of a factor of interest</p>")
  capture.output(XICAB_RATIO <- mcq.compute.fold.change(XICAB_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(XICAB_RATIO), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="{{ tmp_path }}",prefix="abundance_ratio");

{% elif step == "export_current_pepq_in_proteobench" %}
  
  
library(data.table)


get.proteobench <- function(pepq) {

   # sequence   ProForma  rawfile charge proteins
   #(containing "SPECIES" and separated with ";" if it is a protein group
  if ('ProForma' %in% names(pepq@proteins)) {
  }
  else {
    stop(paste("ProForma column is not present, please use at least MassChroQ version 2.4.5 to produce peptide quantification tables",sep=""))
  }
  data <- getdf(pepq)
  datamproteobench <-data[, c("sequence","ProForma", "z", "accession")]
  #datamsstats$sequence <- gsub("L","I",datamsstats$sequence)
  #datamsstats$sequence <- data$peptiniid
  colnames(datamproteobench) <- c("sequence","ProForma", "charge", "proteins")
  datamproteobench$charge <- data$z
  if ("label" %in% colnames(data)) {
    #datamproteobench$IsotopeLabelType <- data$label
    #datamproteobench$IsotopeLabelType <- str_replace(datamproteobench$IsotopeLabelType, "light", "L")
    #datamproteobench$IsotopeLabelType <- str_replace(datamproteobench$IsotopeLabelType, "heavy", "H")
    #datamproteobench$IsotopeLabelType[is.na(datamproteobench$IsotopeLabelType)] <- "L"
  }
  else {
    #datamproteobench$IsotopeLabelType <- "L"
  }

  datamproteobench$rawfile <- data$msrun
  if("areanorm" %in% colnames(data)){
    datamproteobench$area <- data$areanorm
  } else {
    datamproteobench$area <- data$area
  }
  #populate NA for missing values
  df_unique_ion <- unique(datamproteobench[c("sequence","ProForma", "charge", "proteins")])


  proteobench_conditions <- unique (datamproteobench[,c("rawfile", "proteins")])

  datamproteobench = as.data.table(datamproteobench)

  
  datamproteobench <- merge(cbind(pepq@metadata@injections, row=row.names(pepq@metadata@injections)), datamproteobench, by.x="row", by.y="rawfile")

  datamproteobench$row <- NULL;
  colnames(datamproteobench)[colnames(datamproteobench) == 'msrunfile'] <- 'rawfile'
  return (datamproteobench);

}


getdf <- function(object) {
	protein <- accession <- protein_description <- NULL
    temp_proteins = unique(object@proteins[,c("peptide", "protein", "accession", "protein_description")])
	
	shared.pep <- names(table(temp_proteins$peptide))[table(temp_proteins$peptide)>1]
	tab <- as.data.table(object@proteins[object@proteins$peptide %in% shared.pep,c("peptide", "protein", "accession", "protein_description")])
    tab <- tab[,list(protein = paste(protein, collapse=";"), accession = paste(accession, collapse=";"), protein_description = paste(protein_description, collapse=";")), by="peptide"]
	#tab <- ddply(tab, .(peptide), summarize,  protein=paste(protein, collapse=";"), accession=paste(accession, collapse=";"), protein_description=paste(protein_description, collapse=";"))
	tab <- rbind.data.frame(tab, object@proteins[!object@proteins$peptide %in% shared.pep,c("peptide", "protein", "accession", "protein_description")])

	indice <- match(object@peptides$peptide, tab$peptide)

	object@peptides$protein <- tab$protein[indice]
	object@peptides$accession <- tab$accession[indice]
	object@peptides$protein_description <- tab$protein_description[indice]
	if (nrow(object@metadata@metadata)!=0) {
		tpep <- merge(object@peptides, object@metadata@metadata, by.x="msrun", by.y="row.names")
	}

	tpep <- tpep[order(tpep$msrun,tpep$peptide),]
	colnames(tpep)[which(colnames(tpep)=="logarea")] <- "log10area"
	colnames(tpep)[which(colnames(tpep)=="lognorm")] <- "log10norm"

	
	if ('ProForma' %in% names(object@proteins)) {
	  tpep <- merge(tpep, object@proteins[,c("peptide","ProForma")], by.x="peptide", by.y="peptide", all.x = TRUE)
	}
	return (unique(tpep))
}

  assign('pepq', get(load (file="{{ tmp_path }}{{ pepq_rdatafile }}")))
  cat("<h3>writing proteobench tsv file</h3>")
  
  df_proteobench <- get.proteobench(pepq)
  write.table(df_proteobench, file = "{{ tmp_path }}proteobench_export.tsv", sep = "\t", row.names = F, quote = T)
{% endif %}

