suppressPackageStartupMessages({
  require(IMGTStatClonotype)
  require(shiny)
  require(reshape2)
  require(data.table)
  require(grid)
  require(multtest)
  require(ggplot2)
  library(plotly)
  require(gridExtra)
  require(d3heatmap)
  require(DT)
})
### Other function not integrated in the package
g_legend<-function(a.gplot){tmp <- ggplot_gtable(ggplot_build(a.gplot))
                            leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
                            legend <- tmp$grobs[[leg]]
                            return(legend)}
##
Newcolname<-c("CDR3-IMGT sequence (AA)","Experimental ID","Representative sequence index","Nb of '1 copy\'","Nb of \'More than one\'","Total nb of \'1 copy\' and \'More than one\'",
              "\'1 copy\' Indexes","V-gene","V-allele","D-gene","D-allele", "J-gene","J-allele","CDR1-IMGT","CDR2-IMGT","CDR1-IMGT gapped sequence (AA)","CDR2-IMGT gapped sequence (AA)",
              "V-REGION % identity","Sequence length","C104","F118 or W118","Anchors","Sequence ID","Functionality","Sequence file number","sequence clonotype file number")

ColnameNonIdGenes<-c("Gene_Name","Locus")
###
MTPresultsLogDec<-function(data){
  report <- data.frame(Gene_Name=data$Gene_Name)
  report$z<-data$z
  report$Neglog10_rawp<- (-log10(data$rawp))
  report$Neglog10_Bonferroni<- (-log10(data$Bonferroni))
  report$Neglog10_Holm<- (-log10(data$Holm))
  report$Neglog10_Hochberg<- (-log10(data$Hochberg))
  report$Neglog10_SidakSS<- (-log10(data$SidakSS))
  report$Neglog10_SidakSD<- (-log10(data$SidakSD))
  report$Neglog10_BH<- (-log10(data$BH))
  report$Neglog10_BY<- (-log10(data$BY))
  report$Test_interpretation<-data$Test_interpretation
  colnames(report)<-c("Gene_Name","z (Test statistic)","- log_10 (rawp)","- log_10 (Bonferroni)","- log_10 (Holm)","- log_10 (Hochberg)","- log_10 (SidakSS)","- log_10 (SidakSD)","- log_10 (BH)","- log_10 (BY)","Test_interpretation")
  return(report)
}
###
MTPresultsLogDecAllele<-function(data){
  report <- data.frame(Allele_Name=data$Allele_Name)
  report$z<-data$z
  report[,'z'] <- round(report[,'z'], 2)
  report$ Neglog10_rawp<- (-log10(data$rawp))
  report$Neglog10_Bonferroni<- (-log10(data$Bonferroni))
  report$Neglog10_Holm<- (-log10(data$Holm))
  report$Neglog10_Hochberg<- (-log10(data$Hochberg))
  report$Neglog10_SidakSS<- (-log10(data$SidakSS))
  report$Neglog10_SidakSD<- (-log10(data$SidakSD))
  report$Neglog10_BH<- (-log10(data$BH))
  report$Neglog10_BY<- (-log10(data$BY))
  report$Test_interpretation<-data$Test_interpretation
  colnames(report)<-c("Allele_Name","z (Test statistic)","- log_10 (rawp)","- log_10 (Bonferroni)","- log_10 (Holm)","- log_10 (Hochberg)","- log_10 (SidakSS)","- log_10 (SidakSD)","- log_10 (BH)","- log_10 (BY)","Test_interpretation")
  return(report)
}
### By default, Shiny limits file uploads to 5MB per file. This limit is increased to 900 MB
options(shiny.maxRequestSize=900*1024^2)
###
shinyServer(function(input, output, session) {
  observe({
    if(input$Quit==0){
    } else{ isolate({stopApp()})} })

  filedata1 <- reactive({
    infile1 <- input$files1
    if (is.null(infile1)) {
    # User has not uploaded a file yet
    return(NULL)}
    h <-read.delim(infile1$datapath,sep="\t",dec="," ,na.strings=c("NA","null"),header=TRUE, stringsAsFactors =FALSE, colClasses=c("c104"="character","f118"="character"))
    h[is.na(h)] <- ""
    h})

  file_info1 <- reactive({
    infile1 <- input$files1
    validate( need(!is.null(infile1),HTML("Please choose IMGT/HighV-QUEST set 1"))
    )
    name <- (input$files1)[1]
  })

  file_info2 <- reactive({
    infile2 <- input$files2
    validate(need(!is.null(infile2), HTML("Please choose IMGT/HighV-QUEST set 2"))
    )
    name <- (input$files2)[1]
  })

  info1 <- reactive({ s1 = unlist(strsplit(as.character( file_info1()), split='.txt', fixed=TRUE))  })
  info2 <- reactive({ s2 = unlist(strsplit(as.character( file_info2()), split='.txt', fixed=TRUE))  })

  output$Info1 <- renderText({  paste("Set 1: ",HTML('<span style=color:#FF8000> ',info1() ))  })
  output$Info11 <- renderText({  paste("Set 1: ",HTML('<span style=color:#FF8000> ',info1() ))  })
  output$InfoSynGph1 <- renderText({  paste("Set 1: ",HTML('<span style=color:#FF8000> ',info1() ))  })
  output$Info2 <-renderText ({  paste("Set 2: ",HTML('<span style=color:#FF8000> ',info2() ))  })
  output$Info22 <- renderText ({  paste("Set 2: ",HTML('<span style=color:#FF8000> ',info2() ))  })
  output$InfoSynGph2 <- renderText ({  paste("Set 2: ",HTML('<span style=color:#FF8000> ',info2() ))  })


  set1 <- reactive({ clonRem(filedata1(), min=input$cdrlength[1], max=input$cdrlength[2])})

  set1Disp <- reactive({set1()})
  set1Removedseq<-reactive({
    clonRemseq <-function(set1, min=4, max=45){
    set1rem<- subset(set1,((nchar(as.character(set1[,1]))>max)==TRUE | (nchar(as.character(set1[,1]))<min)==TRUE))
    return(set1rem) }
    clonRemseq(filedata1(), min=input$cdrlength[1], max=input$cdrlength[2]) })
   set1RemovedseqDisp<-reactive({set1Removedseq()})

  filedata2 <- reactive({
    infile2 <- input$files2
    if (is.null(infile2)) {
    # User has not uploaded a file yet
    return(NULL)}
  h <- read.delim(infile2$datapath,sep="\t",dec="," ,na.strings=c("NA","null"),header=TRUE, stringsAsFactors =FALSE, colClasses=c("c104"="character","f118"="character"))
  h[is.na(h)] <- ""
  h})
  set2 <- reactive({clonRem(filedata2(), min=input$cdrlength[1], max=input$cdrlength[2])})
  set2Disp <- reactive({set2()})
  set2Removedseq<-reactive({
      clonRemseq <-function(set1, min=4, max=45){
      set2rem<- subset(set1,((nchar(as.character(set1[,1]))>max)==TRUE | (nchar(as.character(set1[,1]))<min)==TRUE))
      return(set2rem)}
      clonRemseq(filedata2(), min=input$cdrlength[1], max=input$cdrlength[2]) })

  set2RemovedseqDisp<-reactive({set2Removedseq() })

  NdivSeveralSingle <- reactive({
  MID <-clonNumDiv(set1(),set2())
  if (input$Type_gene=="Single genes"){
    divwor <-  droplevels(MID[- grep("or", MID$Gene_Name),,drop=TRUE])
    if (length(divwor[,1])==0){divwor <-MID}
  divwor} else if (input$Type_gene=="Several genes") {divwor <- MID}})

  NexpSeveralSingle <- reactive({
    MID <- clonNumExp(set1(),set2())
    if (input$Type_gene=="Single genes"){
      divwor <-  droplevels(MID[- grep("or", MID$Gene_Name),,drop=TRUE])
      if (length(divwor[,1])==0){divwor <-MID}
      divwor} else {divwor <- MID}})

  Ndiv <- reactive({if (input$Type_AnalysisGene=="Yes"){divwor <- NdivSeveralSingle()[which(NdivSeveralSingle()$Proportion.set1>=5 & NdivSeveralSingle()$Proportion.set2>=5),]} else if (input$Type_AnalysisGene=="No") {divwor <- NdivSeveralSingle()} })
  Nexp <- reactive({if (input$Type_AnalysisGene=="Yes"){ divwor <- NexpSeveralSingle()[which(NexpSeveralSingle()$Proportion.set1>=5 & NexpSeveralSingle()$Proportion.set2>=5),]} else if (input$Type_AnalysisGene=="No") {divwor <- NexpSeveralSingle()}})

  div <- reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    sigrepDiv(Ndiv(),set1(),set2())})
  exp <- reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    sigrepExp(Nexp(),set1(),set2())})

  NdivExcl <- reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    divwor <- NdivSeveralSingle()})
  NexpExcl <- reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    divwor <- NexpSeveralSingle()})

  ExcludeDivExp<-function(Data,data1,data2){
    report <- data.frame(Gene_Name=Data$Gene_Name)
    report$Gene_Type <- paste(sapply(strsplit(as.character(report[,1]), " "), function(x) substr(x[[2]],4,4)), "gene")
    report$Nb_IMGT_clonotype_AA.set1 <- Data$Proportion.set1
    ifelse (input$TypeClono=="diversity",report$Proportion.set1 <- Data$Proportion.set1/length(clonRem(data1)$expid),report$Proportion.set1 <- Data$Proportion.set1/sum(clonRem(data1)$total))
    report$Normalized_proportion.set1    <-  report$Proportion.set1*10000
    report$Nb_IMGT_clonotype_AA.set2<-Data$Proportion.set2
    ifelse (input$TypeClono=="diversity", report$Proportion.set2   <- Data$Proportion.set2/length(clonRem(data2)$expid),report$Proportion.set2 <- Data$Proportion.set2/sum(clonRem(data2)$total) )
    report$Normalized_proportion.set2 <-  report$Proportion.set2*10000
    return(report[which(report[,3]<5 | report[,6]<5),])}

  divExcl <- reactive({ ExcludeDivExp(NdivExcl(),set1(),set2())})
  expExcl <- reactive({ ExcludeDivExp(NexpExcl(),set1(),set2())})
############################################################
  NonIdGeneOrd<-reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    NonIdGeneOrder<- function(set1,set2){
    utils::data("GeneList", envir = environment())
    GeneList <- get("GeneList", envir  = environment())
    li1<-c(levels(factor(set1$vgene)),levels(factor(set1$jgene)))
    li2<-c(levels(factor(set2$vgene)),levels(factor(set2$jgene)))
    li<-levels(as.factor(c(li1,li2)))
    lia1<-c(levels(factor(set1$vallele)),levels(factor(set1$jallele)))
    lia2<-c(levels(factor(set2$vallele)),levels(factor(set2$jallele)))
    lia<-levels(as.factor(c(lia1,lia2)))
    fonctionality<-sapply(strsplit(lia, " "), function(x) x[[3]])
    genenamefromallele<-sapply(strsplit(lia, "\\*"), function(x) x[[1]])
    genewithf<-paste(genenamefromallele[match(li, genenamefromallele)],fonctionality[match(li, genenamefromallele)])
    geneswithoutf<-sapply(strsplit(genewithf, " "), function(x) paste(x[[1]],x[[2]]))
    i<-match(li, GeneList$GeneList,nomatch=0)
    if (identical(li[i == 0], character(0))==FALSE){
      GeneListModified<-GeneList
      q<-data.frame(li[i == 0])
      gg<-match(as.character(q[,1]),geneswithoutf)
      q$Species<-sapply(strsplit(as.character(q[,1]), " "), function(x) (x[[1]]))
      q$GeneListF<-genewithf[gg]
      q$Locus <- sapply(strsplit(as.character(q[,1]), " "), function(x) substr(x[[2]],1,3))
      q$ID<-0
      return(q[,c(1,4)])}else if (identical(li[i == 0], character(0))==TRUE){ Note1<-"All genes are ordered for this pairwise comparison"
      Note2<-""
      Note<-cbind(Note1,Note2)
      return(data.frame(Note))}
    }
    NonIdGeneOrder(set1(),set2())
  })
  NOG<-reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    NonIdGeneOrd()})
  output$NonIdgeneOrders <- renderDataTable({
        datatable( NOG(), colnames = ColnameNonIdGenes,rownames=FALSE,options = list(searchHighlight = TRUE,lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
                   pageLength = 5, autoWidth = TRUE, orderClasses = TRUE))})
###########################################################

  output$NbClonoSet1<-renderText({ paste("The number of IMGT clonotypes (AA) in set 1 is: ",HTML('<span style=color:#FF8000> ',length(set1()$expid) ))})

  NbclonoSet1Dgene <- reactive({Nbclono1Dgene<- paste("The number of IMGT clonotypes (AA) in set 1 is ",HTML('<span style=color:#FF8000> ',length(set1()$expid)),HTML('<span style=color:#000000> '," of which "),HTML('<span style=color:#FF8000> ',length(set1()[which(set1()$dgene != ""), ]$expid)),HTML('<span style=color:#000000> ',"with identified D genes."))})

  output$NbClonoSet1Dgene<-renderText({NbclonoSet1Dgene()})

  output$NbSeqSet1<-renderText({ paste("The number of sequences assigned to IMGT clonotypes (AA) in set 1 is: ",HTML('<span style=color:#FF8000> ',sum(set1()$total) ))})

  NbseqSet1Dgene<- reactive({ Nbseq1Dgene<-paste("The number of sequences assigned to IMGT clonotypes (AA) in set 1 is ",HTML('<span style=color:#FF8000> ',sum(set1()$total) ),HTML('<span style=color:#000000> '," of which "),HTML('<span style=color:#FF8000> ',sum(set1()[which(set1()$dgene != ""), ]$total)),HTML('<span style=color:#000000> ',"with identified D genes."))})

  output$NbClonoSet2<-renderText({ paste("The number of IMGT clonotypes (AA) in set 2 is: ",HTML('<span style=color:#FF8000> ',length(set2()$expid)))})

  NbclonoSet2Dgene <- reactive({Nbclono2Dgene<- paste("The number of IMGT clonotypes (AA) in set 2 is ",HTML('<span style=color:#FF8000> ',length(set2()$expid)),HTML('<span style=color:#000000> '," of which "),HTML('<span style=color:#FF8000> ',length(set2()[which(set2()$dgene != ""), ]$expid)),HTML('<span style=color:#000000> ',"with identified D genes."))})

  output$NbClonoSet2Dgene<-renderText({NbclonoSet2Dgene()})

  output$NbSeqSet2<-renderText({ paste("The number of sequences assigned to IMGT clonotypes (AA) in set 2 is: ",HTML('<span style=color:#FF8000> ',sum(set2()$total)))})

  NbseqSet2Dgene<- reactive({Nbseq2Dgene<-paste("The number of sequences assigned to IMGT clonotypes (AA) in set 2 is ",HTML('<span style=color:#FF8000> ',sum(set2()$total) ),HTML('<span style=color:#000000> '," of which "),HTML('<span style=color:#FF8000> ',sum(set2()[which(set2()$dgene != ""), ]$total)),HTML('<span style=color:#000000> ',"with identified D genes."))})

 output$IMGTclassesset1<-renderText({
    if (input$IMGTAAclasses=="20 amino acids"){paste("Frequencies of the",input$IMGTAAclasses, "at" ,input$Type_CDR,"positions (set 1)")
    }else{paste("Frequencies of IMGT amino acid",input$IMGTAAclasses, "classes at", input$Type_CDR,"positions (set 1)")}})

 output$IMGTclassesset2<-renderText({
   if (input$IMGTAAclasses=="20 amino acids"){paste("Frequencies of the",input$IMGTAAclasses, "at" ,input$Type_CDR,"positions (set 2)")
   }else{paste("Frequencies of IMGT amino acid",input$IMGTAAclasses, "classes at", input$Type_CDR,"positions (set 2)")}})

 output$IMGTclassesset1graph<-renderText({ if (input$IMGTAAclasses=="20 amino acids"){paste("Bar graph of the",input$IMGTAAclasses, "at" ,input$Type_CDR,"positions (set 1)")
 }else{paste("Bar graph of IMGT amino acid",input$IMGTAAclasses, "classes at", input$Type_CDR,"positions (set 1)")}})

 output$IMGTclassesset2graph<-renderText({if (input$IMGTAAclasses=="20 amino acids"){paste("Bar graph of the",input$IMGTAAclasses, "at" ,input$Type_CDR,"positions (set 2)")
 }else{paste("Bar graph of IMGT amino acid",input$IMGTAAclasses, "classes at", input$Type_CDR,"positions (set 2)")}})


 output$BargraphCDRlength<-renderText({if (input$TypeClono=="diversity"){
   ifelse(input$NormVal==TRUE,
          paste("Nb of IMGT clonotypes (AA) per ",input$Type_CDR,"length: normalized bar graphs for set 1 and set 2"),
          paste("Nb of IMGT clonotypes (AA) per ",input$Type_CDR,"length: bar graphs for set 1 and set 2") )
 }else if(input$TypeClono=="expression"){
   ifelse(input$NormVal==TRUE,
          paste("Nb of sequences assigned to IMGT clonotypes (AA) per ",input$Type_CDR,"length: normalized bar graphs for set 1 and set 2"),
          paste("Nb of sequences assigned to IMGT clonotypes (AA) per ",input$Type_CDR,"length: bar graphs for set 1 and set 2"))}
 })
 output$List1perCDRlength<-renderText({
   paste("List of IMGT clonotypes (AA) with selected ",input$Type_CDR,"length (set 1)")
 })
 output$List2perCDRlength<-renderText({
   paste("List of IMGT clonotypes (AA) with selected ",input$Type_CDR,"length (set 2)")
 })
  ########################################################
  output$NbClonoSet11ResDgene<-renderText({
    if (input$TypeClono=="diversity" && input$Gene_Type=="D genes"){ NbclonoSet1Dgene()} else if (input$TypeClono=="expression"&& input$Gene_Type=="D genes"){ NbseqSet1Dgene()}
  })

  output$NbClonoSet22ResDgene<-renderText({
    if (input$TypeClono=="diversity"&& input$Gene_Type=="D genes"){ NbclonoSet2Dgene()} else if (input$TypeClono=="expression"&& input$Gene_Type=="D genes"){ NbseqSet2Dgene()}
  })
###############################################################################################
  output$NbRemClonoSet1<-renderText({ paste("The number of unselected IMGT clonotypes (AA) in set 1 is: ",HTML('<span style=color:#FF8000> ',length(set1Removedseq()$expid) ))})
  output$NbRemSeqSet1<-renderText({ paste("The number of sequences assigned to unselected IMGT clonotypes (AA) in set 1 is: ",HTML('<span style=color:#FF8000> ',sum(set1Removedseq()$total) ))})

  output$NbRemClonoSet2<-renderText({ paste("The number of unselected IMGT clonotypes (AA) in set 2 is: ",HTML('<span style=color:#FF8000> ',length(set2Removedseq()$expid)))})
  output$NbRemSeqSet2<-renderText({ paste("The number of sequences assigned to unselected IMGT clonotypes (AA) in set 2 is: ",HTML('<span style=color:#FF8000> ',sum(set2Removedseq()$total)))})

  output$GeneAssociationset1<-renderText({ paste(input$Type_association, "(set 1)")})
  output$GeneAssociationset2<-renderText({ paste(input$Type_association, "(set 2)")})
  ##################################### Search the CDR1-IMGT, CDR2-IMGT and CDR3-IMGT lengths in the set 1
  searchcdr1length1<- reactive({ l <- levels(as.factor(nchar(as.vector(set1()$cdr1))))
                                    ifelse(("0" %in% l)==TRUE, l<-l[-1], l )
                                 l })
  searchcdr2length1<- reactive({ l <- levels(as.factor(nchar(as.vector(set1()$cdr2))))
                                    ifelse(("0" %in% l)==TRUE, l<-l[-1], l )
                                 l })
  searchcdr3length1<- reactive({ l <- levels(as.factor(nchar(as.vector(set1()$cdr3aa))))
                                     ifelse(("0" %in% l)==TRUE, l<-l[-1], l )
                                 l })
  ###############
  output$selectCDRlength1 <- renderUI({
    if(input$Type_CDR=="CDR1-IMGT"){
      selectInput("CDR1lengthselect1", "CDR1-IMGT length selection (set 1)", searchcdr1length1() )} else if(input$Type_CDR=="CDR2-IMGT"){
        selectInput("CDR2lengthselect1", "CDR2-IMGT length selection (set 1)", searchcdr2length1() )} else if(input$Type_CDR=="CDR3-IMGT"){
          selectInput("CDR3lengthselect1", "CDR3-IMGT length selection (set 1)", searchcdr3length1() )}
  })
  ###################################### Search the IMGT clonotypes (AA) per CDR1-IMGT length in the set 1
  clonperCDRlength1<-reactive({
    if (input$Type_CDR=="CDR1-IMGT"){
      set1()[which(nchar(as.vector(set1()$cdr1))==input$CDR1lengthselect1),]} else if (input$Type_CDR=="CDR2-IMGT"){
        set1()[which(nchar(as.vector(set1()$cdr2))==input$CDR2lengthselect1),]} else if (input$Type_CDR=="CDR3-IMGT"){
          set1()[which(nchar(as.vector(set1()$cdr3aa))==input$CDR3lengthselect1),]}
  })
  output$databaseperCDRlength1 <- renderDataTable({
    datatable(clonperCDRlength1(), colnames = Newcolname, rownames=FALSE,options = list(searchHighlight = TRUE, lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
                                                                                        pageLength = 5, autoWidth = TRUE, orderClasses = TRUE,scrollX='100%',
                                                                                        columnDefs = list(list(width = '170px', targets = "_all"))))
  })
  ###################################### Search the IMGT clonotypes (AA) per CDR-IMGT length in the set 2
  clonperCDRlength2<-reactive({
    if (input$Type_CDR=="CDR1-IMGT"){
      set2()[which(nchar(as.vector(set2()$cdr1))==input$CDR1lengthselect2),]} else if (input$Type_CDR=="CDR2-IMGT"){
        set2()[which(nchar(as.vector(set2()$cdr2))==input$CDR2lengthselect2),]} else if (input$Type_CDR=="CDR3-IMGT"){
          set2()[which(nchar(as.vector(set2()$cdr3aa))==input$CDR3lengthselect2),]}
  })

  output$databaseperCDRlength2 <- renderDataTable({datatable(clonperCDRlength2(), colnames = Newcolname,rownames=FALSE,options = list(searchHighlight = TRUE,
                                                                                                                                      lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
                                                                                                                                      pageLength = 5, autoWidth = TRUE, orderClasses = TRUE,scrollX='100%',
                                                                                                                                      columnDefs = list(list(width = '170px', targets = "_all"))))})

  ### Download corresponding tables
  output$downloaddatabaseperCDRlength1 <- downloadHandler(
    filename = function() {
      paste(input$TypeClono, "-per ",input$Type_CDR," length set 1" ,'.csv', sep="")},
    content = function(file) {
      write.table( clonperCDRlength1(), file, sep = ";",  row.names = FALSE, dec = ",")})

  output$downloaddatabasepergenelength2 <- downloadHandler(
    filename = function() {
      paste(input$TypeClono, "-per ",input$Type_CDR," length set 1" ,'.csv', sep="")},
    content = function(file) {
      write.table( clonperCDRlength2(), file, sep = ";",  row.names = FALSE, dec = ",")})

  ##################################### Search the CDR1-IMGT, CDR2-IMGT and CDR3-IMGT lengths in the set 2
  searchcdr1length2<- reactive({l <- levels(as.factor(nchar(as.vector(set2()$cdr1))))
  ifelse(("0" %in% l)==TRUE, l<-l[-1], l )
  l})
  searchcdr2length2<- reactive({l <- levels(as.factor(nchar(as.vector(set2()$cdr2))))
  ifelse(("0" %in% l)==TRUE, l<-l[-1], l )
  l})
  searchcdr3length2<- reactive({l <- levels(as.factor(nchar(as.vector(set2()$cdr3aa))))
  ifelse(("0" %in% l)==TRUE, l<-l[-1], l )
  l})
  ###############
  output$selectCDRlength2 <- renderUI({
    if(input$Type_CDR=="CDR1-IMGT"){
      selectInput("CDR1lengthselect2", "CDR1-IMGT length selection (set 2)", searchcdr1length2() )} else if(input$Type_CDR=="CDR2-IMGT"){
        selectInput("CDR2lengthselect2", "CDR2-IMGT length selection (set 2)", searchcdr2length2() )} else if(input$Type_CDR=="CDR3-IMGT"){
          selectInput("CDR3lengthselect2", "CDR3-IMGT length selection (set 2)", searchcdr3length2() )}})

###############################################################################################

  output$filetable1Disp <- renderDataTable({
      datatable(set1Disp(), colnames = Newcolname,rownames=FALSE,options = list(searchHighlight = TRUE,lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
              pageLength = 5, autoWidth = TRUE, orderClasses = TRUE,scrollX='100%',
              columnDefs = list(list(width = '170px', targets = "_all"))))})

  output$filetable1RemSeqDisp <- renderDataTable({
    datatable(set1RemovedseqDisp(), colnames = Newcolname,rownames=FALSE, options = list(colReorder = list(realtime = TRUE),lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
              pageLength = 5, autoWidth = TRUE, orderClasses = TRUE,scrollX='100%',
              columnDefs = list(list(width = '170px', targets = "_all"))))})

  output$filetable2 <- renderDataTable({set2()},options = list(lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
                pageLength = 5, autoWidth = TRUE, orderClasses = TRUE))

  output$filetable2Disp <- renderDataTable({
    datatable(set2Disp(), colnames = Newcolname,rownames=FALSE,options = list(searchHighlight = TRUE,lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
              pageLength = 5, autoWidth = TRUE, orderClasses = TRUE,scrollX='100%',
              columnDefs = list(list(width = '150px', targets = "_all"))))})

  output$filetable2RemSeq <- renderDataTable({set2Removedseq()}, options = list(lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
                                                                                pageLength = 5, autoWidth = TRUE, orderClasses = TRUE,searchHighlight = TRUE))

  output$filetable2RemSeqDisp <- renderDataTable({
    datatable(set2RemovedseqDisp(), colnames = Newcolname,rownames=FALSE, options = list(searchHighlight = TRUE,colReorder = list(realtime = TRUE),lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
                                                                                         pageLength = 5, autoWidth = TRUE, orderClasses = TRUE,scrollX='100%',
                                                                                         columnDefs = list(list(width = '180px', targets = "_all"))))})

  DisplayResultsTable <- function(data){

      datatable(cbind(data[,1:2],data[,input$show_vars,drop=FALSE]) ,filter='top',options = list(columnDefs = list(list(width = '180px', targets = "_all" )),lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
              pageLength = 5, autoWidth = TRUE, orderClasses = TRUE,searchHighlight = TRUE))%>%   formatStyle(
                      'z',backgroundColor = styleInterval(c(-1.96, 1.96), c('#FFFF6B','#E5E5E5', '#FFFF6B')), fontWeight = styleInterval(c(-1.96, 1.96),c('bold','normal','bold')))%>%  formatStyle(
                      'rawp', backgroundColor = styleInterval(0.05, c('#FFFF6B','#E5E5E5')),fontWeight = styleInterval(0.05,c('bold','normal')) )%>%   formatStyle(
                      'Bonferroni', backgroundColor = styleInterval(0.05, c('#FFFF6B','#E5E5E5')),fontWeight = styleInterval(0.05,c('bold','normal')) )%>%   formatStyle(
                      'Holm',backgroundColor = styleInterval(0.05,c('#FFFF6B','#E5E5E5')), fontWeight = styleInterval(0.05,c('bold','normal')))%>%   formatStyle(
                      'Hochberg',backgroundColor = styleInterval(0.05, c('#FFFF6B','#E5E5E5')), fontWeight = styleInterval(0.05,c('bold','normal')))%>%   formatStyle(
                      'SidakSS',backgroundColor = styleInterval(0.05, c('#FFFF6B','#E5E5E5')),fontWeight = styleInterval(0.05,c('bold','normal')) )%>%   formatStyle(
                      'SidakSD', backgroundColor = styleInterval(0.05, c('#FFFF6B','#E5E5E5')),fontWeight = styleInterval(0.05,c('bold','normal'))) %>%   formatStyle(
                      'BY',backgroundColor = styleInterval(0.05,c('#FFFF6B','#E5E5E5')),fontWeight = styleInterval(0.05,c('bold','normal'))) %>%   formatStyle(
                      'BH', backgroundColor = styleInterval(0.05,c('#FFFF6B','#E5E5E5')),fontWeight = styleInterval(0.05,c('bold','normal')))}
DisplayResultsTablelog10 <- function(data){
    datatable(data,filter='top',options = list(columnDefs = list(list(width = '180px', targets = "_all")),lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
                       pageLength = 5, autoWidth = FALSE, orderClasses = TRUE,searchHighlight = TRUE))%>%   formatStyle(
                      'z (Test statistic)',backgroundColor = styleInterval(c(-1.96, 1.96), c('#FFFF6B','#E5E5E5', '#FFFF6B')), fontWeight = styleInterval(c(-1.96, 1.96),c('bold','normal','bold')))%>%  formatStyle(
                      '- log_10 (rawp)', backgroundColor = styleInterval(1.301, c('#E5E5E5', '#FFFF6B')),fontWeight = styleInterval(1.301,c('normal','bold')))%>%   formatStyle(
                      '- log_10 (Bonferroni)',backgroundColor = styleInterval(1.301, c('#E5E5E5', '#FFFF6B')),fontWeight = styleInterval(1.301,c('normal','bold')))%>%   formatStyle(
                      '- log_10 (Holm)',backgroundColor = styleInterval(1.301, c('#E5E5E5', '#FFFF6B')),fontWeight = styleInterval(1.301,c('normal','bold')))%>%   formatStyle(
                      '- log_10 (Hochberg)',backgroundColor = styleInterval(1.301, c('#E5E5E5', '#FFFF6B')),fontWeight = styleInterval(1.301,c('normal','bold')))%>%   formatStyle(
                      '- log_10 (SidakSS)',backgroundColor = styleInterval(1.301, c('#E5E5E5', '#FFFF6B')),fontWeight = styleInterval(1.301,c('normal','bold')))%>%   formatStyle(
                      '- log_10 (SidakSD)',backgroundColor = styleInterval(1.301, c('#E5E5E5', '#FFFF6B')),fontWeight = styleInterval(1.301,c('normal','bold')) ) %>%   formatStyle(
                      '- log_10 (BY)',backgroundColor = styleInterval(1.301, c('#E5E5E5', '#FFFF6B')),fontWeight = styleInterval(1.301,c('normal','bold')) ) %>%   formatStyle(
                      '- log_10 (BH)',backgroundColor = styleInterval(1.301, c('#E5E5E5', '#FFFF6B')),fontWeight = styleInterval(1.301,c('normal','bold')))}

#### Test results for genes
  output$testresults <- renderDataTable({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)||!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and  set 2" )
    )
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating table... Please wait.", value = 0)
    if(input$TypeClono=="diversity") {DisplayResultsTable(div())} else if(input$TypeClono=="expression") {DisplayResultsTable(exp())}})

  output$testresultsExcluded <- renderDataTable({
    if(input$TypeClono=="diversity") {df<-divExcl()} else if (input$TypeClono=="expression") {df<-expExcl()}
    datatable(df,filter='top',options = list(columnDefs = list(list(width = '180px', targets = "_all")),lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
                                                                                             pageLength = 5, autoWidth = FALSE, orderClasses = TRUE,searchHighlight = TRUE))})

  observeEvent(input$hide3,{toggle("testresultsExcluded")})
#### Test results for allles of genes having a difference in proportions significant by all precedures
  AlleleAllp <-reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    if( input$TypeClono=="diversity"){div()[which(div()$Test_interpretation=="Significant (All_p)  "),]} else  {exp()[which(exp()$Test_interpretation=="Significant (All_p)  "),]}})

  # Function to extract alleles (single or several) ID from set 1 and set 2
  ExtractAllele <- function (data, data1 ){
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    if (input$Type_allele=="Single alleles"){
      data11 <-  droplevels(data[- grep("or", data$vallele),,drop=TRUE])
      if (length(data11[,1])==0){data11 <- data}
      data <- data11
      data11 <-  droplevels(data[- grep("or", data$jallele),,drop=TRUE])
      if (length(data11[,1])==0){data11 <- data}
      data <- data11
      data11 <-  droplevels(data[- grep("or", data$dallele),,drop=TRUE])
      if (length(data11[,1])==0){data11 <- data}
      data <- data11
      } else if (input$Type_allele=="Several alleles"){data <- data}
    genenamesetv <- sapply(strsplit(as.character(data$vgene), " "), function(x) x[[2]])
    genenamesetj <- sapply(strsplit(as.character(data$jgene), " "), function(x) x[[2]])
    datad <- data[which(data$dgene != ""), ]
    genenamesetd <- sapply(strsplit(as.character(datad$dgene), " "), function(x) x[[2]])
    genenameAllp <- sapply(strsplit(as.character(data1$Gene_Name), " "), function(x) x[[2]])
    AllpMIDv <- droplevels(data[genenamesetv %in% genenameAllp,])
    AllpMIDj <- droplevels(data[genenamesetj %in% genenameAllp,])
    AllpMIDd <- droplevels(datad[genenamesetd %in% genenameAllp,])
    return(list(AllpMIDvallele=AllpMIDv,AllpMIDjallele=AllpMIDj,AllpMIDdallele=AllpMIDd))}

  NdivexpAllele <- reactive({
  infile1 <- input$files1
  infile2 <- input$files2
  validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
  av1 <- ExtractAllele(set1(),AlleleAllp())$ AllpMIDvallele
  aj1 <- ExtractAllele(set1(),AlleleAllp())$ AllpMIDjallele
  ad1 <- ExtractAllele(set1(),AlleleAllp())$ AllpMIDdallele
  t1 = rbind(as.data.frame(table(av1$vallele)),as.data.frame(table(aj1$jallele)), as.data.frame(table(ad1$dallele)) )
  colnames(t1) = c('Gene_Name','Proportion.set1')
  av2 <- ExtractAllele(set2(),AlleleAllp())$AllpMIDvallele
  aj2 <- ExtractAllele(set2(),AlleleAllp())$AllpMIDjallele
  ad2 <- ExtractAllele(set2(),AlleleAllp())$AllpMIDdallele
  t2 = rbind(as.data.frame(table(av2$vallele)),as.data.frame(table(aj2$jallele)), as.data.frame(table(ad2$dallele)) )
  colnames(t2) = c('Gene_Name','Proportion.set2')
  df <- merge(t1, t2, all = TRUE)
  df[is.na(df)] <- 0
  df <- df[which(df[,1] != ""), ]})

  NdivexpAlleletable <- reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
  if (input$Type_AnalysisAllele=="Yes"){df<-NdivexpAllele()[which(NdivexpAllele()$Proportion.set1>=5 & NdivexpAllele()$Proportion.set2>=5),]} else if (input$Type_AnalysisAllele=="No"){df <- NdivexpAllele()}})

  DivExpallele <- reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
  if (input$TypeClono=="diversity"){vall <- sigrepDiv(NdivexpAlleletable(),set1(),set2())} else if(input$TypeClono=="expression") {vall <- sigrepExp(NdivexpAlleletable(),set1(),set2())}
  names(vall)[1] <- 'Allele_Name'
  names(vall)[2] <- 'Allele_Type1'
  vall$Allele_Type <- gsub("gene", "allele", vall$Allele_Type1)
  vall <- vall[,c(1,22,3:21)]})

  DivExpalleleGraph <- reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    if (input$TypeClono=="diversity"){vall <- sigrepDiv(NdivexpAlleletable(),set1(),set2())} else if(input$TypeClono=="expression") {vall <- sigrepExp(NdivexpAlleletable(),set1(),set2())}
    names(vall)[1] <- 'Allele_Name1'
    names(vall)[2] <- 'Allele_Type1'
    vall$Allele_Type <- gsub("gene", "allele", vall$Allele_Type1)
    vall$Allele_Name <-  apply(as.matrix(vall$Allele_Name1),1,function(m){
      ifelse (grepl(" or ", m)==FALSE,
              {ifelse(input$Type_allele=="Several alleles",l <- paste(unlist(strsplit(m," "))[2:3],collapse  = " "), l <- m)},{
                mm<-as.data.frame((matrix(unlist(strsplit(unlist(strsplit(unlist(strsplit(gsub(",","",m)," or "))," ")),"\\*")), ncol=4,byrow = TRUE))[,-1])
                mm$C = paste("*",mm[,2], mm[,3], sep="")
                mm <- mm[,-c(2,3)]
                m1 <- unique(mm[,1])
                l <- paste(unlist(lapply(1:length(m1),function(i){gsub("[[:blank:]]","",
                                                                       ifelse (length(mm[mm[,1]==m1[i],i])==1,
                                                                               paste(m1[i], paste (mm[mm[,1]==m1[i],2],collapse = ",")),
                                                                               paste(m1[i],"{", paste (mm[mm[,1]==m1[i],2],collapse = ","),"}")))})),collapse=",")})
      return(l)})
    vall <- vall[,c(23,22,3:21)]})

  divExclAllele <- reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
  divexpExcl <-  ExcludeDivExp(NdivexpAllele(),set1(),set2())
  names(divexpExcl)[1] <- 'Allele_Name'
  names(divexpExcl)[2] <- 'Allele_Type1'
  divexpExcl$Allele_Type <- gsub("gene", "allele", divexpExcl$Allele_Type1)
  divexpExcl <- divexpExcl[,c(1,9,3:8)]
  ifelse(nrow(divexpExcl[which(divexpExcl[,3]<5 | divexpExcl[,6]<5),])!=0,divexpExcl <-divexpExcl[which(divexpExcl[,3]<5 | divexpExcl[,6]<5),] ,{divexpExcl <-cbind("No alleles","","","","","","","")
  colnames(divexpExcl) <- c("Allele_Name", "Allele_Type", "Nb_IMGT_clonotype_AA.set1","Proportion.set1","Normalized_proportion.set1", "Nb_IMGT_clonotype_AA.set2","Proportion.set2","Normalized_proportion.set2")})
  divexpExcl})

  output$testresultsallele <- renderDataTable({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating table... Please wait.", value = 0)
    DisplayResultsTable(DivExpallele())})

  output$testresultsalleleExcluded <- renderDataTable({
    datatable(divExclAllele(),filter='top',options = list(columnDefs = list(list(width = '180px', targets = "_all")),lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
                                                   pageLength = 5, autoWidth = FALSE, orderClasses = TRUE,searchHighlight = TRUE))})

  observeEvent(input$hide4,{toggle("testresultsalleleExcluded")})

  output$MTPgphresults <- renderDataTable({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating table... Please wait.", value = 0)
    if(input$TypeClono=="diversity") {DisplayResultsTablelog10(MTPresultsLogDec(div()))} else {DisplayResultsTablelog10(MTPresultsLogDec(exp()))} })

 output$MTPgphresultsAllele <- renderDataTable({
   progress = shiny::Progress$new()
   on.exit(progress$close())
   progress$set(message = "Creating table... Please wait.", value = 0)
   DisplayResultsTablelog10(MTPresultsLogDecAllele(DivExpallele()))})

 output$downloadDataLog <- downloadHandler(
    filename = function() {
      paste(input$TypeClono,"-Test_results_Log-dec-Genes",'.csv', sep="")
    },
    content = function(file) {
      data1<-MTPresultsLogDec(div())
      data2 <- MTPresultsLogDec(exp())
      colnames(data1)<-c("Gene_Name","z","Neglog10rawp","Neglog10Bonferroni","Neglog10Holm","Neglog10Hochberg","Neglog10SidakSS","Neglog10SidakSD","Neglog10BH","Neglog10BY","Test_interpretation")
      colnames(data2)<-c("Gene_Name","z","Neglog10rawp","Neglog10Bonferroni","Neglog10Holm","Neglog10Hochberg","Neglog10SidakSS","Neglog10SidakSD","Neglog10BH","Neglog10BY","Test_interpretation")
      if (input$TypeClono=="diversity"){
        write.table( data1, file, sep = ";",  row.names = FALSE, dec = ",")} else if (input$TypeClono=="expression"){
        write.table( data2, file, sep = ";",  row.names = FALSE, dec = ",")}})


 output$downloadDataLogAllele<- downloadHandler(
   filename = function() {
     paste(input$TypeClono,"-Test_results_Log-dec-Alleles",'.csv', sep="")
   },
   content = function(file) {
     data<-MTPresultsLogDecAllele(DivExpallele())
     colnames(data)<-c("Allele_Name","z","Neglog10rawp","Neglog10Bonferroni","Neglog10Holm","Neglog10Hochberg","Neglog10SidakSS","Neglog10SidakSD","Neglog10BH","Neglog10BY","Test_interpretation")
     write.table( data, file, sep = ";",  row.names = FALSE, dec = ",")})


  output$downloadData <- downloadHandler(
    filename = function() {
        paste(input$TypeClono,"-Test_results-",'.csv', sep="")},
    content = function(file) {
      if (input$TypeClono=="diversity"){
        write.table( cbind(div()[,1:2], div()[,input$show_vars,drop=FALSE]), file, sep = ";",  row.names = FALSE, dec = ",")} else if (input$TypeClono=="expression"){
        write.table( cbind(exp()[,1:2], exp()[,input$show_vars,drop=FALSE]), file, sep = ";",  row.names = FALSE, dec = ",")}})

  output$downloadDataAllele <- downloadHandler(
    filename = function() {
      paste(input$Type_allele,input$TypeClono,"-Test_results-",'.csv', sep="")},
    content = function(file) {
        write.table(cbind(DivExpallele()[,1:2],DivExpallele()[,input$show_vars,drop=FALSE]), file, sep = ";",  row.names = FALSE, dec = ",")})
  ##############################################################
  ###### resizing multiple testing procedure plot for Shiny Display (resolution=300, height=8cm (3.14 in), width=17cm (6.7 in))
  lineGraphShinyDisplay<-function(data,...){
    data <- data[,c(1,13:20)]
    data<-melt(data, id=c(names(data)[1]))
    x = seq(0, 1, by=0.01)
    freqcum= cut(data$value, x, right=FALSE,include.lowest =TRUE)
    freqcum = table(freqcum, data$variable)
    cumfreq0 = apply(freqcum,2,cumsum)
    df <- rbind(0,cumfreq0)
    df <- data.frame(df)
    fl1 <- list(family = "Arial",size = 12,color = "#000000") #Font of the legend
    l1 <- list(bordercolor = "#000000", borderwidth = 1,font = fl1) #Legend boder and font
    f1 <- list(family = "Arial",size = 16, color = "#000000")
    ax <- list( zeroline = F, showline = T, mirror = "ticks",dtick = 0.1,
                title = "Type I error rate",titlefont=f1,linecolor = toRGB("black"), linewidth = 1)#Font of the legend of the axis titles
    ay <- list( zeroline = F, showline = T, mirror = "ticks", dtick = 10,title = "Number of rejected hypotheses",titlefont=f1,linecolor = toRGB("black"),linewidth = 1)
    plot_ly(x = x, y = df$rawp, line = list(color = "#000000", dash = "dot"), name = "rawp") %>%
      add_trace(x = x,y = df$Bonferroni, name = "Bonferroni",line = list(color = "#B200FF") )%>%
      add_trace(x = x,y = df$Holm, name = "Holm",line = list(color = "#00cd00")) %>%
      add_trace(x = x,y = df$Hochberg, name = "Hochberg",line = list(color = "#0000ff")) %>%
      add_trace(x = x,y = df$SidakSS, name = "SidakSS",line = list(color = "#00ffff")) %>%
      add_trace(x = x,y = df$SidakSD, name = "SidakSD",line = list(color = "#ff00ff")) %>%
      add_trace(x = x,y = df$BH, name = "BH",line = list(color = "#ff0000")) %>%
      add_trace(x = x,y = df$BY, name = "BY",line = list(color = "#FFBA00"))%>%
      layout(xaxis = ax, yaxis = ay,legend = l1, shapes = list(
        list(type = "line",
             line = list(color = "#0000ff", dash = "dot",width =0.75),
             x0 =0.05, x1 =0.05, xref = "x",
             y0 = 0, y1 = max(df$rawp), yref = "y")))
  }

  scatterPlotShinyDisplay<-function(data,...){
    names(data)[2:11]<-c("z","rawp","Bonferroni","Holm","Hochberg","SidakSS","SidakSD","BH","BY","Test_interpretation")
    data<-melt(data, id=c(names(data)[1],"z", "Test_interpretation"))
    f1 <- list(family = "Arial",size = 16,color = "#000000") #Font of the legend of the axis titles
    fl <- list( family = "Arial", size = 12,color = "#000000") #Font of the legend
    l <- list(bordercolor = "#000000",borderwidth = 1,font = fl) #Legend boder and font
    ax1 <- list(zeroline = T, showline = T, mirror = "ticks", dtick = 0.5,title = "z-scores", titlefont=f1,
                ticklen=1, linecolor = toRGB("black"), linewidth = 0.75) #x-axis parameters of the scatter plot
    ay1 <- list(zeroline = T, showline = T, mirror = "ticks", title = "-log(adjusted p-values, 10)",
                titlefont=f1, ticklen=1,linecolor = toRGB("black"),  linewidth = 0.75) #y-axis parameters of the scatter plot
    cols <- c("rawp"=1,"Bonferroni"="#B200FF","Holm"=3,"Hochberg"=4,"SidakSS"=5,"SidakSD"=6,"BH"=10,"BY"="#FFBA00")
    p<-ggplot(data, aes(x=z, y=value, colour=variable, text = paste(data[,1],': ',variable,' (x:',format(round(z, 2), nsmall = 2),', y: ',format(round(value, 2), nsmall = 2),')', sep=""))) +
      theme_bw() + geom_point() +
      theme(legend.title=element_blank())+
      geom_hline(yintercept=1.3,linetype = 2, color=4, size=0.25)+
      geom_vline(xintercept=1.96,linetype = 2, color=4, size=0.25)+
      geom_vline(xintercept=-1.96,linetype = 2, color=4, size=0.25)+
      scale_colour_manual(values=cols)
    ggplotly(p, tooltip = "text")%>%
    layout(xaxis = ax1, yaxis = ay1, legend = l)
  }

  output$LineGraphShinyDisplay <- renderPlotly({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating figure... Please wait.", value = 0)
    if (input$TypeClono=="diversity"){lineGraphShinyDisplay(div())} else if (input$TypeClono=="expression"){lineGraphShinyDisplay(exp())}
                                     })

  output$ScatterPlotShinyDisplay <- renderPlotly({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating figure... Please wait.", value = 0)
    if (input$TypeClono=="diversity"){scatterPlotShinyDisplay(MTPresultsLogDec(div()))} else if (input$TypeClono=="expression"){scatterPlotShinyDisplay(MTPresultsLogDec(exp()))}
                                     })

  output$LineGraphShinyDisplayAllele <- renderPlotly({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating figure... Please wait.", value = 0)
    lineGraphShinyDisplay(DivExpallele())
                                     })

  output$ScatterPlotShinyDisplayAllele <- renderPlotly({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating figure... Please wait.", value = 0)
    df<-MTPresultsLogDecAllele(DivExpallele())
    scatterPlotShinyDisplay(df)
                                    })
  output$TitleGene<-renderText({input$titleGphMTP})
  output$TitleAllele<-renderText({input$titleGphMTPallele })
################################################
############ Displayed synthesis graph in the shiny application (larger font size)

  normjuxBarsShinyDisp<-function(data,...){
    dataV <- data[which(data$Gene_Type=="V gene"),]
    data1V=melt(dataV[c(1,2,5,8)], id.vars = c("Gene_Name", "Gene_Type"))
    pBV<-with(data1V, ggplot(data=data1V) +theme_grey()+
                geom_bar(aes(x=Gene_Name,y =value,fill =factor(variable, levels = rev(levels(variable)))), position="dodge",stat = "identity", colour="black",show.legend=FALSE)+
                geom_bar(aes(x=Gene_Name,y =value,fill =factor(variable, levels = rev(levels(variable)))), position="dodge",stat = "identity")+
                coord_flip() +xlab("V genes")+ylab("Normalized proportions")+
                scale_x_discrete(limits= rev(factor(factor(dataV$Gene_Name),levels=levels(dataV$Gene_Name))))+
                theme(
                  panel.grid.major = element_line(size = 0.75),
                  panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                  legend.position="bottom",
                  plot.title=element_text( face="bold", size=30),
                  strip.text.x = element_text(size=18, colour="black"),
                  axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                  axis.text.x=element_text(size = 12, colour="black"),
                  strip.text.y = element_text(size=14, face="bold", colour="black"),
                  axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                  axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                  strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid"),
                  legend.background = element_rect(colour = "black"),
                  legend.title = element_text(size=14, face="bold"),
                  legend.text = element_text(size = 14, face = "bold",vjust=1.5),
                  legend.key.size = unit(0.75, "cm"))+
                guides(fill=guide_legend(title = "Compared sets: ",nrow=2,keywidth =2.5, keyheight = 1.5,reverse = TRUE)))

    dataJ <- data[which(data$Gene_Type=="J gene"),]
    data1J=melt(dataJ[c(1,2,5,8)], id.vars = c("Gene_Name", "Gene_Type"))
    pBJ<-with(data1J, ggplot(data=data1J) +theme_grey()+
                geom_bar(aes(x=Gene_Name,y =value,fill =factor(variable, levels = rev(levels(variable)))), position="dodge",stat = "identity", colour="black",show.legend=FALSE)+
                geom_bar(aes(x=Gene_Name,y =value,fill =factor(variable, levels = rev(levels(variable)))), position="dodge",stat = "identity")+
                coord_flip() +xlab("J genes")+ylab("Normalized proportions")+
                scale_x_discrete(limits= rev(factor(factor(dataJ$Gene_Name),levels=levels(dataJ$Gene_Name))))+
                theme(
                  panel.grid.major = element_line(size = 0.75),
                  panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                  legend.position="bottom",
                  plot.title=element_text( face="bold", size=30),
                  strip.text.x = element_text(size=18, colour="black"),
                  axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                  axis.text.x=element_text(size = 12, colour="black"),
                  strip.text.y = element_text(size=14, face="bold", colour="black"),
                  axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                  axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                  strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid"),
                  legend.background = element_rect(colour = "black"),
                  legend.title = element_text(size=14, face="bold"),
                  legend.text = element_text(size = 14, face = "bold",vjust=1.5),
                  legend.key.size = unit(0.75, "cm"))+
                guides(fill=guide_legend(title = "Compared sets: ",nrow=2,keywidth =2.5, keyheight = 1.5,reverse = TRUE)))
    dataD <- data[which(data$Gene_Type=="D gene"),]
    data1D=melt(dataD[c(1,2,5,8)], id.vars = c("Gene_Name", "Gene_Type"))
    pBD<-with(data1D, ggplot(data=data1D) +theme_grey()+
                geom_bar(aes(x=Gene_Name,y =value,fill =factor(variable, levels = rev(levels(variable)))), position="dodge",stat = "identity", colour="black",show.legend=FALSE)+
                geom_bar(aes(x=Gene_Name,y =value,fill =factor(variable, levels = rev(levels(variable)))), position="dodge",stat = "identity")+
                coord_flip() +xlab("D genes")+ylab("Normalized proportions")+
                scale_x_discrete(limits= rev(factor(factor(dataD$Gene_Name),levels=levels(dataD$Gene_Name))))+
                theme(
                  panel.grid.major = element_line(size = 0.75),
                  panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                  legend.position="bottom",
                  plot.title=element_text( face="bold", size=30),
                  strip.text.x = element_text(size=18, colour="black"),
                  axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                  axis.text.x=element_text(size = 12, colour="black"),
                  strip.text.y = element_text(size=14, face="bold", colour="black"),
                  axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                  axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                  strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid"),
                  legend.background = element_rect(colour = "black"),
                  legend.title = element_text(size=14, face="bold"),
                  legend.text = element_text(size = 14, face = "bold",vjust=1.5),
                  legend.key.size = unit(0.75, "cm"))+
                guides(fill=guide_legend(title = "Compared sets: ",nrow=2,keywidth =2.5, keyheight = 1.5,reverse = TRUE)))
    list(BarGphV=pBV,BarGphD=pBD,BarGphJ=pBJ)}


  normjuxBarsAlleleShinyDisp<-function(data,...){
    dataV <- data[which(data$Allele_Type=="V allele"),]
    data1V=melt(dataV[c(1,2,5,8)], id.vars = c("Allele_Name", "Allele_Type"))
    pBV<-with(data1V, ggplot(data=data1V) +theme_grey()+
                geom_bar(aes(x=Allele_Name,y =value,fill =factor(variable, levels = rev(levels(variable)))), position="dodge",stat = "identity", colour="black",show.legend=FALSE)+
                geom_bar(aes(x=Allele_Name,y =value,fill =factor(variable, levels = rev(levels(variable)))), position="dodge",stat = "identity")+
                coord_flip() +xlab("V alleles")+ylab("Normalized proportions")+
                scale_x_discrete(limits= rev(factor(as.factor(dataV$Allele_Name),levels=levels(as.factor(dataV$Allele_Name)))))+
                theme(
                  panel.grid.major = element_line(size = 0.75),
                  panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                  legend.position="bottom",
                  plot.title=element_text( face="bold", size=30),
                  strip.text.x = element_text(size=18, colour="black"),
                  axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                  axis.text.x=element_text(size = 12, colour="black"),
                  strip.text.y = element_text(size=14, face="bold", colour="black"),
                  axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                  axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                  strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid"),
                  legend.background = element_rect(colour = "black"),
                  legend.title = element_text(size=14, face="bold"),
                  legend.text = element_text(size = 14, face = "bold",vjust=1.5),
                  legend.key.size = unit(0.75, "cm"))+
                guides(fill=guide_legend(title = "Compared sets: ",nrow=2,keywidth =2.5, keyheight = 1.5,reverse = TRUE)))
    dataJ <- data[which(data$Allele_Type=="J allele"),]
    data1J=melt(dataJ[c(1,2,5,8)], id.vars = c("Allele_Name", "Allele_Type"))
    pBJ<-with(data1J, ggplot(data=data1J) +theme_grey()+
                geom_bar(aes(x=Allele_Name,y =value,fill =factor(variable, levels = rev(levels(variable)))), position="dodge",stat = "identity", colour="black",show.legend=FALSE)+
                geom_bar(aes(x=Allele_Name,y =value,fill =factor(variable, levels = rev(levels(variable)))), position="dodge",stat = "identity")+
                coord_flip() +xlab("J alleles")+ylab("Normalized proportions")+
                scale_x_discrete(limits= rev(factor(as.factor(dataJ$Allele_Name),levels=levels(as.factor(dataJ$Allele_Name)))))+
                theme(
                  panel.grid.major = element_line(size = 0.75),
                  panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                  legend.position="bottom",
                  plot.title=element_text( face="bold", size=30),
                  strip.text.x = element_text(size=18, colour="black"),
                  axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                  axis.text.x=element_text(size = 12, colour="black"),
                  strip.text.y = element_text(size=14, face="bold", colour="black"),
                  axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                  axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                  strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid"),
                  legend.background = element_rect(colour = "black"),
                  legend.title = element_text(size=14, face="bold"),
                  legend.text = element_text(size = 14, face = "bold",vjust=1.5),
                  legend.key.size = unit(0.75, "cm"))+
                guides(fill=guide_legend(title = "Compared sets: ",nrow=2,keywidth =2.5, keyheight = 1.5,reverse = TRUE)))
    dataD <- data[which(data$Allele_Type=="D allele"),]
    data1D=melt(dataD[c(1,2,5,8)], id.vars = c("Allele_Name", "Allele_Type"))
    pBD<-with(data1D, ggplot(data=data1D) +theme_grey()+
                geom_bar(aes(x=Allele_Name,y =value,fill =factor(variable, levels = rev(levels(variable)))), position="dodge",stat = "identity", colour="black",show.legend=FALSE)+
                geom_bar(aes(x=Allele_Name,y =value,fill =factor(variable, levels = rev(levels(variable)))), position="dodge",stat = "identity")+
                coord_flip() +xlab("D alleles")+ylab("Normalized proportions")+
                scale_x_discrete(limits= rev(factor(as.factor(dataD$Allele_Name),levels=levels(as.factor(dataD$Allele_Name)))))+
                theme(
                  panel.grid.major = element_line(size = 0.75),
                  panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                  legend.position="bottom",
                  plot.title=element_text( face="bold", size=30),
                  strip.text.x = element_text(size=18, colour="black"),
                  axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                  axis.text.x=element_text(size = 12, colour="black"),
                  strip.text.y = element_text(size=14, face="bold", colour="black"),
                  axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                  axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                  strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid"),
                  legend.background = element_rect(colour = "black"),
                  legend.title = element_text(size=14, face="bold"),
                  legend.text = element_text(size = 14, face = "bold",vjust=1.5),
                  legend.key.size = unit(0.75, "cm"))+
                guides(fill=guide_legend(title = "Compared sets: ",nrow=2,keywidth =2.5, keyheight = 1.5,reverse = TRUE)))
    list(BarGphV=pBV,BarGphD=pBD,BarGphJ=pBJ)}


  diffpropGphShinyDisp<-function(data,...){
    colors=c("Null difference in proportions  "="#FFFFFF", "Non-significant (rawp)  "="#E40000", "Significant (rawp)  "= "cyan","Significant (All_p)  "="#0026FF", "Significant (Min_2p)  "="#FF00DC","Significant (Only_BH)  "= "green3")

    pbrut <-with(data, ggplot(data,aes(x=factor(Gene_Name, levels=rev(factor(Gene_Name))),y =Difference_proportion))+
                   geom_errorbar(aes(col = Test_interpretation, ymin =Lower_bound_IC_diff_prop,ymax =Upper_bound_IC_diff_prop), cex=0.75, width=0.6)+ theme_grey()+coord_flip()+
                   geom_point(aes(shape = Test_interpretation), size = 1) +ylim( round(min(data$Lower_bound_IC_diff_prop)-0.01,2),  round(max(data$Upper_bound_IC_diff_prop)+0.01,2)) +
                   geom_hline(aes(yintercept = 0)) +
                   theme(
                     panel.grid.major = element_line(size = 0.75),
                     panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                     legend.position="bottom",
                     plot.title=element_text( face="bold", size=30),
                     strip.text.x = element_text(size=18, colour="black"),
                     axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                     axis.text.x=element_text(size = 12, colour="black"),
                     strip.text.y = element_text(size=14, face="bold", colour="black"),
                     axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                     axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                     strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid"),
                     legend.background = element_rect(colour = "black"),
                     legend.title = element_text(size=14, face="bold"),
                     legend.text = element_text(size = 14, face = "bold",vjust=1.5),
                     legend.key.size = unit(0.85, "cm"))+
                     scale_color_manual(name="Test interpretation: ",
                                        values=colors,
                                        breaks=c("Null difference in proportions  ", "Non-significant (rawp)  ", "Significant (rawp)  ", "Significant (All_p)  ","Significant (Min_2p)  ", "Significant (Only_BH)  "))+
                    scale_shape_manual(name="Test interpretation: ",values=c(19,19,19,19,19,19),
                                      breaks=c("Null difference in proportions  ","Non-significant (rawp)  ",  "Significant (rawp)  ","Significant (All_p)  ","Significant (Min_2p)  ","Significant (Only_BH)  ")))

    Datav <- data[which(data$Gene_Type=="V gene"),]

    pv <- with(Datav,ggplot(Datav,aes(x=factor(Gene_Name, levels=rev(factor(Gene_Name))), y =Difference_proportion))+
                 geom_errorbar(aes(col = Test_interpretation, ymin =Lower_bound_IC_diff_prop, ymax =Upper_bound_IC_diff_prop), cex=0.75, width=0.6)+ theme_grey()+coord_flip()+
                 geom_point(aes(shape = Test_interpretation), size = 1) +
                 ylab("Difference in proportions & 95% CI")+
                 ylim( round(min(data$Lower_bound_IC_diff_prop)-0.01,2),  round(max(data$Upper_bound_IC_diff_prop)+0.01,2)) +
                 geom_hline(aes(yintercept = 0)) + xlab("V genes")+
                 theme(
                   panel.grid.major = element_line(size = 0.75),
                   panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                   legend.position="bottom",
                   plot.title=element_text( face="bold", size=30),
                   strip.text.x = element_text(size=18, colour="black"),
                   axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                   axis.text.x=element_text(size = 12, colour="black"),
                   strip.text.y = element_text(size=14, face="bold", colour="black"),
                   axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                   axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                   strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid") )+
                 scale_color_manual(name="Test interpretation: ",
                                    values=colors,
                                    breaks=c("Null difference in proportions  ","Non-significant (rawp)  ", "Significant (rawp)  ", "Significant (All_p)  ", "Significant (Min_2p)  ","Significant (Only_BH)  "))+
                 scale_shape_manual(name="Test interpretation: ",values=c(19,19,19,19,19,19),
                                    breaks=c("Null difference in proportions  ","Non-significant (rawp)  ",  "Significant (rawp)  ","Significant (All_p)  ", "Significant (Min_2p)  ", "Significant (Only_BH)  ")))

    Dataj <- data[which(data$Gene_Type=="J gene"),]

    pj <- with(Dataj,ggplot(Dataj,aes(x=factor(Gene_Name, levels=rev(factor(Gene_Name))),
                                      y =Difference_proportion))+
                 geom_errorbar(aes(col = Test_interpretation, ymin =Lower_bound_IC_diff_prop,
                                   ymax =Upper_bound_IC_diff_prop), cex=0.75, width=0.6)+ theme_grey()+coord_flip()+
                 geom_point(aes(shape = Test_interpretation), size = 1) + ylab("Difference in proportions & 95% CI")+
                 ylim( round(min(data$Lower_bound_IC_diff_prop)-0.01,2),  round(max(data$Upper_bound_IC_diff_prop)+0.01,2)) +
                 geom_hline(aes(yintercept = 0)) + xlab("J genes")+
                 theme(
                   panel.grid.major = element_line(size = 0.75),
                   panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                   legend.position="bottom",
                   plot.title=element_text( face="bold", size=30),
                   strip.text.x = element_text(size=18, colour="black"),
                   axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                   axis.text.x=element_text(size = 12, colour="black"),
                   strip.text.y = element_text(size=14, face="bold", colour="black"),
                   axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                   axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                   strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid") )+
                 scale_color_manual(name="Test interpretation: ",
                                    values=colors,
                                    breaks=c("Null difference in proportions  ","Non-significant (rawp)  ",  "Significant (rawp)  ", "Significant (All_p)  ","Significant (Min_2p)  ","Significant (Only_BH)  "))+
                 scale_shape_manual(name="Test interpretation: ",values=c(19,19,19,19,19,19),
                                    breaks=c("Null difference in proportions  ","Non-significant (rawp)  ",  "Significant (rawp)  ", "Significant (All_p)  ", "Significant (Min_2p)  ", "Significant (Only_BH)  ")))

    Datad <- data[which(data$Gene_Type=="D gene"),]

    pd <- with(Datad,ggplot(Datad,aes(x=factor(Gene_Name, levels=rev(factor(Gene_Name))),
                                      y =Difference_proportion))+
                 geom_errorbar(aes(col = Test_interpretation, ymin =Lower_bound_IC_diff_prop,
                                   ymax =Upper_bound_IC_diff_prop), cex=0.75, width=0.6)+ theme_grey()+coord_flip()+
                 geom_point(aes(shape = Test_interpretation), size = 1) + ylab("Difference in proportions & 95% CI")+
                 ylim( round(min(data$Lower_bound_IC_diff_prop)-0.01,2),  round(max(data$Upper_bound_IC_diff_prop)+0.01,2)) +
                 geom_hline(aes(yintercept = 0)) + xlab("D genes")+
                 theme(
                   panel.grid.major = element_line(size = 0.75),
                   panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                   legend.position="bottom",
                   plot.title=element_text( face="bold", size=30),
                   strip.text.x = element_text(size=18, colour="black"),
                   axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                   axis.text.x=element_text(size = 12, colour="black"),
                   strip.text.y = element_text(size=14, face="bold", colour="black"),
                   axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                   axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                   strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid") )+
                 scale_color_manual(name="Test interpretation: ",
                                    values=colors,
                                    breaks=c("Null difference in proportions  ","Non-significant (rawp)  ",  "Significant (rawp)  ", "Significant (All_p)  ","Significant (Min_2p)  ","Significant (Only_BH)  "))+
                 scale_shape_manual(name="Test interpretation: ",values=c(19,19,19,19,19,19),
                                    breaks=c("Null difference in proportions  ","Non-significant (rawp)  ",  "Significant (rawp)  ", "Significant (All_p)  ", "Significant (Min_2p)  ", "Significant (Only_BH)  ")))
    list(VJgenes=pbrut,Vgenes=pv,Dgenes=pd,Jgenes=pj)
  }



  diffpropGphAlleleShinyDisp<-function(data,...){
    colors=c("Null difference in proportions  "="#FFFFFF", "Non-significant (rawp)  "="#E40000", "Significant (rawp)  "= "cyan","Significant (All_p)  "="#0026FF", "Significant (Min_2p)  "="#FF00DC","Significant (Only_BH)  "= "green3")

    pbrut <-with(data, ggplot(data,aes(x=factor(Allele_Name, levels=rev(factor(Allele_Name))),y =Difference_proportion))+
                   geom_errorbar(aes(col = Test_interpretation, ymin =Lower_bound_IC_diff_prop, ymax =Upper_bound_IC_diff_prop), cex=0.75, width=0.6)+ theme_grey()+coord_flip()+
                   geom_point(aes(shape = Test_interpretation), size = 1) +ylim( round(min(data$Lower_bound_IC_diff_prop)-0.01,2),  round(max(data$Upper_bound_IC_diff_prop)+0.01,2)) +
                   geom_hline(aes(yintercept = 0)) +
                   theme(
                     panel.grid.major = element_line(size = 0.75),
                     panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                     legend.position="bottom",
                     plot.title=element_text( face="bold", size=30),
                     strip.text.x = element_text(size=18, colour="black"),
                     axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                     axis.text.x=element_text(size = 12, colour="black"),
                     strip.text.y = element_text(size=14, face="bold", colour="black"),
                     axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                     axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                     strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid"),
                     legend.background = element_rect(colour = "black"),
                     legend.title = element_text(size=14, face="bold"),
                     legend.text = element_text(size = 14, face = "bold",vjust=1.5),
                     legend.key.size = unit(0.85, "cm"))+
                   scale_color_manual(name="Test interpretation: ",
                                      values=colors,
                                      breaks=c("Null difference in proportions  ",
                                               "Non-significant (rawp)  ",
                                               "Significant (rawp)  ",
                                               "Significant (All_p)  ",
                                               "Significant (Min_2p)  ",
                                               "Significant (Only_BH)  "))+
                   scale_shape_manual(name="Test interpretation: ",values=c(19,19,19,19,19,19),
                                      breaks=c("Null difference in proportions  ","Non-significant (rawp)  ",  "Significant (rawp)  ",
                                               "Significant (All_p)  ",
                                               "Significant (Min_2p)  ",
                                               "Significant (Only_BH)  ")))

    Datav <- data[which(data$Allele_Type=="V allele"),]

    pv <- with(Datav,ggplot(Datav,aes(x=factor(Allele_Name, levels=rev(factor(Allele_Name))), y =Difference_proportion))+
                 geom_errorbar(aes(col = Test_interpretation, ymin =Lower_bound_IC_diff_prop, ymax =Upper_bound_IC_diff_prop), cex=0.75, width=0.6)+ theme_grey()+coord_flip()+
                 geom_point(aes(shape = Test_interpretation), size = 1) +
                 ylab("Difference in proportions & 95% CI")+
                 ylim( round(min(data$Lower_bound_IC_diff_prop)-0.01,2),  round(max(data$Upper_bound_IC_diff_prop)+0.01,2)) +
                 geom_hline(aes(yintercept = 0)) + xlab("V genes")+
                 theme(
                   panel.grid.major = element_line(size = 0.75),
                   panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                   legend.position="bottom",
                   plot.title=element_text( face="bold", size=30),
                   strip.text.x = element_text(size=18, colour="black"),
                   axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                   axis.text.x=element_text(size = 12, colour="black"),
                   strip.text.y = element_text(size=14, face="bold", colour="black"),
                   axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                   axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                   strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid"))+
                 scale_color_manual(name="Test interpretation: ",
                                    values=colors,
                                    breaks=c("Null difference in proportions  ","Non-significant (rawp)  ", "Significant (rawp)  ", "Significant (All_p)  ",
                                             "Significant (Min_2p)  ","Significant (Only_BH)  "))+
                 scale_shape_manual(name="Test interpretation: ",values=c(19,19,19,19,19,19),
                                    breaks=c("Null difference in proportions  ","Non-significant (rawp)  ",  "Significant (rawp)  ",
                                             "Significant (All_p)  ", "Significant (Min_2p)  ", "Significant (Only_BH)  ")))
    Dataj <- data[which(data$Allele_Type=="J allele"),]

    pj <- with(Dataj,ggplot(Dataj,aes(x=factor(Allele_Name, levels=rev(factor(Allele_Name))),
                                      y =Difference_proportion))+
                 geom_errorbar(aes(col = Test_interpretation, ymin =Lower_bound_IC_diff_prop,
                                   ymax =Upper_bound_IC_diff_prop), cex=0.75, width=0.6)+ theme_grey()+coord_flip()+
                 geom_point(aes(shape = Test_interpretation), size = 1) + ylab("Difference in proportions & 95% CI")+
                 ylim( round(min(data$Lower_bound_IC_diff_prop)-0.01,2),  round(max(data$Upper_bound_IC_diff_prop)+0.01,2)) +
                 geom_hline(aes(yintercept = 0)) + xlab("J alleles")+
                 theme(
                   panel.grid.major = element_line(size = 0.75),
                   panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                   legend.position="bottom",
                   plot.title=element_text( face="bold", size=30),
                   strip.text.x = element_text(size=18, colour="black"),
                   axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                   axis.text.x=element_text(size = 12, colour="black"),
                   strip.text.y = element_text(size=14, face="bold", colour="black"),
                   axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                   axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                   strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid"))+
                 scale_color_manual(name="Test interpretation: ",
                                    values=colors,
                                    breaks=c("Null difference in proportions  ","Non-significant (rawp)  ",  "Significant (rawp)  ",
                                             "Significant (All_p)  ","Significant (Min_2p)  ","Significant (Only_BH)  "))+
                 scale_shape_manual(name="Test interpretation: ",values=c(19,19,19,19,19,19),
                                    breaks=c("Null difference in proportions  ","Non-significant (rawp)  ",  "Significant (rawp)  ",
                                             "Significant (All_p)  ", "Significant (Min_2p)  ", "Significant (Only_BH)  "))
               )

    Datad <- data[which(data$Allele_Type=="D allele"),]

    pd <- with(Datad,ggplot(Datad,aes(x=factor(Allele_Name, levels=rev(factor(Allele_Name))),y =Difference_proportion))+
                 geom_errorbar(aes(col = Test_interpretation, ymin =Lower_bound_IC_diff_prop,
                                   ymax =Upper_bound_IC_diff_prop), cex=0.75, width=0.6)+ theme_grey()+coord_flip()+
                 geom_point(aes(shape = Test_interpretation), size = 1) + ylab("Difference in proportions & 95% CI")+
                 ylim( round(min(data$Lower_bound_IC_diff_prop)-0.01,2),  round(max(data$Upper_bound_IC_diff_prop)+0.01,2)) +
                 geom_hline(aes(yintercept = 0)) + xlab("D alleles")+
                 theme(
                   panel.grid.major = element_line(size = 0.75),
                   panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
                   legend.position="bottom",
                   plot.title=element_text( face="bold", size=30),
                   strip.text.x = element_text(size=18, colour="black"),
                   axis.title.x = element_text(size = 14,face="bold", colour="black",vjust=-0.5),
                   axis.text.x=element_text(size = 12, colour="black"),
                   strip.text.y = element_text(size=14, face="bold", colour="black"),
                   axis.title.y = element_text(size = 18,face="bold", colour="black", vjust=1.5),
                   axis.text.y=element_text( size = 14,hjust=0, colour="black"),
                   strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid"))+
                 scale_color_manual(name="Test interpretation: ",
                                    values=colors,
                                    breaks=c("Null difference in proportions  ","Non-significant (rawp)  ",  "Significant (rawp)  ",
                                             "Significant (All_p)  ","Significant (Min_2p)  ","Significant (Only_BH)  "))+
                 scale_shape_manual(name="Test interpretation: ",values=c(19,19,19,19,19,19),
                                    breaks=c("Null difference in proportions  ","Non-significant (rawp)  ",  "Significant (rawp)  ",
                                             "Significant (All_p)  ", "Significant (Min_2p)  ", "Significant (Only_BH)  ")))

   list(VJgenes=pbrut,Vgenes=pv,Dgenes=pd,Jgenes=pj)}
############################################################################

  SynthesisGphr <- reactive({
   progress = shiny::Progress$new()
   on.exit(progress$close())
   progress$set(message = "Creating figure... Please wait.", value = 0)
    if (input$TypeClono=="diversity" && input$Gene_Type== "V genes"){
     grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=2), just="top"), heights = unit(c(2,input$height,2.5,3), "cm"),
                 arrangeGrob(((normjuxBarsShinyDisp(div())$BarGphV)+ xlab(paste(input$locus,"V genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                  ((diffpropGphShinyDisp(div())$Vgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = unit(c(input$width,(input$width)-6), "cm")),
                 arrangeGrob(g_legend(normjuxBarsShinyDisp(div())$BarGphV+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                 arrangeGrob(g_legend(diffpropGphShinyDisp(div())$VJgenes), nrow=1),nrow=4)}

    if (input$TypeClono=="diversity" && input$Gene_Type== "J genes"){
     grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=2), just="top"), heights = unit(c(2,input$height,2.5,3), "cm"),
                             arrangeGrob(((normjuxBarsShinyDisp(div())$BarGphJ)+ xlab(paste(input$locus,"J genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                               ((diffpropGphShinyDisp(div())$Jgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1,  widths = unit(c(input$width,(input$width)-6), "cm")),
                             arrangeGrob(g_legend(normjuxBarsShinyDisp(div())$BarGphJ+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.200, 0.16),nrow=1),
                             arrangeGrob(g_legend(diffpropGphShinyDisp(div())$VJgenes), nrow=1),nrow=4)}

   if (input$TypeClono=="diversity" && input$Gene_Type== "D genes"){
     grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=2), just="top"), heights = unit(c(2,input$height,2.5,3), "cm"),
                  arrangeGrob(((normjuxBarsShinyDisp(div())$BarGphD)+ xlab(paste(input$locus,"D genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                              ((diffpropGphShinyDisp(div())$Dgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1,  widths = unit(c(input$width,(input$width)-6), "cm")),
                  arrangeGrob(g_legend(normjuxBarsShinyDisp(div())$BarGphD+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.200, 0.16),nrow=1),
                  arrangeGrob(g_legend(diffpropGphShinyDisp(div())$VJgenes), nrow=1), nrow=4)}

    if (input$TypeClono=="expression" && input$Gene_Type== "V genes"){
     grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=2), just="top"), heights = unit(c(2,input$height,2.5,3), "cm"),
                             arrangeGrob(((normjuxBarsShinyDisp(exp())$BarGphV)+ xlab(paste(input$locus,"V genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                               ((diffpropGphShinyDisp(exp())$Vgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = unit(c(input$width,(input$width)-6), "cm")),
                             arrangeGrob(g_legend(normjuxBarsShinyDisp(exp())$BarGphV+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.200, 0.16),nrow=1),
                             arrangeGrob(g_legend(diffpropGphShinyDisp(exp())$VJgenes), nrow=1), nrow=4)}

    if (input$TypeClono=="expression" && input$Gene_Type== "J genes"){
       grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=2), just="top"), heights = unit(c(2,input$height,2.5,3), "cm"),
                             arrangeGrob(((normjuxBarsShinyDisp(exp())$BarGphJ)+ xlab(paste(input$locus,"J genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                               ((diffpropGphShinyDisp(exp())$Jgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = unit(c(input$width,(input$width)-6), "cm")),
                             arrangeGrob(g_legend(normjuxBarsShinyDisp(exp())$BarGphJ+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.200, 0.16),nrow=1),
                             arrangeGrob(g_legend(diffpropGphShinyDisp(exp())$VJgenes), nrow=1),nrow=4)}

   if (input$TypeClono=="expression" && input$Gene_Type== "D genes"){
      grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=2), just="top"), heights = unit(c(2,input$height,2.5,3), "cm"),
                  arrangeGrob(((normjuxBarsShinyDisp(exp())$BarGphD)+ xlab(paste(input$locus,"D genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                              ((diffpropGphShinyDisp(exp())$Dgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = unit(c(input$width,(input$width)-6), "cm")),
                  arrangeGrob(g_legend(normjuxBarsShinyDisp(exp())$BarGphD+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.200, 0.16),nrow=1),
                  arrangeGrob(g_legend(diffpropGphShinyDisp(exp())$VJgenes), nrow=1), nrow=4)}
   })

  wi <- function() {if(input$Type_allele=="Several alleles"){h=unit(c(input$widthSynAllele+2,(input$widthSynAllele)-12), "cm")
  } else {h=unit(c(input$widthSynAllele,(input$widthSynAllele)-8), "cm")}}
  widown <- function() {if(input$Type_allele=="Several alleles"){h=unit(c(input$widthSynAllele-5,(input$widthSynAllele)-14), "cm")
  } else {h=unit(c(input$widthSynAllele-8,(input$widthSynAllele)-12), "cm")}}

  SynthesisGphrAllele <- reactive({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating figure... Please wait.", value = 0)
    if (input$Gene_Type== "V genes"){
      if(nrow(DivExpallele()[which(DivExpallele()$Allele_Type=="V allele"),])==0){
        plot(0,type='n',axes=FALSE,ann=FALSE)
        text (1,1,paste("No alleles of",input$Gene_Type,"having significant differences in proportions validated by all multiple testing procedures"))
      } else{
      grid.arrange(main=textGrob(input$titleSynGphAllele,gp=gpar(cex=2), just="top"), heights = unit(c(2,input$heightSynAllele,2.5,3), "cm"),
                   arrangeGrob(((normjuxBarsAlleleShinyDisp(DivExpalleleGraph())$BarGphV)+ xlab(paste(input$locus,"V alleles",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                               ((diffpropGphAlleleShinyDisp(DivExpalleleGraph())$Vgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = wi() ),
                   arrangeGrob(g_legend(normjuxBarsAlleleShinyDisp(DivExpalleleGraph())$BarGphV+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                   arrangeGrob(g_legend(diffpropGphAlleleShinyDisp(DivExpalleleGraph())$VJgenes), nrow=1),nrow=4)
    }} else if (input$Gene_Type== "J genes"){
      if(nrow(DivExpallele()[which(DivExpallele()$Allele_Type=="J allele"),])==0){
        plot(0,type='n',axes=FALSE,ann=FALSE)
        text (1,1,paste("No alleles of",input$Gene_Type,"having significant differences in proportions validated by all multiple testing procedures"))
      }else{
      grid.arrange(main=textGrob(input$titleSynGphAllele,gp=gpar(cex=2), just="top"), heights = unit(c(2,input$heightSynAllele,2.5,3), "cm"),
                   arrangeGrob(((normjuxBarsAlleleShinyDisp(DivExpalleleGraph())$BarGphJ)+ xlab(paste(input$locus,"J alleles",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                               ((diffpropGphAlleleShinyDisp(DivExpalleleGraph())$Jgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = wi()),
                   arrangeGrob(g_legend(normjuxBarsAlleleShinyDisp(DivExpalleleGraph())$BarGphJ+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                   arrangeGrob(g_legend(diffpropGphAlleleShinyDisp(DivExpalleleGraph())$VJgenes), nrow=1),nrow=4)

    }} else if(input$Gene_Type== "D genes"){
      if(nrow(DivExpallele()[which(DivExpallele()$Allele_Type=="D allele"),])==0){
       plot(0,type='n',axes=FALSE,ann=FALSE)
       text (1,1,paste("No alleles of",input$Gene_Type,"having significant differences in proportions validated by all multiple testing procedures"))
      }else{
      grid.arrange(main=textGrob(input$titleSynGphAllele,gp=gpar(cex=2), just="top"), heights = unit(c(2,input$heightSynAllele,2.5,3), "cm"),
                   arrangeGrob(((normjuxBarsAlleleShinyDisp(DivExpalleleGraph())$BarGphD)+ xlab(paste(input$locus,"D alleles",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                               ((diffpropGphAlleleShinyDisp(DivExpalleleGraph())$Dgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = wi()),
                   arrangeGrob(g_legend(normjuxBarsAlleleShinyDisp(DivExpalleleGraph())$BarGphD+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                   arrangeGrob(g_legend(diffpropGphAlleleShinyDisp(DivExpalleleGraph())$VJgenes), nrow=1),nrow=4)

    }}
      })
  heightSynGene <- function() {input$height*37.8}
  output$SynthesisGph <- renderPlot({SynthesisGphr()}, height = heightSynGene)

  heightSynAllele <- function() {input$heightSynAllele*37.8}
  output$SynthesisGphAllele <- renderPlot({SynthesisGphrAllele()}, height = heightSynAllele)


  ################################
  output$downloadSyngraphAllelePDF <- downloadHandler(
    filename = function() {
        paste(input$TypeClono, "-syn_graph-",input$Gene_Type,'.pdf', sep="")},
    content = function(file) {
      if (input$Gene_Type== "V genes"){
        pdf(file,  height=(input$heightSynAllele)/2.54, width=(input$widthSynAllele)/2.54)
        grid.arrange(main=textGrob(input$titleSynGphAllele,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$heightSynAllele)-4.5,1.5,1), "cm"),
                     arrangeGrob(((normjuxBarsAllele(DivExpalleleGraph())$BarGphV)+ xlab(paste(input$locus,"V alleles",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGphAllele(DivExpalleleGraph())$Vgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = widown() ),
                     arrangeGrob(g_legend(normjuxBarsAllele(DivExpalleleGraph())$BarGphV+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2,0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGphAllele(DivExpalleleGraph())$VJgenes), nrow=1),nrow=4)
        dev.off()}
      if ( input$Gene_Type== "J genes"){
        pdf(file,  height=(input$heightSynAllele)/2.54, width=(input$widthSynAllele)/2.54)
        grid.arrange(main=textGrob(input$titleSynGphAllele,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$heightSynAllele)-4.5,1.5,1), "cm"),
                     arrangeGrob(((normjuxBarsAllele(DivExpalleleGraph())$BarGphJ)+ xlab(paste(input$locus,"J alleles",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGphAllele(DivExpalleleGraph())$Jgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = widown() ),
                     arrangeGrob(g_legend(normjuxBarsAllele(DivExpalleleGraph())$BarGphJ+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGphAllele(DivExpalleleGraph())$VJgenes), nrow=1),nrow=4)
        dev.off()}
      if (input$Gene_Type== "D genes"){
        pdf(file,  height=(input$height)/2.54, width=(input$width)/2.54)
        grid.arrange(main=textGrob(input$titleSynGphAllele,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$heightSynAllele)-4.5,1.5,1), "cm"),
                     arrangeGrob(((normjuxBarsAllele(DivExpalleleGraph())$BarGphD)+ xlab(paste(input$locus,"D alleles",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGphAllele(DivExpalleleGraph())$Dgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = widown() ),
                     arrangeGrob(g_legend(normjuxBarsAllele(DivExpalleleGraph())$BarGphD+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGphAllele(DivExpalleleGraph())$VJgenes), nrow=1),nrow=4)
        dev.off()}},
    contentType='NA')

  output$downloadSyngraphAllelePNG <- downloadHandler(
    filename = function() {
       paste (input$TypeClono, "-syn_graph-",input$Gene_Type,'.png', sep="")},
    content = function(file) {
      if (input$Gene_Type== "V genes"){
      png(file,  height=(input$heightSynAllele)/2.54, width=(input$widthSynAllele)/2.54, units = "in", res = 300)
      grid.arrange(main=textGrob(input$titleSynGphAllele,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$heightSynAllele)-4.5,1.5,1), "cm"),
                   arrangeGrob(((normjuxBarsAllele(DivExpalleleGraph())$BarGphV)+ xlab(paste(input$locus,"V alleles",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                               ((diffpropGphAllele(DivExpalleleGraph())$Vgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = widown() ),
                   arrangeGrob(g_legend(normjuxBarsAllele(DivExpalleleGraph())$BarGphV+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                   arrangeGrob(g_legend(diffpropGphAllele(DivExpalleleGraph())$VJgenes), nrow=1),nrow=4)
      dev.off()}
      if ( input$Gene_Type== "J genes"){
        png(file,  height=(input$heightSynAllele)/2.54, width=(input$widthSynAllele)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleSynGphAllele,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$heightSynAllele)-4.5,1.5,1), "cm"),
                     arrangeGrob(((normjuxBarsAllele(DivExpalleleGraph())$BarGphJ)+ xlab(paste(input$locus,"J alleles",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGphAllele(DivExpalleleGraph())$Jgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = widown()  ),
                     arrangeGrob(g_legend(normjuxBarsAllele(DivExpalleleGraph())$BarGphJ+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGphAllele(DivExpalleleGraph())$VJgenes), nrow=1),nrow=4)
        dev.off()}
      if (input$Gene_Type== "D genes"){
        png(file,  height=(input$heightSynAllele)/2.54, width=(input$widthSynAlleleSynAllele)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleSynGphAllele,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$heightSynAllele)-4.5,1.5,1), "cm"),
                     arrangeGrob(((normjuxBarsAllele(DivExpalleleGraph())$BarGphD)+ xlab(paste(input$locus,"D alleles",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGphAllele(DivExpalleleGraph())$Dgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = widown() ),
                     arrangeGrob(g_legend(normjuxBarsAllele(DivExpalleleGraph())$BarGphD+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGphAllele(DivExpalleleGraph())$VJgenes), nrow=1),nrow=4)
        dev.off()} },
    contentType='image/png')

  output$downloadSyngraphAlleleJPG <- downloadHandler(
    filename = function() {
      paste (input$TypeClono, "-syn_graph-",input$Gene_Type,'.jpg', sep="")},
    content = function(file) {
      if (input$Gene_Type== "V genes"){
        png(file,  height=(input$heightSynAllele)/2.54, width=(input$widthSynAllele)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleSynGphAllele,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$heightSynAllele)-4.5,1.5,1), "cm"),
                     arrangeGrob(((normjuxBarsAllele(DivExpalleleGraph())$BarGphV)+ xlab(paste(input$locus,"V alleles",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGphAllele(DivExpalleleGraph())$Vgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = widown() ),
                     arrangeGrob(g_legend(normjuxBarsAllele(DivExpalleleGraph())$BarGphV+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGphAllele(DivExpalleleGraph())$VJgenes), nrow=1),nrow=4)
        dev.off()}
      if ( input$Gene_Type== "J genes"){
        png(file,  height=(input$heightSynAllele)/2.54, width=(input$widthSynAllele)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleSynGphAllele,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$heightSynAllele)-4.5,1.5,1), "cm"),
                     arrangeGrob(((normjuxBarsAllele(DivExpalleleGraph())$BarGphJ)+ xlab(paste(input$locus,"J alleles",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGphAllele(DivExpalleleGraph())$Jgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = widown() ),
                     arrangeGrob(g_legend(normjuxBarsAllele(DivExpalleleGraph())$BarGphJ+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGphAllele(DivExpalleleGraph())$VJgenes), nrow=1),nrow=4)
        dev.off()}
      if (input$Gene_Type== "D genes"){
        png(file,  height=(input$heightSynAllele)/2.54, width=(input$widthSynAllele)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleSynGphAllele,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$heightSynAllele)-4.5,1.5,1), "cm"),
                     arrangeGrob(((normjuxBarsAllele(DivExpalleleGraph())$BarGphD)+ xlab(paste(input$locus,"D alleles",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGphAllele(DivExpalleleGraph())$Dgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = widown() ),
                     arrangeGrob(g_legend(normjuxBarsAllele(DivExpalleleGraph())$BarGphD+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGphAllele(DivExpalleleGraph())$VJgenes), nrow=1),nrow=4)
        dev.off()} },
    contentType='image/png')
############################################################### Display of the number of IMGT clonotype (AA) and assigned sequences for the synthesis graph
############################################

  NbclonoSet1SG <- reactive({Nbclono1<- paste("The number of IMGT clonotypes (AA) in set 1 is: ",HTML('<span style=color:#FF8000> ',length(set1()$expid) ))})

  NbseqSet1SG<- reactive({Nbseq1<-paste("The number of sequences assigned to IMGT clonotypes (AA) in set 1 is: ",HTML('<span style=color:#FF8000> ',sum(set1()$total) ))})

  output$NbClonoSet11SG<-renderText({
  if (input$TypeClono=="diversity" && (input$Gene_Type=="V genes"||input$Gene_Type=="J genes")){ NbclonoSet1SG()} else if (input$TypeClono=="expression" && (input$Gene_Type=="V genes"||input$Gene_Type=="J genes")){ NbseqSet1SG()}
  })

  NbclonoSet2SG <- reactive({Nbclono1<- paste("The number of IMGT clonotypes (AA) in set 2 is: ",HTML('<span style=color:#FF8000> ',length(set2()$expid) ))})

  NbseqSet2SG<- reactive({Nbseq1<-paste("The number of sequences assigned to IMGT clonotypes (AA) in set 2 is: ",HTML('<span style=color:#FF8000> ',sum(set2()$total) ))})

  output$NbClonoSet22SG<-renderText({
    if (input$TypeClono=="diversity"&& (input$Gene_Type=="V genes"||input$Gene_Type=="J genes")){ NbclonoSet2SG()} else if (input$TypeClono=="expression"&& (input$Gene_Type=="V genes"||input$Gene_Type=="J genes")){ NbseqSet2SG()}})



    ########## Save graphs as PDF, PNG and JPEG
  output$downloadMTPgraphPDF <- downloadHandler(
    filename = function() { paste(input$TypeClono, "-MTP_graph-" ,'.pdf', sep="")},
    content = function(file) {
      if (input$TypeClono=="diversity"){
      pdf(file,  height=3.14, width=6.7)
            multprocPlot(div())
            graphics::mtext(input$titleGphMTP, outer=TRUE,  cex=0.95, line=-1.75)
      dev.off()}else if (input$TypeClono=="expression"){
        pdf(file, height=3.14, width=6.7)
        multprocPlot(exp())
        graphics:: mtext(input$titleGphMTP, outer=TRUE,  cex=0.95, line=-1.75)
        dev.off()}},
    contentType=NA)

  output$downloadMTPgraphPNG <- downloadHandler(
    filename = function() {paste(input$TypeClono, "-MTP_graph-",'.png', sep="")},
    content = function(file) {
      if (input$TypeClono=="diversity"){
        png(file, width = 6.7, height = 3.14, units = "in", res = 300)
        multprocPlot(div())
        mtext(input$titleGphMTP, outer=TRUE,  cex=0.95, line=-1.75)
        dev.off()}else if (input$TypeClono=="expression"){
        png(file, width = 6.7, height = 3.14, units = "in", res = 300)
        multprocPlot(exp())
        mtext(input$titleGphMTP, outer=TRUE,  cex=0.95, line=-1.75)
          dev.off()}},
    contentType='image/png')

  output$downloadMTPgraphJPG <- downloadHandler(
    filename = function() {paste(input$TypeClono, "-MTP_graph-" ,'.jpg', sep="") },
    content = function(file) {
      if (input$TypeClono=="diversity"){
        jpeg(file, width = 6.7, height = 3.14, units = "in", res = 300)
        multprocPlot(div())
        mtext(input$titleGphMTP, outer=TRUE,  cex=0.95, line=-1.75)
        dev.off()}else if (input$TypeClono=="expression"){
        jpeg(file,width = 6.7, height = 3.14, units = "in", res = 300)
        multprocPlot(exp())
        mtext(input$titleGphMTP, outer=TRUE,  cex=0.95, line=-1.75)
        dev.off()}},
    contentType='image/jpg')
  ################################
  ########## Save graphs as PDF, PNG and JPEG
  output$downloadMTPgraphAllelePDF <- downloadHandler(
    filename = function() { paste(input$TypeClono, "-MTP_graph_allele-" ,'.pdf', sep="")},
    content = function(file) {
        pdf(file,  height=3.14, width=6.7)
        multprocPlot(DivExpallele())
        graphics::mtext(input$titleGphMTPallele, outer=TRUE,  cex=0.95, line=-1.75)
        dev.off()},
    contentType=NA)

  output$downloadMTPgraphAllelePNG <- downloadHandler(
    filename = function() {paste(input$TypeClono, "-MTP_graph_allele-",'.png', sep="")},
    content = function(file) {
        png(file, width = 6.7, height = 3.14, units = "in", res = 300)
        multprocPlot(DivExpallele())
        mtext(input$titleGphMTPallele, outer=TRUE,  cex=0.95, line=-1.75)
        dev.off()},
    contentType='image/png')

  output$downloadMTPgraphAlleleJPG <- downloadHandler(
    filename = function() {paste(input$TypeClono, "-MTP_graph_allele-" ,'.jpg', sep="")},
    content = function(file) {
        jpeg(file, width = 6.7, height = 3.14, units = "in", res = 300)
        multprocPlot(DivExpallele())
        mtext(input$titleGphMTPallele, outer=TRUE,  cex=0.95, line=-1.75)
        dev.off()},
    contentType='image/jpg')
  ################################

  output$downloadSyngraphPDF <- downloadHandler(
    filename = function() {
      if (input$TypeClono=="diversity"){
        paste(input$TypeClono, "-syn_graph-",input$Gene_Type,'.pdf', sep="")} else if (input$TypeClono=="expression"){paste(input$TypeClono, "-syn_graph-",input$Gene_Type,'.pdf', sep="")}},
    content = function(file) {
      if (input$TypeClono=="diversity" && input$Gene_Type== "V genes"){
        pdf(file,  height=(input$height)/2.54, width=(input$width)/2.54)
       grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4.5,1.5,1), "cm"),
                               arrangeGrob(((normjuxBars(div())$BarGphV)+ xlab(paste(input$locus,"V genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(div())$Vgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                               arrangeGrob(g_legend(normjuxBars(div())$BarGphV+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.200, 0.16),nrow=1),
                               arrangeGrob(g_legend(diffpropGph(div())$VJgenes), nrow=1), nrow=4)
    dev.off()}
      if (input$TypeClono=="diversity" && input$Gene_Type== "J genes"){
        pdf(file,  height=(input$height)/2.54, width=(input$width)/2.54)
       grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                               arrangeGrob(((normjuxBars(div())$BarGphJ)+ xlab(paste(input$locus,"J genes",sep=""))+scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(div())$Jgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                               arrangeGrob(g_legend(normjuxBars(div())$BarGphJ+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                               arrangeGrob(g_legend(diffpropGph(div())$VJgenes), nrow=1), nrow=4)
    dev.off()}
      if (input$TypeClono=="diversity" && input$Gene_Type== "D genes"){
        pdf(file,  height=(input$height)/2.54, width=(input$width)/2.54)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(div())$BarGphD)+ xlab(paste(input$locus,"D genes",sep=""))+scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(div())$Dgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(div())$BarGphD+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(div())$VJgenes), nrow=1),nrow=4)
    dev.off()}
      if (input$TypeClono=="expression" && input$Gene_Type== "V genes"){
        pdf(file,  height=(input$height)/2.54, width=(input$width)/2.54)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                               arrangeGrob(((normjuxBars(exp())$BarGphV)+ xlab(paste(input$locus,"V genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(exp())$Vgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                               arrangeGrob(g_legend(normjuxBars(exp())$BarGphV+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                               arrangeGrob(g_legend(diffpropGph(exp())$VJgenes), nrow=1), nrow=4)
        dev.off()}
      if (input$TypeClono=="expression" && input$Gene_Type== "J genes"){
        pdf(file,  height=(input$height)/2.54, width=(input$width)/2.54)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                               arrangeGrob(((normjuxBars(exp())$BarGphJ)+ xlab(paste(input$locus,"J genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(exp())$Jgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                               arrangeGrob(g_legend(normjuxBars(exp())$BarGphJ+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                               arrangeGrob(g_legend(diffpropGph(exp())$VJgenes), nrow=1), nrow=4)
        dev.off()}
      if (input$TypeClono=="expression" && input$Gene_Type== "D genes"){
        pdf(file,  height=(input$height)/2.54, width=(input$width)/2.54)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(exp())$BarGphD)+ xlab(paste(input$locus,"D genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(exp())$Dgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(exp())$BarGphD+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(exp())$VJgenes), nrow=1), nrow=4)
        dev.off()}},
    contentType='NA')

  output$downloadSyngraphPNG <- downloadHandler(
    filename = function() {
      if (input$TypeClono=="diversity"){
        paste(input$TypeClono, "-syn_graph-",input$Gene_Type,'.png', sep="")} else if (input$TypeClono=="expression"){paste(input$TypeClono, "-syn_graph-",input$Gene_Type,'.png', sep="")}},
    content = function(file) {
      if (input$TypeClono=="diversity" && input$Gene_Type== "V genes"){
        png(file,  height=(input$height)/2.54, width=(input$width)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4.5,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(div())$BarGphV)+ xlab(paste(input$locus,"V genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(div())$Vgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(div())$BarGphV+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.200, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(div())$VJgenes), nrow=1),nrow=4)
    dev.off()}
      if (input$TypeClono=="diversity" && input$Gene_Type== "J genes"){
        png(file,  height=(input$height)/2.54, width=(input$width)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(div())$BarGphJ)+ xlab(paste(input$locus,"J genes",sep=""))+scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(div())$Jgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(div())$BarGphJ+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(div())$VJgenes), nrow=1),nrow=4)
    dev.off()}
      if (input$TypeClono=="diversity" && input$Gene_Type== "D genes"){
        png(file,  height=(input$height)/2.54, width=(input$width)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(div())$BarGphD)+ xlab(paste(input$locus,"D genes",sep=""))+scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(div())$Dgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(div())$BarGphD+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(div())$VJgenes), nrow=1), nrow=4)
    dev.off() }
      if (input$TypeClono=="expression" && input$Gene_Type== "V genes"){
        png(file,  height=(input$height)/2.54, width=(input$width)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(exp())$BarGphV)+ xlab(paste(input$locus,"V genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(exp())$Vgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(exp())$BarGphV+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(exp())$VJgenes), nrow=1),nrow=4)
    dev.off()}

      if (input$TypeClono=="expression" && input$Gene_Type== "J genes"){
        png(file,  height=(input$height)/2.54, width=(input$width)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(exp())$BarGphJ)+ xlab(paste(input$locus,"J genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(exp())$Jgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(exp())$BarGphJ+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(exp())$VJgenes), nrow=1), nrow=4)
    dev.off()}
      if (input$TypeClono=="expression" && input$Gene_Type== "D genes"){
        png(file,  height=(input$height)/2.54, width=(input$width)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(exp())$BarGphD)+ xlab(paste(input$locus,"D genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(exp())$Dgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(exp())$BarGphD+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(exp())$VJgenes), nrow=1), nrow=4)
        dev.off()}},
    contentType='image/png')

  output$downloadSyngraphJPG <- downloadHandler(
    filename = function() {
      if (input$TypeClono=="diversity"){
        paste(input$TypeClono, "-syn_graph-",input$Gene_Type,'.jpg', sep="")} else if (input$TypeClono=="expression"){paste(input$TypeClono, "-syn_graph-",input$Gene_Type,'.jpg', sep="")}},
    content = function(file) {
      if (input$TypeClono=="diversity" && input$Gene_Type== "V genes"){
        jpeg(file,  height=(input$height)/2.54, width=(input$width)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4.5,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(div())$BarGphV)+ xlab(paste(input$locus,"V genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(div())$Vgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(div())$BarGphV+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.200, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(div())$VJgenes), nrow=1), nrow=4)
        dev.off()}
      if (input$TypeClono=="diversity" && input$Gene_Type== "J genes"){
        jpeg(file,  height=(input$height)/2.54, width=(input$width)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(div())$BarGphJ)+ xlab(paste(input$locus,"J genes",sep=""))+scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(div())$Jgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(div())$BarGphJ+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(div())$VJgenes), nrow=1), nrow=4)
        dev.off()}
      if (input$TypeClono=="diversity" && input$Gene_Type== "D genes"){
        jpeg(file,  height=(input$height)/2.54, width=(input$width)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(div())$BarGphD)+ xlab(paste(input$locus,"D genes",sep=""))+scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(div())$Dgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(div())$BarGphD+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(div())$VJgenes), nrow=1), nrow=4)
        dev.off()}
      if (input$TypeClono=="expression" && input$Gene_Type== "V genes"){
        jpeg(file,  height=(input$height)/2.54, width=(input$width)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(exp())$BarGphV)+ xlab(paste(input$locus,"V genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(exp())$Vgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(exp())$BarGphV+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(exp())$VJgenes), nrow=1), nrow=4)
        dev.off()}
      if (input$TypeClono=="expression" && input$Gene_Type== "J genes"){
        jpeg(file,  height=(input$height)/2.54, width=(input$width)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(exp())$BarGphJ)+ xlab(paste(input$locus,"J genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(exp())$Jgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(exp())$BarGphJ+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(exp())$VJgenes), nrow=1), nrow=4)
        dev.off()}
      if (input$TypeClono=="expression" && input$Gene_Type== "D genes"){
        jpeg(file,  height=(input$height)/2.54, width=(input$width)/2.54, units = "in", res = 300)
        grid.arrange(main=textGrob(input$titleGph,gp=gpar(cex=1.5), just="top"), heights = unit(c(1.5,(input$height)-4,1.5,1), "cm"),
                     arrangeGrob(((normjuxBars(exp())$BarGphD)+ xlab(paste(input$locus,"D genes",sep=""))+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))+theme(legend.position = "none")),
                                 ((diffpropGph(exp())$Dgenes)+ theme(axis.text.y = element_blank(),axis.title.y=element_blank())+theme(legend.position = "none")), nrow=1, widths = c(0.15, 0.10)),
                     arrangeGrob(g_legend(normjuxBars(exp())$BarGphD+ scale_fill_manual(values=c(input$barcolor2, input$barcolor1), breaks=c("Normalized_proportion.set2","Normalized_proportion.set1"))),grid.rect(gp=gpar(col="white")), widths = c(0.2, 0.16),nrow=1),
                     arrangeGrob(g_legend(diffpropGph(exp())$VJgenes), nrow=1), nrow=4)
        dev.off()} },
    contentType='image/jpg')

  ############################################
  ##################################### Bar graph set 1 CDR-IMGT length - normalized number of clonotypes (diversity)
  distPlotSetCDRdivexp<-function(data1, data2,color="blue", numset="1"){
    report1 <-data1
    ifelse(input$TypeClono=="diversity", report1$Normalized.nb.clonotypes<-(1/length(data1[,1]))*10000,  report1$Normalized.nb.sequences<-((report1$total)/(sum(report1$total)))*10000)
    if (input$Type_CDR=="CDR1-IMGT"){
    report1$cdrlength<-nchar(as.vector(report1$cdr1))} else if (input$Type_CDR=="CDR2-IMGT"){
      report1$cdrlength<-nchar(as.vector(report1$cdr2))} else if (input$Type_CDR=="CDR3-IMGT"){
        report1$cdrlength<-nchar(as.vector(report1$cdr3aa))}
    report2 <-data2
    ifelse(input$TypeClono=="diversity", report2$Normalized.nb.clonotypes<-(1/length(data2[,1]))*10000,  report2$Normalized.nb.sequences<-((report2$total)/(sum(report2$total)))*10000)
    if (input$Type_CDR=="CDR1-IMGT"){report2$cdrlength<-nchar(as.vector(report2$cdr1))} else if (input$Type_CDR=="CDR2-IMGT"){
        report2$cdrlength<-nchar(as.vector(report2$cdr2))} else if (input$Type_CDR=="CDR3-IMGT"){ report2$cdrlength<-nchar(as.vector(report2$cdr3aa))}
    t1 <- table(factor(report1$cdrlength, levels=min(report2$cdrlength, report1$cdrlength):max(report1$cdrlength, report2$cdrlength)))
    t1n<- round(t1/sum(t1)*10000, 3)
    texp1 <- aggregate(total~cdrlength, data=report1,sum)
    texp1$total1<- round(texp1$total/sum(texp1$total)*10000, 3)
    colnames(texp1) <- c("cdrlength","Nb.sequences.set1","Normalized.nb.sequences.set1")
    l <- data.frame(t1,t1n)
    l <- l[,c(1,2,4) ]
    colnames(l) <- c("cdrlength","Nb.clonotypes.set1","Normalized.nb.clonotypes.set1")
    df1 <- merge(l, texp1, all = TRUE, by="cdrlength")
    df1[is.na(df1)] <- 0
    ifelse(input$NormVal==TRUE,{ifelse(input$TypeClono=="diversity", {axisname <- "Normalized number of IMGT clonotypes (AA)"
    E1<-ggplot(df1,aes(x=as.factor(cdrlength),y =Normalized.nb.clonotypes.set1,text = paste("\"" ,as.factor(cdrlength),"\" (", Normalized.nb.clonotypes.set1,") ", sep="")))},{ axisname <- "Normalized number of sequences assigned to IMGT clonotypes (AA)"
    E1<-ggplot(df1,aes(x=as.factor(cdrlength),y =Normalized.nb.sequences.set1,text = paste("\"" ,as.factor(cdrlength),"\" (", Normalized.nb.sequences.set1, ") ", sep="")))})
    }, {ifelse(input$TypeClono=="diversity", {axisname <- "Number of IMGT clonotypes (AA)"
    E1<-ggplot(df1,aes(x=as.factor(cdrlength),y =Nb.clonotypes.set1,text = paste("\"" ,as.factor(cdrlength),"\" (", Nb.clonotypes.set1,") ", sep="")))},{ axisname <- "Number of sequences assigned to IMGT clonotypes (AA)"
    E1<-ggplot(df1,aes(x=as.factor(cdrlength),y =Nb.sequences.set1,text = paste("\"" ,as.factor(cdrlength),"\" (", Nb.sequences.set1, ") ", sep="")))})
    })
    E1<-E1+
      theme_grey()+
      geom_bar( size=0.25,stat="identity", fill=color,color="black",alpha=0.3,show.legend=FALSE) +
      xlab(paste(input$Type_CDR," lengths (set ",numset,")",sep=""))+ ylab(axisname)+
      theme(
        plot.margin=unit(x=c(0,0,2,2),units="cm"),
        panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
        strip.text.x = element_text(size=10, colour="black"),
        axis.title.x = element_text(size = 10,face="bold", colour="black",vjust=-0.5),
        axis.text.x=element_text(size = 10, colour="black"),
        strip.text.y = element_text(size=10, face="bold", colour="black"),
        axis.title.y = element_text(size = 9,face="bold", colour="black", vjust=1.5),
        axis.text.y=element_text( size = 10,hjust=0, colour="black"),
        strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=0.35, linetype="solid"),
        legend.title = element_text(size=10, face="bold"))
    E <- ggplotly(E1, tooltip = "text")}

  output$distPlotSet1CDR <- renderPlotly({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    distPlotSetCDRdivexp(set1(),set2())})
  output$distPlotSet2CDR <- renderPlotly({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    distPlotSetCDRdivexp(set2(),set1(),"red",numset="2")})
  ############
  #### Function to make table and graphs for CDR-IMGT ~ AA (or IMGT classes) in each position
  ############

  divexpCDR <- function(data){
    if (input$Type_CDR=="CDR1-IMGT"& input$TypeClono=="diversity"){
      seq <- as.vector(data$cdr1)
      pos<-unlist(lapply(1:nchar(seq)[1],function(x,y) num_cdr1(x,y),y=nchar(seq)[1]))
      dff <-as.data.frame(matrix(unlist(strsplit(as.character(data[,14]),"")), nrow=length(data[,14]), byrow=TRUE))
    } else if (input$Type_CDR=="CDR2-IMGT"& input$TypeClono=="diversity"){
      seq <- as.vector(data$cdr2)
      pos<-unlist(lapply(1:nchar(seq)[1],function(x,y) num_cdr2(x,y),y=nchar(seq)[1]))
      dff <-as.data.frame(matrix(unlist(strsplit(as.character(data[,15]),"")), nrow=length(data[,15]), byrow=TRUE))
    } else if (input$Type_CDR=="CDR3-IMGT"& input$TypeClono=="diversity"){
      seq <- as.vector(data$cdr3aa)
      pos<-unlist(lapply(1:nchar(seq)[1],function(x,y) num_cdr(x,y),y=nchar(seq)[1]))
      dff <-as.data.frame(matrix(unlist(strsplit(as.character(data[,1]),"")), nrow=length(data[,1]), byrow=TRUE))
    } else if (input$Type_CDR=="CDR1-IMGT"& input$TypeClono=="expression"){
      seq <- data.frame(data$cdr1,data$total)
      seq1 <- as.character(data$cdr1[1])
      pos<-unlist(lapply(1:nchar(seq1),function(x,y) num_cdr1(x,y),y<-nchar(seq1)))
      dupl<-function (x,y) {rep(x,y)}
      seqexpr<-matrix(unlist(mapply(dupl,x=seq[,1],y=seq[,2])))
      dff <-matrix(unlist(strsplit(seqexpr[!sapply( seqexpr, is.null)],"")), nrow=length(seqexpr), byrow=TRUE)
    } else if (input$Type_CDR=="CDR2-IMGT"& input$TypeClono=="expression"){
      seq <- data.frame(data$cdr2,data$total)
      seq1 <- as.character(data$cdr2[1])
      pos<-unlist(lapply(1:nchar(seq1),function(x,y) num_cdr2(x,y),y<-nchar(seq1)))
      dupl<-function (x,y) {rep(x,y)}
      seqexpr<-matrix(unlist(mapply(dupl,x=seq[,1],y=seq[,2])))
      dff <-matrix(unlist(strsplit(seqexpr[!sapply( seqexpr, is.null)],"")), nrow=length(seqexpr), byrow=TRUE)
    } else if (input$Type_CDR=="CDR3-IMGT"& input$TypeClono=="expression"){
      seq <- data.frame(data$cdr3aa,data$total)
      seq1 <- as.character(data$cdr3aa[1])
      pos<-unlist(lapply(1:nchar(seq1),function(x,y) num_cdr(x,y),y<-nchar(seq1)))
      dupl<-function (x,y) {rep(x,y)}
      seqexpr<-matrix(unlist(mapply(dupl,x=seq[,1],y=seq[,2])))
      dff <-matrix(unlist(strsplit(seqexpr[!sapply( seqexpr, is.null)],"")), nrow=length(seqexpr), byrow=TRUE)}
    x<-apply(dff, 2, paste, collapse="")
    frequence<-function(y){  A <- unlist(lapply(gregexpr(y,x),function(x) if(x[[1]]!=-1) length(x) else 0))
    return(A) }
    ifelse(input$TypeClono=="diversity",V<-lapply(AA,frequence), V<-lapply(AA,function(y,x) frequences(y,x),x<-x) )
    aa<-do.call(rbind, V)
    ifelse(input$AbsPercent=="Percentages",aa <- round((aa/colSums(aa)*100),2),aa<-do.call(rbind, V) )
    # Matrix aa for AA
    if(input$IMGTAAclasses=="20 amino acids"){
      rownames(aa)<-AAcodonStop
      colnames(aa)<-pos
      AA <-melt(aa)} else if(input$IMGTAAclasses=="Physicochemical"){
        # Matrix aaclassPhysico for 'physicochemical' Classes
        aa <- rbind(colSums(aa[c(1,10,11,20), ,drop=FALSE]),colSums(aa[c(2,9,12), ,drop=FALSE]),colSums(aa[c(5,13), ,drop=FALSE]),colSums(aa[c(16,17), ,drop=FALSE]),colSums(aa[c(4,7), ,drop=FALSE]),colSums(aa[c(3,6), ,drop=FALSE]),aa[8,],aa[14,],aa[15,],aa[18,],aa[19,],aa[21,],aa[22,])
        rownames(aa) <- classPhysico
        colnames(aa)<-pos
        AA <-melt(aa)}else if(input$IMGTAAclasses=="Hydropathy"){
          # Matrix aaclassHydro for 'Hydropathy' Classes
          aa <- rbind(colSums( aa[c(1,5,10,11,13,14,18,20), ,drop=FALSE]),colSums(aa[c(8,9,15,16,17,19), ,drop=FALSE]),colSums(aa[c(2,3,4,6,7,12), ,drop=FALSE]),aa[21,],aa[22,])
          rownames(aa) <- classHydro
          colnames(aa)<-pos
          AA <-melt(aa)}else if(input$IMGTAAclasses=="Volume"){
            # Matrix aaclassHydro for 'Volume' Classes
            aa <- rbind(colSums( aa[c(1,8,16), ,drop=FALSE]),colSums(aa[c(3,4,5,15,17), ,drop=FALSE]),colSums(aa[c(6,7,9,20), ,drop=FALSE]),colSums(aa[c(2,10,11,12,13), ,drop=FALSE]),colSums(aa[c(14,18,19), ,drop=FALSE]),aa[21,],aa[22,])
            rownames(aa) <- classVolume
            colnames(aa)<-pos
            AA <-melt(aa)}else if(input$IMGTAAclasses=="Chemical"){
              # Matrix aaclassChemical for 'Chemical' Classes
              aa <- rbind(colSums(aa[c(1,8,10,11,15,20), ,drop=FALSE]),colSums(aa[c(14,18,19), ,drop=FALSE]),colSums(aa[c(5,13), ,drop=FALSE]),colSums(aa[c(16,17), ,drop=FALSE]),colSums(aa[c(2,9,12), ,drop=FALSE]),colSums(aa[c(4,7), ,drop=FALSE]),colSums(aa[c(3,6), ,drop=FALSE]),aa[21,],aa[22,])
              rownames(aa) <- classChemical
              colnames(aa)<-pos
              AA <-melt(aa)}else if(input$IMGTAAclasses=="Charge"){
                # Matrix aaclassCharge for 'Charge' Classes
                aa <- rbind(colSums(aa[c(2,9,12), ,drop=FALSE]),colSums(aa[c(4,7), ,drop=FALSE]),colSums(aa[c(1,3,5,6,8,10,11,13,14,15,16,17,18,19,20), ,drop=FALSE]),aa[21,],aa[22,])
                rownames(aa) <- classCharge
                colnames(aa)<-pos
                AA <-melt(aa)}else if(input$IMGTAAclasses=="Hydrogen donor or acceptor atoms"){
                  # Matrix HydroDonorAA for 'Hydrogen donor or acceptor atoms' Classes
                  aa <- rbind(colSums(aa[c(2,12,18), ,drop=FALSE]),colSums(aa[c(4,7), ,drop=FALSE]),colSums(aa[c(3,6,9,16,17,19), ,drop=FALSE]),colSums(aa[c(1,5,8,10,11,13,14,15,20), ,drop=FALSE]),aa[21,],aa[22,])
                  rownames(aa) <- classHydroDonorAA
                  colnames(aa)<-pos
                  AA <-melt(aa)}else if(input$IMGTAAclasses=="Polarity"){
                    # Matrix aaclassCharge for 'Polarity' Classes
                    aa <- rbind(colSums(aa[c(2,3,4,6,7,9,12,16,17,19), ,drop=FALSE]),colSums(aa[c(1,5,8,10,11,13,14,15,18,20), ,drop=FALSE]),aa[21,],aa[22,])
                    rownames(aa) <- classPolarity
                    colnames(aa)<-pos
                    AA <-melt(aa)}
    list(a1div=aa,ameltdiv=AA)
  }

  AAposdivexp<- reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    return(list(c1div= divexpCDR(clonperCDRlength1())$a1div, cc1div= divexpCDR(clonperCDRlength1())$ameltdiv,
                                   c2div= divexpCDR(clonperCDRlength2())$a1div, cc2div= divexpCDR(clonperCDRlength2())$ameltdiv))})

  set1DivclonperCDRlengthCDR <-reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    AAposdivexp()$c1div})

  set2DivclonperCDRlengthCDR <-reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    AAposdivexp()$c2div})

  Set1DivclonperCDRlengthCDR <-reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    AAposdivexp()$cc1div})
  Set2DivclonperCDRlengthCDR <-reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    AAposdivexp()$cc2div})

  namerow <- reactive(
    if(input$IMGTAAclasses=="20 amino acids"){
    paste(input$IMGTAAclasses)} else {paste(input$IMGTAAclasses, "classes")} )
  namecol <- reactive(paste(input$Type_CDR, "positions"))

  output$AAposset1 <- renderDataTable({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating table... Please wait.", value = 0)
    datatable(set1DivclonperCDRlengthCDR(),container = htmltools::withTags(table(
      class = 'display',thead(
        tr(
          th(rowspan = 2, namerow()),
          th(colspan = length(colnames(set1DivclonperCDRlengthCDR())), namecol(), style="text-align:center;")
        ),
        tr(
          lapply(colnames(set1DivclonperCDRlengthCDR()), th)
        )
      )
    )),rownames=TRUE,options = list(searchHighlight = TRUE,lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
                                                                                                           pageLength = 5, autoWidth = TRUE, orderClasses = TRUE,scrollX='100%')) })

  output$AAposset2 <- renderDataTable({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating table... Please wait.", value = 0)
    datatable(set2DivclonperCDRlengthCDR(),container = htmltools::withTags(table(
      class = 'display',thead(
        tr(
          th(rowspan = 2, namerow()),
          th(colspan = length(colnames(set2DivclonperCDRlengthCDR())),  namecol(), style="text-align:center;")
        ),
        tr(
          lapply(colnames(set2DivclonperCDRlengthCDR()), th)
        )
      )
    )),rownames=TRUE,options = list(searchHighlight = TRUE,lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
                                                                                                           pageLength = 5, autoWidth = TRUE, orderClasses = TRUE,scrollX='100%')) })

  observeEvent(input$hide1,{toggle("AAposset1")})
  observeEvent(input$hide2,{toggle("AAposset2")})

   ft <- list(
    family = "Arial, sans-serif",
    size = 14,
    color = "black")
  #####
  ## Plot CDR-IMGT~AA
  #####
  distPlotAA<-function(data){
    if(input$IMGTAAclasses=="20 amino acids"){brek <- AAcodonStopplot} else if (input$IMGTAAclasses=="Physicochemical"){
      brek <- classPhysico} else if (input$IMGTAAclasses=="Hydropathy"){
        brek <- classHydro} else if (input$IMGTAAclasses=="Volume"){
          brek <- classVolume} else if (input$IMGTAAclasses=="Chemical"){
            brek <-classChemical} else if (input$IMGTAAclasses=="Charge"){
              brek <- classCharge} else if (input$IMGTAAclasses=="Hydrogen donor or acceptor atoms"){
                brek <- classHydroDonorAA}else if (input$IMGTAAclasses=="Polarity"){
                  brek <- classPolarity}
    if(input$IMGTAAclasses=="20 amino acids"){color <- colors} else if (input$IMGTAAclasses=="Physicochemical"){
      color <- colorsPhysico} else if (input$IMGTAAclasses=="Hydropathy"){
        color <- colorsHydro} else if (input$IMGTAAclasses=="Volume"){
          color <- colorsVolume} else if (input$IMGTAAclasses=="Chemical"){
            color<-colorsChemical} else if (input$IMGTAAclasses=="Charge"){
              color <- colorsCharge} else if (input$IMGTAAclasses=="Hydrogen donor or acceptor atoms"){
                color <- colorsHydroDonorAA}else if (input$IMGTAAclasses=="Polarity"){
                  color <- colorsPolarity}
    if(input$AbsPercent =="Absolute values" & input$TypeClono =="diversity"){DivExp="Number of"} else if(input$AbsPercent =="Absolute values" & input$TypeClono =="expression") {DivExp="Number of sequences assigned to"}
    if(input$AbsPercent =="Percentages" & input$TypeClono =="diversity"){DivExp="% of"} else if (input$AbsPercent =="Percentages" & input$TypeClono =="expression")  {DivExp="% of sequences assigned to"}
    colnames(data)[1] <- "Class"
    colnames(data)[3] <-"Y_value"
  plotAA<-ggplot(data,aes(x=factor(Var2, levels=unique(as.character(Var2))),y= Y_value,fill=Class,text = paste(Class," (", Y_value,") ", sep="")) ) +
      geom_bar(stat="identity", colour="black", size=0.35,show.legend = TRUE)+
      theme_grey()+
      xlab("")+ ylab("")+
      scale_fill_manual(name="",values=color,breaks=brek)+
    theme(
        plot.margin=unit(x=c(0,0,2,2),units="cm"),
        panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
        strip.text.x = element_text(size=10,face="bold", colour="black"),
        axis.title.x = element_text(size = 10,face="bold", colour="black"),
        axis.text.x=element_text(size = 10,face="bold", colour="black"),
        strip.text.y = element_text(size=10, face="bold", colour="black"),
        axis.title.y = element_text(size = rel(1),face="bold", colour="black"),
        axis.text.y=element_text( size = 10,face="bold",hjust=0, colour="black"),
        strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid"),
        legend.title = element_blank(),
        legend.text = element_text(size=8, face="bold"),
        legend.key.size = unit(0.25, "cm"))
  E <- ggplotly(plotAA , tooltip = "text")
  x <- list( title = paste(input$Type_CDR,"positions", collapse = ""), titlefont = ft)
  y <- list( title = paste(DivExp,"IMGT clonotypes (AA)", collapse = ""), titlefont = ft)
  E <- E %>%
    layout(xaxis =x , yaxis =y, hovermode ="x", autosize = F, width = (input$widthAApos)*37,795275, height = (input$heightAApos)*37,795275 )
 }

  output$distPlotAAdivexp1 <- renderPlotly({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating figure... Please wait.", value = 0)
    distPlotAA(Set1DivclonperCDRlengthCDR())})
  output$distPlotAAdivexp2 <- renderPlotly({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating figure... Please wait.", value = 0)
    distPlotAA(Set2DivclonperCDRlengthCDR())})

####### Shannon, Kabat index for AA and CDR-IMGT Positions
  Ind <- function(data, type=input$TypeIndex, name="Index_value"){
    if(input$TypeIndex=="Shannon entropy"){S <- Shannon(t(data))
    }else if(input$TypeIndex=="Wu-Kabat variability"){S <- Kabat(data)
    }else {S <- Simpson(data)}
    G <-data.frame(rownames(t(data)))
    G$S <- S
    colnames(G) <- c("Positions",name)
    G}

Indtab <- function(data){t(Ind(data, type=input$TypeIndex, name="Index_value"))}

  output$IndexTable1 <- renderDataTable({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating table... Please wait.", value = 0)
    datatable(data.frame(Indtab(set1DivclonperCDRlengthCDR()))[2,], container = htmltools::withTags(table(
      class = 'display',
      thead(
        tr(
          th(rowspan = 2, 'Variability index'),
          th(colspan = length(Ind(set1DivclonperCDRlengthCDR())[,1]),  namecol(), style="text-align:center;")
        ),
        tr(
          lapply(Ind(set1DivclonperCDRlengthCDR())[,1], th)
        )
      )
    )), options = list(pageLength = 1, dom = 't'),rownames=input$TypeIndex )})

  output$IndexTable2 <- renderDataTable({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating table... Please wait.", value = 0)
    datatable(data.frame(Indtab(set2DivclonperCDRlengthCDR()))[2,], container = htmltools::withTags(table(
      class = 'display',
      thead(
        tr(
          th(rowspan = 2, 'Variability index'),
          th(colspan = length(Ind(set2DivclonperCDRlengthCDR())[,1]),  namecol(), style="text-align:center;")
        ),
        tr(
          lapply(Ind(set2DivclonperCDRlengthCDR())[,1], th)
        )
      )
    )), options = list(pageLength = 1, dom = 't'),rownames=input$TypeIndex )})

  ShannonP1 <- reactive({ Ind(set1DivclonperCDRlengthCDR(), type="Shannon", name="ShannonIdx")})
  ShannonP2 <- reactive({ Ind(set2DivclonperCDRlengthCDR(), type="Shannon", name="ShannonIdx")})

  KabatP1 <- reactive({Ind(set1DivclonperCDRlengthCDR(), type="Kabat", name="KabatIdx")})
  KabatP2 <- reactive({Ind(set2DivclonperCDRlengthCDR(), type="Kabat", name="KabatIdx")})

  SimpsonP1 <- reactive({ Ind(set1DivclonperCDRlengthCDR(), type="Simpson", name="SimpsonIdx")})
  SimpsonP2 <- reactive({ Ind(set2DivclonperCDRlengthCDR(), type="Simpson", name="SimpsonIdx")})

  Indexplot <- function(data,Index_value, nameI="Index name",color="blue",set="(set 1)"){
    E <- ggplot(data=data, aes(x=Positions, y=Index_value )) +
      geom_line(colour=color,size=0.2,group=1) +
      geom_point()+xlab("")+ylab("")+
      theme(
        plot.margin=unit(x=c(0,0,2,2),units="cm"),
        panel.border = element_rect(linetype = "solid", colour = "#808080", fill=NA),
        strip.text.x = element_text(size=10,face="bold", colour="black"),
        axis.title.x = element_text(size = 10,face="bold", colour="black",margin = margin(b = 20)),
        axis.text.x=element_text(size = 10,face="bold", colour="black"),
        strip.text.y = element_text(size=10, face="bold", colour="black"),
        axis.title.y = element_text(size = 10,face="bold", colour="black", margin = margin(r = 200)),
        axis.text.y=element_text( size = 10,face="bold",hjust=0, colour="black"),
        strip.background = element_rect( colour="#808080", fill="#DBDBDB", size=1, linetype="solid"),
        legend.title = element_text(size=10, face="bold"),
        legend.text = element_text(size=10, face="bold"),
        legend.key.size = unit(1, "cm"))
    E1 <- ggplotly(E)
    #%>% config(displayModeBar = F)

    x <- list( title = paste(input$Type_CDR,"positions", set=set ,collapse = " "), titlefont = ft)
    y <- list( title = nameI, titlefont = ft)

      if(input$IMGTAAclasses=="20 amino acids"){
         E1 <- E1 %>%layout(xaxis = x, yaxis = y, autosize = F, width = ((input$widthAApos)*37.795275-115), height = 250)} else if (input$IMGTAAclasses=="Physicochemical"){
          E1 <- E1 %>% layout(xaxis = x, yaxis = y, autosize = F, width = ((input$widthAApos)*37.795275-145), height = 250)} else if (input$IMGTAAclasses=="Hydropathy"){
           E1 <- E1 %>% layout(xaxis = x, yaxis = y, autosize = F, width = ((input$widthAApos)*37.795275-168), height = 250)} else if (input$IMGTAAclasses=="Volume"){
            E1 <- E1 %>% layout(xaxis = x, yaxis = y, autosize = F, width = ((input$widthAApos)*37.795275-153), height = 250)} else if (input$IMGTAAclasses=="Chemical"){
             E1 <- E1 %>% layout(xaxis = x, yaxis = y, autosize = F, width = ((input$widthAApos)*37.795275-145), height = 250)} else if (input$IMGTAAclasses=="Charge"){
              E1 <- E1 %>% layout(xaxis = x, yaxis = y, autosize = F, width = ((input$widthAApos)*37.795275-168), height = 250)} else if (input$IMGTAAclasses=="Hydrogen donor or acceptor atoms"){
               E1 <- E1 %>%  layout(xaxis = x, yaxis = y, autosize = F, width = ((input$widthAApos)*37.795275-190), height = 250)}else if (input$IMGTAAclasses=="Polarity"){
                E1 <- E1 %>% layout(xaxis = x, yaxis = y, autosize = F, width = ((input$widthAApos)*37.795275-155), height = 250)}
    }

  output$downloadAAposset1 <- downloadHandler(
    filename = function() {paste(input$TypeClono, "-per ",input$Type_CDR," length_position set 1" ,'.csv', sep="")},
    content = function(file) {write.table(set1DivclonperCDRlengthCDR(), file, sep = ";", col.names = NA, row.names = TRUE, dec = ",")})

  output$downloadAAposset2 <- downloadHandler(
    filename = function() {paste(input$TypeClono, "-per ",input$Type_CDR," length_position set 2" ,'.csv', sep="")},
    content = function(file) {write.table(set2DivclonperCDRlengthCDR(), file, sep = ";", col.names = NA, row.names = TRUE, dec = ",")})

  output$Indexplot1 <-renderPlotly({if (input$TypeIndex=="Shannon entropy"){Indexplot(ShannonP1(),ShannonP1()$ShannonIdx,"Shannon entropy")}else if(input$TypeIndex=="Wu-Kabat variability"){
    Indexplot(KabatP1(),KabatP1()$KabatIdx,"Wu-Kabat variability")} else if (input$TypeIndex=="Simpson index"){Indexplot(SimpsonP1(),SimpsonP1()$SimpsonIdx,"Simpson index") }})

  output$Indexplot2 <-renderPlotly({if (input$TypeIndex=="Shannon entropy"){Indexplot(ShannonP2(),ShannonP2()$ShannonIdx, "Shannon entropy","red","(set 2)")}else if(input$TypeIndex=="Wu-Kabat variability"){
    Indexplot(KabatP2(),KabatP2()$KabatIdx,"Wu-Kabat variability","red","(Set 2)")} else if (input$TypeIndex=="Simpson index"){Indexplot(SimpsonP2(),SimpsonP2()$SimpsonIdx,"Simpson index","red","(Set 2)") }})

  ####
  ##### Table of V-D-J gene associations (for the dendrogramme)
  geneassociation <- function(data){
    if( input$TypeClono=="diversity"){
    if (input$Type_association=="V- J gene associations"){
      dnd <- as.matrix(ftable(data$vgene,data$jgene))
    } else if (input$Type_association=="V- D gene associations"){
      dnd <- as.matrix(ftable(data$vgene,data$dgene))
    } else {
      dnd <- as.matrix(ftable(data$jgene,data$dgene))}
      dnd <-  dnd[,which(colnames(dnd) != "")]
      if (input$NormValues){dnd/length(data[,1])*10000} else  {dnd}
      }else if( input$TypeClono=="expression"){
    if (input$Type_association=="V- J gene associations"){
      dnd <-aggregate(total~vgene+jgene, data=data,sum)
      dnd<- xtabs(total~., data=dnd)
    } else if (input$Type_association=="V- D gene associations"){
      dnd <-aggregate(total~vgene+dgene, data=data,sum)
      dnd<- xtabs(total~., data=dnd)
    } else {
      dnd <-aggregate(total~jgene+dgene, data=data,sum)
      dnd<- xtabs(total~., data=dnd)}
        dnd <-  dnd[,which(colnames(dnd) != "")]
        if (input$NormValues){dnd/sum(data$total)*10000} else  {dnd}}}

  DendroSet1 <- reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    geneassociation(set1())})
  DendroSet2 <- reactive({
    infile1 <- input$files1
    infile2 <- input$files2
    validate( need((!is.null(infile1)&&!is.null(infile2)), "Please choose IMGT/HighV-QUEST set 1 and set 2" )
    )
    geneassociation(set2())})
  output$ DendroSet1table <- renderDataTable({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating table... Please wait.", value = 0)
    datatable(DendroSet1(),rownames=TRUE,options = list(searchHighlight = TRUE,lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
                                                                        pageLength = 5, autoWidth = TRUE, orderClasses = TRUE,scrollX='100%')) })

  output$ DendroSet2table <- renderDataTable({
    progress = shiny::Progress$new()
    on.exit(progress$close())
    progress$set(message = "Creating table... Please wait.", value = 0)
    datatable(DendroSet2(),rownames=TRUE,options = list(searchHighlight = TRUE,lengthMenu = list(c(5,10,25,50, -1), list('5','10','25', '50', 'All')),
                                                        pageLength = 5, autoWidth = TRUE, orderClasses = TRUE,scrollX='100%')) })
   ####
  hclustward <- function(d) hclust(d, method="ward.D")
  disteucl <- function(x) dist(x, method="canberra")
  output$HeatmapSet1 <- renderD3heatmap({
    d3heatmap(
      DendroSet1(), scale="none",distfun=disteucl, hclustfun = hclustward,xaxis_font_size = "12px",yaxis_font_size = "12px",xaxis_height=200, yaxis_width=250,
      colors = input$palette,
      dendrogram = if (input$clustering) "both" else "none")
  })
  output$HeatmapSet2 <- renderD3heatmap({
    d3heatmap(
      DendroSet2(), scale="none",distfun=disteucl, hclustfun =hclustward,xaxis_font_size = "12px",yaxis_font_size = "12px",xaxis_height=200, yaxis_width=250,
      colors = input$palette,
      dendrogram = if (input$clustering) "both" else "none")})

  colorsDendro <- reactive({
         if(input$palette=="YlGnBu"){colorsDendro<-c("#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58")
  } else if (input$palette=="YlOrRd"){colorsDendro<-c("#ffffcc", "#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a", "#e31a1c","#bd0026","#800026")
  } else if (input$palette=="Greens"){colorsDendro<-c("#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#005a32")
  } else if (input$palette=="Blues"){colorsDendro<-c("#f7fbff", "#deebf7", "#c6dbef", "#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b")
  } else if (input$palette=="Reds"){colorsDendro<-c("#fff5f0" ,"#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d" ,"#a50f15","#67000d")}
    colorsDendro})

  ########## Save graphs as PDF, PNG and JPEG
  output$heatmap1PDF <- downloadHandler(
    filename = function() { paste(input$TypeClono, "-heatmap_graph-" ,'.pdf', sep="")},
    content = function(file) {
      pdf(file, height=5.7, width=5.7)
      if (input$clustering) {
        heatmap(DendroSet1(), col=colorsDendro(), distfun=disteucl, hclustfun = hclustward , margins = c(7,7),cexRow=0.65, cexCol=0.75, scale='none')
      }else heatmap(DendroSet1(), col=colorsDendro() ,Rowv =NA, Colv = NA , margins = c(7,7),cexRow=0.65, cexCol=0.75, scale='none')
        dev.off()},
    contentType=NA)

  output$downloadheatmap1PNG <- downloadHandler(
     filename = function() {paste(input$TypeClono, "-heatmap_graph-",'.png', sep="")},
    content = function(file) {
        png(file, width = 5.7, height = 5.7, units = "in", res = 300)
        if (input$clustering) {
          heatmap(DendroSet1(), col=colorsDendro(), distfun=disteucl, hclustfun = hclustward, margins = c(7,7),cexRow=0.65, cexCol=0.75, scale='none')
        } else heatmap(DendroSet1(), col=colorsDendro() ,Rowv =NA, Colv = NA , margins = c(7,7),cexRow=0.65, cexCol=0.75, scale='none')
       dev.off()},
    contentType='image/png')

  output$downloadheatmap1JPG <- downloadHandler(
    filename = function() {paste(input$TypeClono, "-MTP_graph-" ,'.jpg', sep="")},
    content = function(file) {
      jpeg(file, width = 5.7, height =5.7, units = "in", res = 300)
      if (input$clustering) {
        heatmap(DendroSet1(), col=colorsDendro(), distfun=disteucl, hclustfun = hclustward , margins = c(7,7),cexRow=0.65, cexCol=0.75, scale='none')
      } else heatmap(DendroSet1(), col=colorsDendro() ,Rowv =NA, Colv = NA , margins = c(7,7),cexRow=0.65, cexCol=0.75, scale='none')
     dev.off()},
    contentType='image/jpg')

  ###########
  output$heatmap2PDF <- downloadHandler(
    filename = function() { paste(input$TypeClono, "-heatmap_graph-" ,'.pdf', sep="")},
    content = function(file) {
      pdf(file, height=5.7, width=5.7)
      if (input$clustering) {
        heatmap(DendroSet2(), col=colorsDendro(),distfun=disteucl, hclustfun = hclustward , margins = c(7,7),cexRow=0.65, cexCol=0.75, scale='none')
      }else heatmap(DendroSet2(), col=colorsDendro() ,Rowv =NA, Colv = NA , margins = c(7,7),cexRow=0.65, cexCol=0.75, scale='none')
     dev.off()},
    contentType=NA)

  output$downloadheatmap2PNG <- downloadHandler(

    filename = function() {paste(input$TypeClono, "-heatmap_graph-",'.png', sep="")},
    content = function(file) {
      png(file, width = 5.7, height = 5.7, units = "in", res = 300)
      if (input$clustering) {
        heatmap(DendroSet2(), col=colorsDendro(), distfun=disteucl, hclustfun = hclustward , margins = c(7,7),cexRow=0.65, cexCol=0.75, scale='none')
      }else heatmap(DendroSet2(), col=colorsDendro() ,Rowv =NA, Colv = NA , margins = c(7,7),cexRow=0.65, cexCol=0.75, scale='none')
      dev.off()},
    contentType='image/png')

  output$downloadheatmap2JPG <- downloadHandler(
    filename = function() {paste(input$TypeClono, "-MTP_graph-" ,'.jpg', sep="")},
    content = function(file) {
     jpeg(file, width = 5.7, height =5.7, units = "in", res = 300)
      if (input$clustering) {
        heatmap(DendroSet2(), col=colorsDendro(),distfun=disteucl, hclustfun = hclustward , margins = c(7,7),cexRow=0.65, cexCol=0.75, scale='none')
      }else heatmap(DendroSet2(), col=colorsDendro() ,Rowv =NA, Colv = NA , margins = c(7,7),cexRow=0.65, cexCol=0.75, scale='none')
    dev.off()},
    contentType='image/jpg')

  output$heatmapset1table<-renderText({ paste(input$Type_association, "table (set 1)")})
  output$heatmapset2table<-renderText({ paste(input$Type_association, "table (set 2)")})

  output$downloadDendroSet1 <- downloadHandler(
    filename = function() {
      paste(input$Type_association, " table set 1" ,'.csv', sep="")},
    content = function(file) {
      write.table( DendroSet1(), file, sep = ";", col.names = NA, row.names = TRUE, dec = ",")})

  output$downloadDendroSet2 <- downloadHandler(
    filename = function() {
      paste(input$Type_association, " table set 2" ,'.csv', sep="")},
    content = function(file) {
      write.table( DendroSet2(), file, sep = ";", col.names = NA, row.names = TRUE, dec = ",")})
  })


