R/RNAseq.R

Defines functions downloadShrimp downloadMirbase makeDb.R matureOnHairpin trim plotDensity length.stat reading.log shrimp countMature wrapperMirnaCounts miRNAde SaveDESeq2TopTable deseq2Processing openmiRNAFile loadmirnapath permuting enrich runEnrichment mirnaTable SaveMirPathTopTable mirPath

Documented in deseq2Processing downloadShrimp enrich loadmirnapath miRNAde mirnaTable mirPath permuting runEnrichment wrapperMirnaCounts

#oneChannelGUI miRNAbowtieRun executes bowtie and convert a sam in a bam file  miRNAs-seq
#oneChannelGUI mRNAbowtieRun executes bowtie and convert a sam in a bam file  mRNAs-seq
#                            the resulting bam files contains only the mapped reads
#oneChannelGUI adaptorTrimm run a perl script that remove 5 ad 3 prime end adaptors from illumina reads
#oneChannelGUI NGSreformat uses perl scripts to reformat the output of shrimp  v2 in a form suitable to be uploaded on oneChannelGUI
#oneChannelGUI makeSam function is used to create a samtools for each bam generated by tophat
#oneChannelGUI dexCounts uses the dex python script to generate a count object. Uses the target generated by makeSam
#oneChannelGUI dexExons
#oneChannelGUI desGenes
#oneChannelGUI topTable.exons filtering and saving a topTable for exon-level analysis with dexseq
#oneChannelGUI topTable.genes filtering and saving a topTable for gene-level analysis with deseq
#openPdf, closePdf useful to open connection to pdf under linux system
#oneChannelGUI
#miRNAde uses wrapper to detect mature miRNAs
################################################################################
"miRNAbowtieRun" <-function(){
      Try(ptm <- proc.time())
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
      Try(etcDir  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/etc", sep=""))
      Try(localdata <- paste(etcDir, "/localData.txt", sep=""))
      Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
 #     Try(SetWD())
      Try(myWD <- getwd())
      if(is.na(myinfo[which(myinfo[,1]== "bowtieDirLocation"),2])){
           Try(tkmessageBox(title="Bowtie",message="Bowtie cannot be found please go to the General tool menu and use the function\nInstall Bowtie and Picard tools\nto install Bowtie.",icon="error",type="ok"))
           Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(return())
      }
      Try(setwd(myinfo[which(myinfo[,1]== "bowtieDirLocation"),2]))
      Try(data.in.dir <- dir())
      Try(data.in.dir <- data.in.dir[grep('_nc.ebwt$',data.in.dir)])
      Try(data.in.dir <- strsplit(data.in.dir, "\\."))
      Try(data.in.dir <- unique(sapply(data.in.dir, function(x) x[1])))
      Try(refnames <- paste(data.in.dir, seq(1, length(data.in.dir)), sep=" = ", collapse=", "))
      ##selecting the ref set for mapping
     #select ref genome 
     Try(ttGetGenomes <- tktoplevel(.affylmGUIglobals$ttMain))
     Try(tkwm.deiconify(ttGetGenomes))
     Try(tkgrab.set(ttGetGenomes))
     Try(tkfocus(ttGetGenomes))
     Try(tkwm.title(ttGetGenomes,"Which miRNA precursors set do you want to use as reference?"))
     Try(tkgrid(tklabel(ttGetGenomes,text="    ")))
     Try(ttGetGenomesTcl <- tclVar("hg19"))
     Try(rbIQR.hs <- tkradiobutton(ttGetGenomes,text="Human miRNA precursors", variable=ttGetGenomesTcl,value="hs_nc",font=.affylmGUIglobals$affylmGUIfont2))
     Try(rbIQR.mm<-tkradiobutton(ttGetGenomes,text="Mouse miRNA precursors", variable=ttGetGenomesTcl,value="mm_nc",font=.affylmGUIglobals$affylmGUIfont2))
     Try(rbIQR.rn<-tkradiobutton(ttGetGenomes,text="Rat miRNA precursors", variable=ttGetGenomesTcl,value="rn_nc",font=.affylmGUIglobals$affylmGUIfont2))
     Try(rbIQR.bo<-tkradiobutton(ttGetGenomes,text="Bovine miRNA precursors", variable=ttGetGenomesTcl,value="bo_nc",font=.affylmGUIglobals$affylmGUIfont2))
     
     Try(tkgrid(tklabel(ttGetGenomes,text="    "),rbIQR.hs))
     Try(tkgrid(tklabel(ttGetGenomes,text="    "),rbIQR.mm))
     Try(tkgrid(tklabel(ttGetGenomes,text="    "),rbIQR.rn))
     Try(tkgrid(tklabel(ttGetGenomes,text="    "),rbIQR.bo))

     Try(tkgrid.configure(rbIQR.hs,rbIQR.mm,rbIQR.rn, rbIQR.bo, columnspan=2,sticky="w"))
     Try(tkgrid(tklabel(ttGetGenomes,text="    "),tklabel(ttGetGenomes,text="    ")))
     Try(ReturnVal1 <- "")
     Try(onCancel <- function() {Try(ReturnVal1 <<- "");Try(tkgrab.release(ttGetGenomes));Try(tkdestroy(ttGetGenomes));Try(tkfocus(.affylmGUIglobals$ttMain))})
     Try(onOK <- function() {Try(ReturnVal1 <<- tclvalue(ttGetGenomesTcl));Try(tkgrab.release(ttGetGenomes));Try(tkdestroy(ttGetGenomes));Try(tkfocus(.affylmGUIglobals$ttMain))})
     Try(OK.but     <- tkbutton(ttGetGenomes,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
     Try(Cancel.but <- tkbutton(ttGetGenomes,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

     Try(tkgrid(tklabel(ttGetGenomes,text="    "),OK.but,Cancel.but, tklabel(ttGetGenomes,text="    ")))
     Try(tkgrid.configure(OK.but,sticky="e"))
     Try(tkgrid.configure(Cancel.but,sticky="w"))
     Try(tkgrid(tklabel(ttGetGenomes,text="    ")))

     Try(tkbind(ttGetGenomes,"<Destroy>",function() {ReturnVal1 <- "";Try(tkgrab.release(ttGetGenomes));Try(tkfocus(.affylmGUIglobals$ttMain));}))
     Try(tkbind(OK.but, "<Return>",onOK))
     Try(tkbind(Cancel.but, "<Return>",onCancel))      
     Try(tkwait.window(ttGetGenomes))
     Try(tkfocus(.affylmGUIglobals$ttMain))
     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
     Try(setwd(myWD))  #back again in the working dir
     
      #opening target for primary mapping
    	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
      Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	    Try(tkwm.deiconify(ttExonandTargets))
	    Try(tkgrab.set(ttExonandTargets))
	    Try(tkfocus(ttExonandTargets))
	    Try(tkwm.title(ttExonandTargets,"Targets file"))
      Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

	    OpenTargetsFileAndSetCursor <- function()
	   {
		   	Try(tkconfigure(ttExonandTargets,cursor="watch"))
			  Try(tkfocus(ttExonandTargets))
			  Try(OpenTargetsFile())
			  Try(tkconfigure(ttExonandTargets,cursor="arrow"))
			  Try(tkfocus(ttExonandTargets))
	   } 

	   Try(OpenTargetsFile.but <- tkbutton(ttExonandTargets, text="Select Targets File",command=OpenTargetsFile,font=.affylmGUIglobals$affylmGUIfont2))

	   Try(tclvalue(.affylmGUIglobals$TargetsfileName) <- fixSeps(tclvalue(.affylmGUIglobals$TargetsfileName)))
	   Try(TargetsfileBoxTitleLabel <- tklabel(ttExonandTargets,text=as.character(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle)),font=.affylmGUIglobals$affylmGUIfont2))
	   Try(TargetsfileNameLabel <- tklabel(ttExonandTargets,text=as.character(tclvalue(.affylmGUIglobals$TargetsfileName)),background="white",font=.affylmGUIglobals$affylmGUIfont2))
	   Try(tkconfigure(TargetsfileBoxTitleLabel, textvariable=.affylmGUIglobals$TargetsfileBoxTitle))
	   Try(tkconfigure(TargetsfileNameLabel, textvariable=.affylmGUIglobals$TargetsfileName))

	   Try(tkgrid(tklabel(ttExonandTargets,text="    ")))
	   Try(tkgrid(TargetsfileBoxTitleLabel,columnspan=4))
	   Try(tkgrid(TargetsfileNameLabel,columnspan=4))

	   Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

	   Try(tkgrid(tklabel(ttExonandTargets,text="    "),OpenTargetsFile.but))
	   Try(tkgrid.configure(OpenTargetsFile.but,columnspan=2))
	   Try(Abort <- 1)
	   onOK <- function()
	  {
			  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
			  Try(if(length(Targets)==0)
			  {
				   Try(tkmessageBox(title="NGS Targets File",message=paste("Either you did not specify a valid NGS Targets File",
					   "or an error occurred while reading in the Targets file.	It should be in tab-delimited text format and it should include the column headings \"FileName\", and \"Target\".",icon="error")))
				   onCancel()
			  })
			  Try(tkgrab.release(ttExonandTargets));
			  Try(tkdestroy(ttExonandTargets));
			  Try(tkfocus(.affylmGUIglobals$ttMain))
			  Try(Abort <<- 0)
	  }
	  onCancel <- function() {Try(tkgrab.release(ttExonandTargets));Try(tkdestroy(ttExonandTargets));Try(tkfocus(.affylmGUIglobals$ttMain));Try(Abort<<-1)}
	  Try(OK.but <-tkbutton(ttExonandTargets,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	  Try(Cancel.but <-tkbutton(ttExonandTargets,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
	  Try(tkgrid(tklabel(ttExonandTargets,text="    ")))
	  Try(tkgrid(tklabel(ttExonandTargets,text="    "),OK.but,Cancel.but))
	  Try(tkgrid(tklabel(ttExonandTargets,text="       ")))
	  Try(tkfocus(ttExonandTargets))
	  Try(tkbind(ttExonandTargets, "<Destroy>", function() {Try(tkgrab.release(ttExonandTargets));Try(tkfocus(.affylmGUIglobals$ttMain));}))
	  Try(tkwait.window(ttExonandTargets))
      
	  if(Abort==1)
				return(0)
	  Try(tkfocus(.affylmGUIglobals$ttMain))
	  Try(Targets <- get("Targets",affylmGUIenvironment))
	  Try(Targets.sam <- Targets)
	  #make a bam file
    Try(javaDir <- get("javaDir",envir=affylmGUIenvironment))
    if(is.na(javaDir)){javaDir <- ""}
    if(javaDir != ""){
          Try(picardLoc <- paste('"',javaDir,'"', "/bin/java -jar ",myinfo[which(myinfo[,1]== "bowtieDirLocation"),2], "/SamFormatConverter.jar", sep=""))

    }else{
          Try(picardLoc <- paste("java -jar ",myinfo[which(myinfo[,1]== "bowtieDirLocation"),2], "/SamFormatConverter.jar", sep=""))
    }
    Try(refGenome <- paste(myinfo[which(myinfo[,1]== "bowtieDirLocation"),2],ReturnVal1,sep="/"))
    #defining bowtie params#####################################################
    Try(botwieParams<-tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.deiconify(botwieParams))
    Try(tkgrab.set(botwieParams))
    Try(tkfocus(botwieParams))
    Try(tkwm.title(botwieParams,"Bowtie parameters"))
    Try(tkgrid(tklabel(botwieParams,text="    ")))

    Try(frame1 <- tkframe(botwieParams,relief="groove",borderwidth=2))
    Try(HowManyQuestion1 <- tklabel(frame1,text="Number of allowed mismatches",font=.affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(HowManyQuestion1))
    Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
    Try(thresholdTcl <- tclVar("1"))
    Try(I0.but  <- tkradiobutton(frame1,text="1",variable=thresholdTcl,value="1",font=.affylmGUIglobals$affylmGUIfont2))
    Try(I1.but  <- tkradiobutton(frame1,text="2",variable=thresholdTcl,value="2",font=.affylmGUIglobals$affylmGUIfont2))
    Try(I2.but  <- tkradiobutton(frame1,text="3",variable=thresholdTcl,value="3",font=.affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(I0.but,sticky="w"))
    Try(tkgrid(I1.but,sticky="w"))
    Try(tkgrid(I2.but,sticky="w"))

    Try(tkgrid.configure(HowManyQuestion1,I0.but,I1.but,I2.but,sticky="w"))

    Try(frame2 <- tkframe(botwieParams,relief="groove",borderwidth=2))
    Try(fractionLabel <- tklabel(frame2,text="Input data type",font=.affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(fractionLabel,sticky="w"))
    Try(tkgrid.configure(fractionLabel,sticky="w"))
    Try(fractionTcl <- tclVar("-q"))
    Try(F1.but <- tkradiobutton(frame2,text="FASTQ",variable=fractionTcl,value="-q",font=.affylmGUIglobals$affylmGUIfont2))

    Try(tkgrid(F1.but,sticky="w"))
    Try(tkgrid.configure(fractionLabel,F1.but,sticky="w"))

    Try(onOK <- function()
    {
                            bowtieVal1 <- tclvalue(thresholdTcl)
                            bowtieVal2 <- tclvalue(fractionTcl)
                            Try(bowtieVal <<- paste(bowtieVal1, bowtieVal2, sep=";"))
                            Try(tkgrab.release(botwieParams))
                            Try(tkdestroy(botwieParams))
                            Try(tkfocus(.affylmGUIglobals$ttMain))
    })

    Try(frame3 <- tkframe(botwieParams,borderwidth=2))
    Try(onCancel <- function() {Try(bowtieVal <<- ""); Try(tkgrab.release(botwieParams));Try(tkdestroy(botwieParams));Try(tkfocus(.affylmGUIglobals$ttMain))})
    Try(OK.but <-tkbutton(frame3,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
    Try(Cancel.but <-tkbutton(frame3,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

    Try(tkgrid(tklabel(frame3,text="    "),OK.but,Cancel.but,tklabel(frame3,text="    ")))

    Try(tkgrid(tklabel(botwieParams,text="    "),frame1,frame2,tklabel(botwieParams,text="  ")))
    Try(tkgrid(tklabel(botwieParams,text="    ")))
    Try(tkgrid(tklabel(botwieParams,text="    "),frame3,tklabel(botwieParams,text="  ")))
    Try(tkgrid(tklabel(botwieParams,text="    ")))
    Try(tkgrid.configure(frame1,frame3,sticky="w"))

    Try(tkfocus(botwieParams))
    Try(tkbind(botwieParams, "<Destroy>", function() {Try(tkgrab.release(botwieParams));Try(tkfocus(.affylmGUIglobals$ttMain));}))
                       Try(tkwait.window(botwieParams))
    Try(if(bowtieVal==""){return()} )
    Try(tmp <-strsplit(bowtieVal, ";"))
    Try(mismatch <- as.numeric(tmp[[1]][1]))
    Try(data.type <- tmp[[1]][2])
    ############################################################################
    for (i in 1: dim(Targets)[1]){
	  Try(outputSam <- paste(getwd(),paste(Targets$FileName[i],".sam", sep=""),sep="/"))
	  Try(inputData <- paste(getwd(),Targets$FileName[i],sep="/"))
      Try(cat("Processing: ", Targets$FileName[i],"\n"))
      Try(Targets.sam$FileName[i]<-paste(Targets$FileName[i],".bam", sep=""))
      if(.Platform$OS.type=="windows"){
            Try(bowtieLoc <- paste(myinfo[which(myinfo[,1]== "bowtieDirLocation"),2],"/bowtie.exe -a --best -k 1 -q -v 1 -S", sep=""))
            Try(system(paste(bowtieLoc,refGenome,inputData, outputSam, sep=" ")))
            Try(system(paste(picardLoc, " I=",outputSam, " O=", sub("sam$","bam", outputSam), sep="")))
            Try(file.remove(outputSam)) 
          # bowtie.exe -a -m 1 -q -v 1 -S chr1 tmp.fq tmp.out.sam
     } else if(.Platform$OS.type!="windows"){
            Try(bowtieLoc <- paste(myinfo[which(myinfo[,1]== "bowtieDirLocation"),2],"/bowtie -a --best -k 1 -q -v 1 -S", sep=""))
            Try(system(paste(bowtieLoc,refGenome,inputData, outputSam, sep=" ")))
            Try(system(paste(picardLoc, " I=",outputSam, " O=", sub("sam$","bam", outputSam), sep=""))) 
            Try(file.remove(outputSam))
     }
   }
     Try(newfilename <- paste("target", gsub(" ", "_",date()),"_sam.txt",sep=""))
     Try(newfilename <- gsub("\\:", "-",newfilename))
     
     Try(write.table(Targets.sam, newfilename, row.names=F, quote = F, sep="\t"))
     Try(tkmessageBox(title="Bowtie primary mapping",message=paste("Bowtie primary mapping is finished.\nBAM files are available in",getwd(),"The target file to load bam files in oneChannelGUI is",newfilename, sep="\n"),type="ok"))
     Try(usedtime <- proc.time() - ptm)
     Try(cat("\nUsed CPU time (min) ",usedtime[3]/60,"\n"))
     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
     Try(tkfocus(.affylmGUIglobals$ttMain))

}
################################################################################
"NGSreformat" <- function(){
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(ptm <- proc.time())
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  Try(perlDirLocation <- get("perlDirLocation",envir=affylmGUIenvironment))
  Try(perl.info <- "")
  Try(perl.info <- system("perl -v", intern=T))
  
  if(length(grep("perl", perl.info)) == 0){
      Try(tkmessageBox(title="Perl program",message="Perl program is not installed!",type="ok", icon="error"))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(return())
  }
  #load target
  Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttExonandTargets))
	Try(tkgrab.set(ttExonandTargets))
	Try(tkfocus(ttExonandTargets))
	Try(tkwm.title(ttExonandTargets,"Targets file"))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

	OpenTargetsFileAndSetCursor <- function()
	{
			Try(tkconfigure(ttExonandTargets,cursor="watch"))
			Try(tkfocus(ttExonandTargets))
			Try(OpenTargetsFile())
			Try(tkconfigure(ttExonandTargets,cursor="arrow"))
			Try(tkfocus(ttExonandTargets))
	}

	Try(OpenTargetsFile.but <- tkbutton(ttExonandTargets, text="Select Targets File",command=OpenTargetsFile,font=.affylmGUIglobals$affylmGUIfont2))

	Try(tclvalue(.affylmGUIglobals$TargetsfileName) <- fixSeps(tclvalue(.affylmGUIglobals$TargetsfileName)))
	Try(TargetsfileBoxTitleLabel <- tklabel(ttExonandTargets,text=as.character(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle)),font=.affylmGUIglobals$affylmGUIfont2))
	Try(TargetsfileNameLabel <- tklabel(ttExonandTargets,text=as.character(tclvalue(.affylmGUIglobals$TargetsfileName)),background="white",font=.affylmGUIglobals$affylmGUIfont2))
	Try(tkconfigure(TargetsfileBoxTitleLabel, textvariable=.affylmGUIglobals$TargetsfileBoxTitle))
	Try(tkconfigure(TargetsfileNameLabel, textvariable=.affylmGUIglobals$TargetsfileName))

	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))
	Try(tkgrid(TargetsfileBoxTitleLabel,columnspan=4))
	Try(tkgrid(TargetsfileNameLabel,columnspan=4))

	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

	Try(tkgrid(tklabel(ttExonandTargets,text="    "),OpenTargetsFile.but))
	Try(tkgrid.configure(OpenTargetsFile.but,columnspan=2))
	Try(Abort <- 1)
	onOK <- function()
	{
			Try(Targets <- get("Targets",envir=affylmGUIenvironment))
			Try(if(length(Targets)==0)
			{
				Try(tkmessageBox(title="NGS Targets File",message=paste("Either you did not specify a valid NGS Targets File",
					"or an error occurred while reading in the Targets file.	It should be in tab-delimited text format and it should include the column headings \"FileName\", and \"Target\".",icon="error")))
				onCancel()
#				return()
			})
			Try(tkgrab.release(ttExonandTargets));
			Try(tkdestroy(ttExonandTargets));
			Try(tkfocus(.affylmGUIglobals$ttMain))
			Try(Abort <<- 0)
	}
	onCancel <- function() {Try(tkgrab.release(ttExonandTargets));Try(tkdestroy(ttExonandTargets));Try(tkfocus(.affylmGUIglobals$ttMain));Try(Abort<<-1)}
	Try(OK.but <-tkbutton(ttExonandTargets,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	Try(Cancel.but <-tkbutton(ttExonandTargets,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))
	Try(tkgrid(tklabel(ttExonandTargets,text="    "),OK.but,Cancel.but))
	Try(tkgrid(tklabel(ttExonandTargets,text="       ")))
	Try(tkfocus(ttExonandTargets))
	Try(tkbind(ttExonandTargets, "<Destroy>", function() {Try(tkgrab.release(ttExonandTargets));Try(tkfocus(.affylmGUIglobals$ttMain));}))
	Try(tkwait.window(ttExonandTargets))

	if(Abort==1)
				return(0)
  
	Try(Targets <- get("Targets",affylmGUIenvironment))
	Try(slides <- Targets$FileName)
	
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  Try(target.array.names <- sub(".CEL", "", tmp1.pd$FileName))
  Try(target.array.names <- paste(tmp1.pd$FileName, ".bed", sep=""))   #giving the extension filename of counts data produced reformatting the output of shrimp
  #NGS reads number and reformatting Tartget in Targets #######################
  Try(tmpTarget <- Targets$Target)
  Try(tmpTarget <- strsplit(tmpTarget, "_"))
  Try(newTarget <- sapply(tmpTarget, function(x)x[1]))
  Try(Targets$Target <- newTarget)
  Try(rownames(Targets) <- NULL)
  Try(assign("Targets",Targets,envir=affylmGUIenvironment))
  Try(totalReads <- sapply(tmpTarget, function(x)x[2]))
  Try(mappedReads <- sapply(tmpTarget, function(x)x[3]))
  Try(assign("totalReads", as.numeric(totalReads),envir=affylmGUIenvironment))
  Try(assign("mappedReads", as.numeric(mappedReads),envir=affylmGUIenvironment))
  
   ###########     
   Try(Targets <- get("Targets",envir=affylmGUIenvironment))
   #defining the the type of input of mapped NGS data
   Try(ttGetNGSinput <- tktoplevel(.affylmGUIglobals$ttMain))
   Try(tkwm.deiconify(ttGetNGSinput))
   Try(tkgrab.set(ttGetNGSinput))
   Try(tkfocus(ttGetNGSinput))
   Try(tkwm.title(ttGetNGSinput,"Selecting Type of NGS input data"))
   #
   Try(tkgrid(tklabel(ttGetNGSinput,text="    ")))
   Try(NGSinputTcl <- tclVar("SHRIMP"))
   Try(rbA <- tkradiobutton(ttGetNGSinput,text="SHRIMP output",variable=NGSinputTcl,value="SHRIMP",font=.affylmGUIglobals$affylmGUIfont2))
   Try(rbB <- tkradiobutton(ttGetNGSinput,text="mature miRNAs from miRanalyser",variable=NGSinputTcl,value="miRanalyser",font=.affylmGUIglobals$affylmGUIfont2))
	 Try(rbC <- tkradiobutton(ttGetNGSinput,text="mature miRNAs from MicroRazerS",variable=NGSinputTcl,value="MicroRazerS",font=.affylmGUIglobals$affylmGUIfont2))
        
   Try(tkgrid(tklabel(ttGetNGSinput,text="    "),rbA))
   Try(tkgrid(tklabel(ttGetNGSinput,text="    "),rbB))
   Try(tkgrid(tklabel(ttGetNGSinput,text="    "),rbC))
      
 	 Try(tkgrid.configure(rbA,rbB, rbC, columnspan=2,sticky="w"))
 	 Try(tkgrid(tklabel(ttGetNGSinput,text="    "),tklabel(ttGetNGSinput,text="    ")))
	 #
	 Try(ReturnNGSinput <- "")
	 Try(
		         onCancel <- function() {
			          Try(ReturnNGSinput <<- "");
			          Try(tkgrab.release(ttGetNGSinput));
			          Try(tkdestroy(ttGetNGSinput));
			          Try(tkfocus(.affylmGUIglobals$ttMain))
		        }
	 )
	 Try(
		       onOK <- function() {
			         Try(ReturnNGSinput <<- tclvalue(NGSinputTcl));
			         Try(tkgrab.release(ttGetNGSinput));
			         Try(tkdestroy(ttGetNGSinput));
			         Try(tkfocus(.affylmGUIglobals$ttMain))
		      }
	 )
   #
	 Try(OK.but     <- tkbutton(ttGetNGSinput,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	 Try(Cancel.but <- tkbutton(ttGetNGSinput,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
	 #
	 Try(tkgrid(tklabel(ttGetNGSinput,text="    "),OK.but,Cancel.but,tklabel(ttGetNGSinput,text="    ")))
	 Try(tkgrid.configure(OK.but,sticky="e"))
	 Try(tkgrid.configure(Cancel.but,sticky="w"))
	 Try(tkgrid(tklabel(ttGetNGSinput,text="    ")))
	 #
	 Try(tkbind(ttGetNGSinput,"<Destroy>",function() {ReturnNGSinput <- "";Try(tkgrab.release(ttGetNGSinput));Try(tkfocus(.affylmGUIglobals$ttMain));}))
	 Try(tkbind(OK.but, "<Return>",onOK))
	 Try(tkbind(Cancel.but, "<Return>",onCancel))
	 #
	 Try(tkwait.window(ttGetNGSinput))
   if(ReturnNGSinput == "SHRIMP"){
       #which organism
       Try(ttGetOrganism <- tktoplevel(.affylmGUIglobals$ttMain))
	     Try(tkwm.deiconify(ttGetOrganism))
       Try(tkgrab.set(ttGetOrganism))
       Try(tkfocus(ttGetOrganism))
       Try(tkwm.title(ttGetOrganism,"Which organism"))
	
 	     Try(tkgrid(tklabel(ttGetOrganism,text="    ")))
       Try(ttGetOrganismTcl <- tclVar("hs"))
       Try(rbIQR.5 <- tkradiobutton(ttGetOrganism,text="H. sapiens",variable=ttGetOrganismTcl,value="hs",font=.affylmGUIglobals$affylmGUIfont2))
       Try(rbIQR.25<-tkradiobutton(ttGetOrganism,text="M. musculus",variable=ttGetOrganismTcl,value="mm",font=.affylmGUIglobals$affylmGUIfont2))
       Try(rbIQR.50<-tkradiobutton(ttGetOrganism,text="oneChannelGUI miRbase precursors",variable=ttGetOrganismTcl,value="mirbase",font=.affylmGUIglobals$affylmGUIfont2))
       Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.5))
	     Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.25))
	     Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.50))

	     Try(tkgrid.configure(rbIQR.5,rbIQR.25, rbIQR.50,columnspan=2,sticky="w"))
	     Try(tkgrid(tklabel(ttGetOrganism,text="    "),tklabel(ttGetOrganism,text="    ")))
       Try(ReturnVal <- "")
       Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGetOrganism));Try(tkdestroy(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain))})
       Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGetOrganismTcl));Try(tkgrab.release(ttGetOrganism));Try(tkdestroy(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain))})
       Try(OK.but     <- tkbutton(ttGetOrganism,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
       Try(Cancel.but <- tkbutton(ttGetOrganism,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

	     Try(tkgrid(tklabel(ttGetOrganism,text="    "),OK.but,Cancel.but, tklabel(ttGetOrganism,text="    ")))
       Try(tkgrid.configure(OK.but,sticky="e"))
	     Try(tkgrid.configure(Cancel.but,sticky="w"))
	     Try(tkgrid(tklabel(ttGetOrganism,text="    ")))

       Try(tkbind(ttGetOrganism,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain));}))
       Try(tkbind(OK.but, "<Return>",onOK))
       Try(tkbind(Cancel.but, "<Return>",onCancel))      
       Try(tkwait.window(ttGetOrganism))
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  
       if(ReturnVal == ""){
            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
            Try(return())
       } else if (ReturnVal == "hs"){
             Try(cat("Be patient!!!!.....\n"))
             Try(cat("reformatting data aligned using H. sapiens as reference\n"))
             for(i in Targets$FileName){
                Try(cat("Processing ", i,"\n"))
                Try(system(paste("perl", paste(perlDirLocation, "/shrimpENSEMBL2genominator.hs.pl", sep=""), i, sep=" ")))
            }
       } else if (ReturnVal == "mm"){
             Try(cat("Be patient!!!!.....\n"))
             Try(cat("reformatting data aligned using M. musculus as reference genome\n"))
             for(i in Targets$FileName){
                Try(cat("Processing ", i,"\n"))
                Try(system(paste("perl", paste(perlDirLocation, "/shrimpENSEMBL2genominator.mm.pl", sep=""), i, sep=" ")))
            }
       } else if (ReturnVal == "mirbase"){
             Try(cat("Be patient!!!!.....\n"))
             Try(cat("reformatting data aligned using the miRbase precursors, generated using oneChannelGUI \nExport miRbase fasta reference file for microRNA-seq quantitative analysis function,\nas reference\n"))
             for(i in Targets$FileName){
                Try(cat("Processing ", i,"\n"))
                Try(system(paste("perl", paste(perlDirLocation, "/shrimpENSEMBL2genominator.mirbase.pl", sep=""), i, sep=" ")))
            }
       } 
    } else if(ReturnNGSinput == "MicroRazerS"){
       #which organism
       Try(ttGetOrganism <- tktoplevel(.affylmGUIglobals$ttMain))
	     Try(tkwm.deiconify(ttGetOrganism))
       Try(tkgrab.set(ttGetOrganism))
       Try(tkfocus(ttGetOrganism))
       Try(tkwm.title(ttGetOrganism,"Which organism"))
	
 	     Try(tkgrid(tklabel(ttGetOrganism,text="    ")))
       Try(ttGetOrganismTcl <- tclVar("hs"))
       Try(rbIQR.5 <- tkradiobutton(ttGetOrganism,text="H. sapiens",variable=ttGetOrganismTcl,value="hs",font=.affylmGUIglobals$affylmGUIfont2))
       Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.5))

	     Try(tkgrid.configure(rbIQR.5, columnspan=2,sticky="w"))
	     Try(tkgrid(tklabel(ttGetOrganism,text="    "),tklabel(ttGetOrganism,text="    ")))
       Try(ReturnVal <- "")
       Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGetOrganism));Try(tkdestroy(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain))})
       Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGetOrganismTcl));Try(tkgrab.release(ttGetOrganism));Try(tkdestroy(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain))})
       Try(OK.but     <- tkbutton(ttGetOrganism,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
       Try(Cancel.but <- tkbutton(ttGetOrganism,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

	     Try(tkgrid(tklabel(ttGetOrganism,text="    "),OK.but,Cancel.but, tklabel(ttGetOrganism,text="    ")))
       Try(tkgrid.configure(OK.but,sticky="e"))
	     Try(tkgrid.configure(Cancel.but,sticky="w"))
	     Try(tkgrid(tklabel(ttGetOrganism,text="    ")))

       Try(tkbind(ttGetOrganism,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain));}))
       Try(tkbind(OK.but, "<Return>",onOK))
       Try(tkbind(Cancel.but, "<Return>",onCancel))      
       Try(tkwait.window(ttGetOrganism))
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  
       if(ReturnVal == ""){
            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
             Try(tkfocus(.affylmGUIglobals$ttMain))
            Try(return())
       } else if (ReturnVal == "hs"){
             Try(cat("Be patient!!!!.....\n"))
             Try(cat("reformatting data aligned using H. sapiens as reference genome\n"))
             for(i in Targets$FileName){
                Try(cat("Processing ", i,"\n"))
                Try(system(paste("perl", paste(perlDirLocation, "/MicroRazerSENSEMBL2genominator.hs.pl", sep=""), i, sep=" ")))
            }
       }
    } else if(ReturnNGSinput == "miRanalyser"){
              Try(tkmessageBox(title="NGS data reformatting",message="Tab delimited files for mature miRNAs produced by miRanalyser can be directly loaded on oneChannelGUI without reformatting."))
    }
    Try(usedtime <- proc.time() - ptm)
    Try(cat("\nUsed CPU time (min) ",usedtime[3]/60,"\n"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
     Try(tkfocus(.affylmGUIglobals$ttMain))
}
################################################################################
"adaptorTrimm" <-function(){
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(SetWD())
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  Try(perlDirLocation <- get("perlDirLocation",envir=affylmGUIenvironment))
  Try(perl.info <- "")
  Try(perl.info <- system("perl -v", intern=T))
  
  if(length(grep("perl", perl.info)) == 0){
      Try(tkmessageBox(title="Perl program",message="Perl program is not installed!",type="ok", icon="error"))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(return())
  }
  #load target
  Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttExonandTargets))
	Try(tkgrab.set(ttExonandTargets))
	Try(tkfocus(ttExonandTargets))
	Try(tkwm.title(ttExonandTargets,"Targets file"))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

	OpenTargetsFileAndSetCursor <- function()
	{
			Try(tkconfigure(ttExonandTargets,cursor="watch"))
			Try(tkfocus(ttExonandTargets))
			Try(OpenTargetsFile())
			Try(tkconfigure(ttExonandTargets,cursor="arrow"))
			Try(tkfocus(ttExonandTargets))
	}

	Try(OpenTargetsFile.but <- tkbutton(ttExonandTargets, text="Select Targets File",command=OpenTargetsFile,font=.affylmGUIglobals$affylmGUIfont2))

	Try(tclvalue(.affylmGUIglobals$TargetsfileName) <- fixSeps(tclvalue(.affylmGUIglobals$TargetsfileName)))
	Try(TargetsfileBoxTitleLabel <- tklabel(ttExonandTargets,text=as.character(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle)),font=.affylmGUIglobals$affylmGUIfont2))
	Try(TargetsfileNameLabel <- tklabel(ttExonandTargets,text=as.character(tclvalue(.affylmGUIglobals$TargetsfileName)),background="white",font=.affylmGUIglobals$affylmGUIfont2))
	Try(tkconfigure(TargetsfileBoxTitleLabel, textvariable=.affylmGUIglobals$TargetsfileBoxTitle))
	Try(tkconfigure(TargetsfileNameLabel, textvariable=.affylmGUIglobals$TargetsfileName))

	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))
	Try(tkgrid(TargetsfileBoxTitleLabel,columnspan=4))
	Try(tkgrid(TargetsfileNameLabel,columnspan=4))

	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

	Try(tkgrid(tklabel(ttExonandTargets,text="    "),OpenTargetsFile.but))
	Try(tkgrid.configure(OpenTargetsFile.but,columnspan=2))
	Try(Abort <- 1)
	onOK <- function()
	{
			Try(Targets <- get("Targets",envir=affylmGUIenvironment))
			Try(if(length(Targets)==0)
			{
				Try(tkmessageBox(title="NGS Targets File",message=paste("Either you did not specify a valid NGS Targets File",
					"or an error occurred while reading in the Targets file.	It should be in tab-delimited text format and it should include the column headings \"FileName\", and \"Target\".",icon="error")))
				onCancel()
#				return()
			})
			Try(tkgrab.release(ttExonandTargets));
			Try(tkdestroy(ttExonandTargets));
			Try(tkfocus(.affylmGUIglobals$ttMain))
			Try(Abort <<- 0)
	}
	onCancel <- function() {Try(tkgrab.release(ttExonandTargets));Try(tkdestroy(ttExonandTargets));Try(tkfocus(.affylmGUIglobals$ttMain));Try(Abort<<-1)}
	Try(OK.but <-tkbutton(ttExonandTargets,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	Try(Cancel.but <-tkbutton(ttExonandTargets,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))
	Try(tkgrid(tklabel(ttExonandTargets,text="    "),OK.but,Cancel.but))
	Try(tkgrid(tklabel(ttExonandTargets,text="       ")))
	Try(tkfocus(ttExonandTargets))
	Try(tkbind(ttExonandTargets, "<Destroy>", function() {Try(tkgrab.release(ttExonandTargets));Try(tkfocus(.affylmGUIglobals$ttMain));}))
	Try(tkwait.window(ttExonandTargets))

	if(Abort==1)
				return(0)
  
	Try(Targets <- get("Targets",affylmGUIenvironment))
	Try(slides <- Targets$FileName)
	
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  Try(target.array.names <- sub(".CEL", "", tmp1.pd$FileName))
  Try(target.array.names <- paste(tmp1.pd$FileName, ".bed", sep=""))   #giving the extension filename of counts data produced reformatting the output of shrimp
  #NGS reads number and reformatting Tartget in Targets #######################
  Try(tmpTarget <- Targets$Target)
  Try(tmpTarget <- strsplit(tmpTarget, "_"))
  Try(newTarget <- sapply(tmpTarget, function(x)x[1]))
  Try(Targets$Target <- newTarget)
  Try(rownames(Targets) <- NULL)
  Try(assign("Targets",Targets,envir=affylmGUIenvironment))
  Try(cat("Be patient!!!!.....\n"))
  Try(cat("Trimming 3,5 end linkers\n"))
  Try(tmp.file <- tempfile("trimming_stats", fileext=".pdf", tmpdir=getwd()))
  Try(tmp.file <- paste("trimming_stats", gsub(" ", "_",date()),".pdf",sep=""))
  Try(tmp.file <- gsub("\\:", "-",tmp.file))
  Try(pdf(tmp.file))
  for(i in Targets$FileName){
     Try(ptm <- proc.time())
     Try(file.copy(i, "tmp.fq"))
     Try(cat("Processing ", i,"\t"))
     #syntax in  Adapter_trim.pl
     Try(system(paste("perl", paste(perlDirLocation, "Adapter_trimCRA.pl -i ",paste(getwd(),"/",i, " -o ",sep=""), paste(getwd(),"/",i, "trim.fq ",sep=""), "-f 4 -q 1" , sep=""), sep=" ")))
     Try(mytime <- as.numeric(unlist(proc.time() - ptm)))
     Try(mytime <- mytime[3]/60)
     Try(cat(mytime," mins\n"))
     Try(tmp.hist <- read.table(paste(getwd(),"/",i, ".triml",sep=""), sep="\t", header=F, as.is=T))
     Try(par(mfrow=c(1,2)))
     Try(hist(tmp.hist[,1], main=paste("3' end trimming", i, sep="\n"), xlab="trimmed nts"))
     Try(hist(tmp.hist[,2], main=paste("5' end trimming", i, sep="\n"), xlab="trimmed nts"))
  }
  Try(dev.off())
  Try(tmp.trimmed <- paste(Targets$FileName, "trim.fq", sep=""))
  Try(Targets$FileName <- tmp.trimmed)
  Try(target.trimmed <- strsplit(tmp.file, "trimming_stats"))
  Try(trimming.stats <- paste("trimming_stats", as.character(unlist(target.trimmed))[2], sep="")) 
  Try(target.trimmed <- paste("target", as.character(unlist(target.trimmed))[2], sep=""))
  Try(target.trimmed <- sub(".pdf", ".txt", target.trimmed))
  Try(write.table(Targets,  target.trimmed, sep="\t", quote=FALSE, row.names=FALSE))
  Try(tkmessageBox(title="Trimming Statistics",message=paste("Trimming statistics are saved in",trimming.stats, "\nThe target file for Bowtie mapping is ", target.trimmed),type="ok", icon="info"))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkfocus(.affylmGUIglobals$ttMain))
}
################################################################################
"mRNAbowtieRun" <-function(){
      Try(ptm <- proc.time())
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
     #select ref genome 
     Try(ttGetGenomes <- tktoplevel(.affylmGUIglobals$ttMain))
     Try(tkwm.deiconify(ttGetGenomes))
     Try(tkgrab.set(ttGetGenomes))
     Try(tkfocus(ttGetGenomes))
     Try(tkwm.title(ttGetGenomes,"Which genome do you want to use as reference?"))
     Try(tkgrid(tklabel(ttGetGenomes,text="    ")))
     Try(ttGetGenomesTcl <- tclVar("hg19"))
     Try(rbIQR.hs <- tkradiobutton(ttGetGenomes,text="Human hg19 genome       ",variable=ttGetGenomesTcl,value="hg19",font=.affylmGUIglobals$affylmGUIfont2))
     Try(rbIQR.mm<-tkradiobutton(ttGetGenomes,text="Mouse mm9 genome          ",variable=ttGetGenomesTcl,value="mm9",font=.affylmGUIglobals$affylmGUIfont2))
     Try(rbIQR.rn<-tkradiobutton(ttGetGenomes,text="Rat rn4 genome            ",variable=ttGetGenomesTcl,value="rn4",font=.affylmGUIglobals$affylmGUIfont2))
     
     Try(tkgrid(tklabel(ttGetGenomes,text="    "),rbIQR.hs))
     Try(tkgrid(tklabel(ttGetGenomes,text="    "),rbIQR.mm))
     Try(tkgrid(tklabel(ttGetGenomes,text="    "),rbIQR.rn))

     Try(tkgrid.configure(rbIQR.hs,rbIQR.mm,rbIQR.rn, columnspan=2,sticky="w"))
     Try(tkgrid(tklabel(ttGetGenomes,text="    "),tklabel(ttGetGenomes,text="    ")))
     Try(ReturnVal1 <- "")
     Try(onCancel <- function() {Try(ReturnVal1 <<- "");Try(tkgrab.release(ttGetGenomes));Try(tkdestroy(ttGetGenomes));Try(tkfocus(.affylmGUIglobals$ttMain))})
     Try(onOK <- function() {Try(ReturnVal1 <<- tclvalue(ttGetGenomesTcl));Try(tkgrab.release(ttGetGenomes));Try(tkdestroy(ttGetGenomes));Try(tkfocus(.affylmGUIglobals$ttMain))})
     Try(OK.but     <- tkbutton(ttGetGenomes,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
     Try(Cancel.but <- tkbutton(ttGetGenomes,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

     Try(tkgrid(tklabel(ttGetGenomes,text="    "),OK.but,Cancel.but, tklabel(ttGetGenomes,text="    ")))
     Try(tkgrid.configure(OK.but,sticky="e"))
     Try(tkgrid.configure(Cancel.but,sticky="w"))
     Try(tkgrid(tklabel(ttGetGenomes,text="    ")))

     Try(tkbind(ttGetGenomes,"<Destroy>",function() {ReturnVal1 <- "";Try(tkgrab.release(ttGetGenomes));Try(tkfocus(.affylmGUIglobals$ttMain));}))
     Try(tkbind(OK.but, "<Return>",onOK))
     Try(tkbind(Cancel.but, "<Return>",onCancel))      
     Try(tkwait.window(ttGetGenomes))
     Try(cat("\nBe patient! mapping will take a while...\n"))
     Try(bowtieRefs <- get("bowtieRefs",envir=affylmGUIenvironment))
     Try(installed <- bowtieRefs[which(names(bowtieRefs)==ReturnVal1)]) #checking ofr the presence of the buld ref
     if(is.na(installed)){
         Try(cat(paste("\nMissing ", ReturnVal1, " reference genome! Please use the function:\nDownload and build hs, mm, rn bowtie reference sets\nto install it.", sep="")))
         Try(return())
     }else{
            if(names(installed)=="hg19"){
               Try(refG <- "hs_chr")
            }else if(names(installed)=="mm9"){
               Try(refG <- "mm_chr")
            }else if(names(installed)=="rn4"){
               Try(refG <- "rn_chr")
            }
     }
      Try(etcDir  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/etc", sep=""))
      Try(localdata <- paste(etcDir, "/localData.txt", sep=""))
      Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
  #    Try(SetWD())
      Try(myWD <- getwd())
      if(is.na(myinfo[which(myinfo[,1]== "bowtieDirLocation"),2])){
           Try(tkmessageBox(title="Bowtie",message="Bowtie cannot be found please go to the General tool menu and use the function\nInstall Bowtie and Picard tools\nto install Bowtie.",icon="error",type="ok"))
           Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(return())
      }
      Try(setwd(myinfo[which(myinfo[,1]== "bowtieDirLocation"),2]))
      
      Try(data.in.dir <- dir())
      Try(data.in.dir <- data.in.dir[grep('.ebwt$',data.in.dir)])
      Try(myrefid <- paste('^', refG,sep=""))
      Try(data.in.dir <- data.in.dir[grep(myrefid,data.in.dir)])
      Try(data.in.dir <- strsplit(data.in.dir, "\\."))
      Try(data.in.dir <- unique(sapply(data.in.dir, function(x) x[1])))
      Try(refnames <- paste(paste(data.in.dir[1:trunc(length(data.in.dir)/2)], seq(1, trunc(length(data.in.dir)/2)), sep=" = ", collapse=", "), paste(data.in.dir[(trunc(length(data.in.dir)/2)+1):length(data.in.dir)], seq((trunc(length(data.in.dir)/2)+1), length(data.in.dir)), sep=" = ", collapse=", "),sep="\n"))
      ##selecting the ref set for mapping  I.E. selecting the chromosome for the mapping
      Try(ttcolExtract<-tktoplevel(.affylmGUIglobals$ttMain))
      Try(tkwm.deiconify(ttcolExtract))
      Try(tkgrab.set(ttcolExtract))
      Try(tkfocus(ttcolExtract))
      Try(tkwm.title(ttcolExtract,"Defining the reference set to be used for bowtie mapping"))
      Try(tkgrid(tklabel(ttcolExtract,text="    ")))
      Try(refBowtie <- "")
      Try(Local.colExtract <- tclVar(init=refBowtie))
      Try(entry.colExtract <-tkentry(ttcolExtract,width="4",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.colExtract,bg="white"))
      Try(tkgrid(tklabel(ttcolExtract,text=paste("Please enter the number associated to the reference set of interest\n", refnames),font=.affylmGUIglobals$affylmGUIfont2)))
      Try(tkgrid(entry.colExtract))
      onOK <- function()
      {
                     Try(assign("refBowtie", as.numeric(tclvalue(Local.colExtract)),affylmGUIenvironment))
                     Try(tkgrab.release(ttcolExtract));Try(tkdestroy(ttcolExtract));Try(tkfocus(.affylmGUIglobals$ttMain))                        
      }
      Try(OK.but <-tkbutton(ttcolExtract,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
      Try(tkgrid(tklabel(ttcolExtract,text="    ")))
      Try(tkgrid(OK.but))
      Try(tkgrid.configure(OK.but))
      Try(tkgrid(tklabel(ttcolExtract,text="       ")))
      Try(tkfocus(entry.colExtract))
      Try(tkbind(entry.colExtract, "<Return>",onOK))
      Try(tkbind(ttcolExtract, "<Destroy>", function(){Try(tkgrab.release(ttcolExtract));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
      Try(tkwait.window(ttcolExtract))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(refBowtie <- get("refBowtie", affylmGUIenvironment))
      if(is.na(refBowtie)){
                         Try(tkmessageBox(title="Defining the reference set to be used for bowtie mapping",message="You have not selected any reference set!\nIf you are interested to other references sequences other than miRNA precursors, you need to download them with the function:\nDownload bowtie built reference sets\navailable in General tools menu."))
                         Try(tkfocus(.affylmGUIglobals$ttMain))
                         Try(return())
      } else if(refBowtie > length(data.in.dir)){
                         Try(tkmessageBox(title="Defining the reference set to be used for bowtie mapping",message="You have selected a non existing reference set!"))
                         Try(tkfocus(.affylmGUIglobals$ttMain))
                         Try(return())
      }
      Try(tkmessageBox(title="Defining the reference set to be used for bowtie mapping",message=paste("You have selected", data.in.dir[refBowtie],"as reference set for bowtie mapping.", sep=" ")))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(setwd(myWD))  #back again in the working dir
      #defining bowtie params#####################################################
      Try(botwieParams<-tktoplevel(.affylmGUIglobals$ttMain))
      Try(tkwm.deiconify(botwieParams))
      Try(tkgrab.set(botwieParams))
      Try(tkfocus(botwieParams))
      Try(tkwm.title(botwieParams,"Bowtie parameters"))
      Try(tkgrid(tklabel(botwieParams,text="    ")))

      Try(frame1 <- tkframe(botwieParams,relief="groove",borderwidth=2))
      Try(HowManyQuestion1 <- tklabel(frame1,text="Number of allowed mismatches",font=.affylmGUIglobals$affylmGUIfont2))
      Try(tkgrid(HowManyQuestion1))
      Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
      Try(thresholdTcl <- tclVar("1"))
      Try(I0.but  <- tkradiobutton(frame1,text="1",variable=thresholdTcl,value="1",font=.affylmGUIglobals$affylmGUIfont2))
      Try(I1.but  <- tkradiobutton(frame1,text="2",variable=thresholdTcl,value="2",font=.affylmGUIglobals$affylmGUIfont2))
      Try(I2.but  <- tkradiobutton(frame1,text="3",variable=thresholdTcl,value="3",font=.affylmGUIglobals$affylmGUIfont2))
      Try(tkgrid(I0.but,sticky="w"))
      Try(tkgrid(I1.but,sticky="w"))
      Try(tkgrid(I2.but,sticky="w"))

      Try(tkgrid.configure(HowManyQuestion1,I0.but,I1.but,I2.but,sticky="w"))

      Try(frame2 <- tkframe(botwieParams,relief="groove",borderwidth=2))
      Try(fractionLabel <- tklabel(frame2,text="Input data type",font=.affylmGUIglobals$affylmGUIfont2))
      Try(tkgrid(fractionLabel,sticky="w"))
      Try(tkgrid.configure(fractionLabel,sticky="w"))
      Try(fractionTcl <- tclVar("pe"))
      Try(F1.but <- tkradiobutton(frame2,text="Pair-end",variable=fractionTcl,value="pe",font=.affylmGUIglobals$affylmGUIfont2))
      Try(F2.but <- tkradiobutton(frame2,text="single-end",variable=fractionTcl,value="se",font=.affylmGUIglobals$affylmGUIfont2))

      Try(tkgrid(F1.but, F2.but,sticky="w"))
      Try(tkgrid.configure(fractionLabel,F1.but,F2.but,sticky="w"))

      Try(onOK <- function()
      {
                            bowtieVal1 <- tclvalue(thresholdTcl)
                            bowtieVal2 <- tclvalue(fractionTcl)
                            Try(bowtieVal <<- paste(bowtieVal1, bowtieVal2, sep=";"))
                            Try(tkgrab.release(botwieParams))
                            Try(tkdestroy(botwieParams))
                            Try(tkfocus(.affylmGUIglobals$ttMain))
      })

      Try(frame3 <- tkframe(botwieParams,borderwidth=2))
      Try(onCancel <- function() {Try(bowtieVal <<- ""); Try(tkgrab.release(botwieParams));Try(tkdestroy(botwieParams));Try(tkfocus(.affylmGUIglobals$ttMain))})
      Try(OK.but <-tkbutton(frame3,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
      Try(Cancel.but <-tkbutton(frame3,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

      Try(tkgrid(tklabel(frame3,text="    "),OK.but,Cancel.but,tklabel(frame3,text="    ")))

      Try(tkgrid(tklabel(botwieParams,text="    "),frame1,frame2,tklabel(botwieParams,text="  ")))
      Try(tkgrid(tklabel(botwieParams,text="    ")))
      Try(tkgrid(tklabel(botwieParams,text="    "),frame3,tklabel(botwieParams,text="  ")))
      Try(tkgrid(tklabel(botwieParams,text="    ")))
      Try(tkgrid.configure(frame1,frame3,sticky="w"))

      Try(tkfocus(botwieParams))
      Try(tkbind(botwieParams, "<Destroy>", function() {Try(tkgrab.release(botwieParams));Try(tkfocus(.affylmGUIglobals$ttMain));}))
      Try(tkwait.window(botwieParams))
      Try(if(bowtieVal==""){return()} )
      Try(tmp <-strsplit(bowtieVal, ";"))
      Try(mismatch <- as.numeric(tmp[[1]][1]))
      Try(data.type <- tmp[[1]][2])
      ##########################################################################
     #default Thread 1
     Try(assign("Threads", 1 , affylmGUIenvironment)) 
     #defining number of threads
     if(.Platform$OS.type!="windows" ){
        Try(ttThreads<-tktoplevel(.affylmGUIglobals$ttMain))
	    Try(tkwm.deiconify(ttThreads))
	    Try(tkgrab.set(ttThreads))
	    Try(tkfocus(ttThreads))
	    Try(tkwm.title(ttThreads,"Defining the BG threshold for filtering"))
	    Try(tkgrid(tklabel(ttThreads,text="    ")))
	    Try(Threadsnum <- "1")
	    Try(Local.Threads <- tclVar(init=Threadsnum))
	    Try(entry.Threads <-tkentry(ttThreads,width="4",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.Threads,bg="white"))
	    Try(tkgrid(tklabel(ttThreads,text="Please enter the number of cores to be used by Bowtie. \nIf you do not know what to do use 1.",font=.affylmGUIglobals$affylmGUIfont2)))
	    Try(tkgrid(entry.Threads))
	    onOK <- function()
	    {
	                     Try(Threadsnum <- trunc(as.numeric(tclvalue(Local.Threads))))
	                     Try(assign("Threads", trunc(as.numeric(tclvalue(Local.Threads))),affylmGUIenvironment))
				               Try(assign("Threads.available", TRUE,affylmGUIenvironment))
	                     Try(tkgrab.release(ttThreads));Try(tkdestroy(ttThreads));Try(tkfocus(.affylmGUIglobals$ttMain))                        
	    }
	    Try(OK.but <-tkbutton(ttThreads,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	    Try(tkgrid(tklabel(ttThreads,text="    ")))
	    Try(tkgrid(OK.but))
	    Try(tkgrid.configure(OK.but))
	    Try(tkgrid(tklabel(ttThreads,text="       ")))
	    Try(tkfocus(entry.Threads))
	    Try(tkbind(entry.Threads, "<Return>",onOK))
	    Try(tkbind(ttThreads, "<Destroy>", function(){Try(tkgrab.release(ttThreads));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
	    Try(tkwait.window(ttThreads))
	    Try(tkfocus(.affylmGUIglobals$ttMain))
	  }
	  Try(Threadsnum <- get("Threads", env=affylmGUIenvironment))

    ############################################################################
      if(data.type == "pe"){
            Try(tkmessageBox(title="Pair-end mapping",message=paste("You have selected PAIR-END option.\nPlease remember that the two fastq files names, associated to the pair ends sequencing,\nhave to be written in the following format in the target file: filename1,filename2", sep=" ")))
      }
      #opening target for primary mapping
    	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
      Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	    Try(tkwm.deiconify(ttExonandTargets))
	    Try(tkgrab.set(ttExonandTargets))
	    Try(tkfocus(ttExonandTargets))
	    Try(tkwm.title(ttExonandTargets,"Targets file"))
      Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

	    OpenTargetsFileAndSetCursor <- function()
	   {
		   	Try(tkconfigure(ttExonandTargets,cursor="watch"))
			  Try(tkfocus(ttExonandTargets))
			  Try(OpenTargetsFile())
			  Try(tkconfigure(ttExonandTargets,cursor="arrow"))
			  Try(tkfocus(ttExonandTargets))
	   } 

	   Try(OpenTargetsFile.but <- tkbutton(ttExonandTargets, text="Select Targets File",command=OpenTargetsFile,font=.affylmGUIglobals$affylmGUIfont2))

	   Try(tclvalue(.affylmGUIglobals$TargetsfileName) <- fixSeps(tclvalue(.affylmGUIglobals$TargetsfileName)))
	   Try(TargetsfileBoxTitleLabel <- tklabel(ttExonandTargets,text=as.character(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle)),font=.affylmGUIglobals$affylmGUIfont2))
	   Try(TargetsfileNameLabel <- tklabel(ttExonandTargets,text=as.character(tclvalue(.affylmGUIglobals$TargetsfileName)),background="white",font=.affylmGUIglobals$affylmGUIfont2))
	   Try(tkconfigure(TargetsfileBoxTitleLabel, textvariable=.affylmGUIglobals$TargetsfileBoxTitle))
	   Try(tkconfigure(TargetsfileNameLabel, textvariable=.affylmGUIglobals$TargetsfileName))

	   Try(tkgrid(tklabel(ttExonandTargets,text="    ")))
	   Try(tkgrid(TargetsfileBoxTitleLabel,columnspan=4))
	   Try(tkgrid(TargetsfileNameLabel,columnspan=4))

	   Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

	   Try(tkgrid(tklabel(ttExonandTargets,text="    "),OpenTargetsFile.but))
	   Try(tkgrid.configure(OpenTargetsFile.but,columnspan=2))
	   Try(Abort <- 1)
	   onOK <- function()
	  {
			  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
			  Try(if(length(Targets)==0)
			  {
				   Try(tkmessageBox(title="NGS Targets File",message=paste("Either you did not specify a valid NGS Targets File",
					   "or an error occurred while reading in the Targets file.	It should be in tab-delimited text format and it should include the column headings \"FileName\", and \"Target\".",icon="error")))
				   onCancel()
			  })
			  Try(tkgrab.release(ttExonandTargets));
			  Try(tkdestroy(ttExonandTargets));
			  Try(tkfocus(.affylmGUIglobals$ttMain))
			  Try(Abort <<- 0)
	  }
	  onCancel <- function() {Try(tkgrab.release(ttExonandTargets));Try(tkdestroy(ttExonandTargets));Try(tkfocus(.affylmGUIglobals$ttMain));Try(Abort<<-1)}
	  Try(OK.but <-tkbutton(ttExonandTargets,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	  Try(Cancel.but <-tkbutton(ttExonandTargets,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
	  Try(tkgrid(tklabel(ttExonandTargets,text="    ")))
	  Try(tkgrid(tklabel(ttExonandTargets,text="    "),OK.but,Cancel.but))
	  Try(tkgrid(tklabel(ttExonandTargets,text="       ")))
	  Try(tkfocus(ttExonandTargets))
	  Try(tkbind(ttExonandTargets, "<Destroy>", function() {Try(tkgrab.release(ttExonandTargets));Try(tkfocus(.affylmGUIglobals$ttMain));}))
	  Try(tkwait.window(ttExonandTargets))
      
	  if(Abort==1)
				return(0)
	  Try(tkfocus(.affylmGUIglobals$ttMain))
	  Try(Targets <- get("Targets",affylmGUIenvironment))
	  Try(Targets.sam <- Targets)
	  #make a bam file
    Try(javaDir <- get("javaDir",envir=affylmGUIenvironment))
    if(is.na(javaDir)){javaDir <- ""}
    if(javaDir != ""){
             Try(picardLoc <- paste('"',javaDir,'"',"/bin/java -jar ",myinfo[which(myinfo[,1]== "bowtieDirLocation"),2], "/SamFormatConverter.jar", sep=""))
    }else{
             Try(picardLoc <- paste("java -jar ",myinfo[which(myinfo[,1]== "bowtieDirLocation"),2], "/SamFormatConverter.jar", sep=""))
    }
#    Try(picardSort <- paste("java -jar ",myinfo[which(myinfo[,1]== "bowtieDirLocation"),2], "/SortSam.jar", sep=""))
#    Try(picardIndex <- paste("java -jar ",myinfo[which(myinfo[,1]== "bowtieDirLocation"),2], "/BuildBamIndex.jar", sep=""))
 
	  Try(refGenome <- paste(myinfo[which(myinfo[,1]== "bowtieDirLocation"),2],data.in.dir[refBowtie],sep="/"))
  #  Try(require(Rsamtools)||Stop("\nMissing Rsamtools library\n"))

    for (i in 1: dim(Targets)[1]){
      Try(cat("Processing: ", Targets$FileName[i],"\n"))
      if(data.type == "pe"){
              Try(pe.files <- as.character(unlist(strsplit(Targets$FileName[i], ","))))
              Try(sam.name <- paste(pe.files, collapse="-"))
              Try(mybam <- paste(data.in.dir[refBowtie],".bam", sep=""))
              Try(Targets.sam$FileName[i]<-paste(sam.name,mybam,sep="."))
      }else{
             Try(Targets.sam$FileName[i]<-paste(Targets$FileName[i],data.in.dir[refBowtie],".bam", sep=""))
      }
      if(.Platform$OS.type=="windows"){
            Try(bowtieLoc <- paste(myinfo[which(myinfo[,1]== "bowtieDirLocation"),2],"/bowtie.exe -a --best -k 1 -q -v ",mismatch," -S", sep=""))
            if(data.type == "pe"){
              Try(pe.files <- as.character(unlist(strsplit(Targets$FileName[i], ","))))
       	      Try(inputData1 <- paste(getwd(),pe.files[1],sep="/"))
       	      Try(inputData2 <- paste(getwd(),pe.files[2],sep="/"))
       	      Try(sam.name <- paste(pe.files, collapse="-"))
	      	  Try(outputSam <- paste(getwd(),paste(sam.name,".sam", sep=""),sep="/"))
              Try(system(paste(bowtieLoc,refGenome,"-1",inputData1,"-2",inputData2, outputSam, sep=" ")))
              Try(system(paste(picardLoc, " I=",outputSam, " O=tmp.bam", sep="")))
              Try(sortBam("tmp.bam","tmpS")) 
              Try(file.remove(outputSam))
              Try(file.remove("tmp.bam"))
              Try(indexBam("tmpS.bam"))
              Try(mybam <- sub("sam$",data.in.dir[refBowtie], outputSam))
              Try(filterBam("tmpS.bam", paste(mybam, ".bam", sep=""), index="tmpS.bam", indexDestination=TRUE, param=ScanBamParam(flag=scanBamFlag(isProperPair = TRUE, isUnmappedQuery = FALSE))))
              Try(file.remove("tmpS.bam"))
            }else{
	            Try(outputSam <- paste(getwd(),paste(Targets$FileName[i],".sam", sep=""),sep="/"))
       	      Try(inputData <- paste(getwd(),Targets$FileName[i],sep="/"))
              Try(system(paste(bowtieLoc,refGenome,inputData, outputSam, sep=" ")))
              Try(mybam <- sub("sam$",data.in.dir[refBowtie], outputSam))
              Try(system(paste(picardLoc, " I=",outputSam, " O=tmp.bam", sep="")))
              Try(sortBam("tmp.bam","tmpS")) 
              Try(file.remove(outputSam))
              Try(file.remove("tmp.bam"))
              Try(indexBam("tmpS.bam"))
              Try(mybam <- sub("sam$",data.in.dir[refBowtie], outputSam))
              Try(filterBam("tmpS.bam", paste(mybam, ".bam", sep=""), index="tmpS.bam", indexDestination=TRUE, param=ScanBamParam(flag=scanBamFlag(isProperPair = TRUE, isUnmappedQuery = FALSE))))
              Try(file.remove("tmpS.bam"))
           } 
          # bowtie.exe -a -m 1 -q -v 1 -S chr1 tmp.fq tmp.out.sam
     } else if(.Platform$OS.type!="windows"){
            Try(bowtieLoc <- paste(myinfo[which(myinfo[,1]== "bowtieDirLocation"),2],"/bowtie -p ",Threadsnum," -a --best -k 1 -q -v ",mismatch," -S", sep=""))
            if(data.type == "pe"){
              Try(pe.files <- as.character(unlist(strsplit(Targets$FileName[i], ","))))
       	      Try(inputData1 <- paste(getwd(),pe.files[1],sep="/"))
       	      Try(inputData2 <- paste(getwd(),pe.files[2],sep="/"))
       	      Try(sam.name <- paste(pe.files, collapse="-"))
	      	  Try(outputSam <- paste(getwd(),paste(sam.name,".sam", sep=""),sep="/"))
              Try(system(paste(bowtieLoc,refGenome,"-1",inputData1,"-2",inputData2, outputSam, sep=" ")))
              Try(system(paste(picardLoc, " I=",outputSam, " O=tmp.bam", sep="")))
              Try(sortBam("tmp.bam","tmpS")) 
              Try(file.remove(outputSam))
              Try(file.remove("tmp.bam"))
              Try(indexBam("tmpS.bam"))
              Try(mybam <- sub("sam$",data.in.dir[refBowtie], outputSam))
              Try(filterBam("tmpS.bam", paste(mybam, ".bam", sep=""), index="tmpS.bam", indexDestination=TRUE, param=ScanBamParam(flag=scanBamFlag(isProperPair = TRUE, isUnmappedQuery = FALSE))))
              Try(file.remove("tmpS.bam"))
            }else{
	            Try(outputSam <- paste(getwd(),paste(Targets$FileName[i],".sam", sep=""),sep="/"))
       	      Try(inputData <- paste(getwd(),Targets$FileName[i],sep="/"))
              Try(system(paste(bowtieLoc,refGenome,inputData, outputSam, sep=" ")))
              Try(system(paste(picardLoc, " I=",outputSam, " O=tmp.bam", sep="")))
              Try(sortBam("tmp.bam","tmpS")) 
              Try(file.remove(outputSam))
              Try(file.remove("tmp.bam"))
              Try(indexBam("tmpS.bam"))
              Try(mybam <- sub("sam$",data.in.dir[refBowtie], outputSam))
              Try(filterBam("tmpS.bam", paste(mybam, ".bam", sep=""), index="tmpS.bam", indexDestination=TRUE, param=ScanBamParam(flag=scanBamFlag(isProperPair = TRUE, isUnmappedQuery = FALSE))))
              Try(file.remove("tmpS.bam"))
            } 
     }
   }
     Try(newfilename <- paste("target", gsub(" ", "_",date()),"_sam.txt",sep=""))
     Try(newfilename <- gsub("\\:", "-",newfilename))
     
     Try(write.table(Targets.sam, newfilename, row.names=F, quote = F, sep="\t"))
     Try(tkmessageBox(title="Bowtie primary mapping",message=paste("Bowtie primary mapping is finished.\nBAM files are available in",getwd(),"The target file to load bam files in oneChannelGUI is",newfilename, sep="\n"),type="ok"))
     Try(usedtime <- proc.time() - ptm)
     Try(cat("\nUsed CPU time (min) ",usedtime[3]/60,"\n"))
     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
     Try(tkfocus(.affylmGUIglobals$ttMain))
}
##############################################################################
downloadShrimp <- function(){
	Abort <<- 0
	Try(my.dir <- getwd())
    #download shrimp
    Try(shrimpDirLocation  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/shrimp", sep=""))	
	Try(system(paste("mkdir ", shrimpDirLocation)))
    Try(setwd(shrimpDirLocation))
	Try(assign("shrimpDirLocation", shrimpDirLocation, affylmGUIenvironment))#directory where NGS perl scripts are located
	Try(assign("shrimpDirLocation.Available",TRUE,affylmGUIenvironment))
    Try(cat("\nBegin downloads of Shrimp.....\n"))
    #defining which program to be downloaded
    Try(ttGetShrimp <- tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.deiconify(ttGetShrimp))
    Try(tkgrab.set(ttGetShrimp))
    Try(tkfocus(ttGetShrimp))
    Try(tkwm.title(ttGetShrimp,"Which OS are you using?"))

    Try(tkgrid(tklabel(ttGetShrimp,text="    ")))
    Try(ttGetShrimpTcl <- tclVar("unix"))
    Try(rbIQR.mac<-tkradiobutton(ttGetShrimp,text="macOS             ",variable=ttGetShrimpTcl,value="macOS",font=.affylmGUIglobals$affylmGUIfont2))
    Try(rbIQR.linux<-tkradiobutton(ttGetShrimp,text="unix              ",variable=ttGetShrimpTcl,value="unix",font=.affylmGUIglobals$affylmGUIfont2))
    
    Try(tkgrid(tklabel(ttGetShrimp,text="    "),rbIQR.mac))
    Try(tkgrid(tklabel(ttGetShrimp,text="    "),rbIQR.linux))

    Try(tkgrid.configure(rbIQR.mac,rbIQR.linux, columnspan=2,sticky="w"))
    Try(tkgrid(tklabel(ttGetShrimp,text="    "),tklabel(ttGetShrimp,text="    ")))
    Try(ReturnVal <- "unix")
    Try(onCancel <- function() {Try(tkgrab.release(ttGetShrimp));Try(tkdestroy(ttGetShrimp));Try(tkfocus(.affylmGUIglobals$ttMain));Abort <<- 1})
	Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGetShrimpTcl));Try(tkgrab.release(ttGetShrimp));Try(tkdestroy(ttGetShrimp));Try(tkfocus(.affylmGUIglobals$ttMain))})
    Try(OK.but     <- tkbutton(ttGetShrimp,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
    Try(Cancel.but <- tkbutton(ttGetShrimp,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

    Try(tkgrid(tklabel(ttGetShrimp,text="    "),OK.but,Cancel.but, tklabel(ttGetShrimp,text="    ")))
    Try(tkgrid.configure(OK.but,sticky="e"))
    Try(tkgrid.configure(Cancel.but,sticky="w"))
    Try(tkgrid(tklabel(ttGetShrimp,text="    ")))

    Try(tkbind(ttGetShrimp,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetShrimp));Try(tkfocus(.affylmGUIglobals$ttMain));}))
    Try(tkbind(OK.but, "<Return>",onOK))
    Try(tkbind(Cancel.but, "<Return>",onCancel)) 
    Try(tkwait.window(ttGetShrimp))
	
	if(Abort==1){
		Try(return())   
	}else if(ReturnVal=="unix"){
       Try(download.file("http://compbio.cs.toronto.edu/shrimp/releases/SHRiMP_2_2_3.lx26.x86_64.tar.gz", "shrimp.tar.gz", mode="wb"))
       Try(system("gzip -d shrimp.tar.gz"))
       Try(system("tar xvf shrimp.tar"))
       Try(system("cp -fR ./SHRiMP_2_2_3/* ."))
       Try(system("rm -fR ./SHRiMP_2_2_3/"))
    }else{
        Try(download.file("http://compbio.cs.toronto.edu/shrimp/releases/SHRiMP_2_2_2.macosx.x86_64.tar.gz", "shrimp.tar.gz", mode="wb"))
        Try(system("gzip -d shrimp.tar.gz"))
        Try(system("tar xvf shrimp.tar"))
        Try(system("cp -fR ./SHRiMP_2_2_2/* ."))
        Try(system("rm -fR ./SHRiMP_2_2_2/"))
    }
    Try(etcDir  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/etc", sep=""))
    Try(localdata <- paste(etcDir, "/localData.txt", sep=""))
    Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
    Try(myinfo[which(myinfo[,1]=="shrimpDirLocation"),2] <- shrimpDirLocation)
    Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
	setwd(my.dir)    
}	
    
.downloadMirbase <- function(org="hsa"){
  # require(Biostrings) || stop("\nMissing Biostrings\n")
   cat("\ndownloading harpins\n")
   download.file("ftp://mirbase.org/pub/mirbase/CURRENT/hairpin.fa.gz", "hairpin.fa.gz", mode="wb")
   system(paste("gzip --force -d hairpin.fa.gz", sep=""))
   harpins <- readRNAStringSet("hairpin.fa", format="fasta")
   harpins <- DNAStringSet(harpins)
   harpins <- harpins[grep(org, names(harpins))]
   harpins.n <- strsplit(names(harpins)," ")
   harpins.n <- sapply(harpins.n, function(x)x[1])
   names(harpins) <- harpins.n
   writeXStringSet(harpins, "harpin.fa", format="fasta")
   cat("\ndownloading matures\n")
   download.file("ftp://mirbase.org/pub/mirbase/CURRENT/mature.fa.gz", "mature.fa.gz", mode="wb")
   system(paste("gzip --force -d mature.fa.gz", sep=""))
   mature <- readRNAStringSet("mature.fa", format="fasta")
   mature <- DNAStringSet(mature)
   mature <- mature[grep(org, names(mature))]
   mature.n <- strsplit(names(mature)," ")
   mature.n <- sapply(mature.n, function(x)x[1])
   names(mature) <- mature.n
   writeXStringSet(mature, "mature.fa", format="fasta")
}

.makeDb.R <- function(fasta.file, db.name="harpins-ls", shrimp.folder){
	system(paste(shrimp.folder,"/bin/gmapper-ls -s 00111111001111111100,00111111110011111100,00111111111100111100,00111111111111001100,00111111111111110000 -H -S ",db.name, " ", fasta.file, sep=""), wait=FALSE)
}

.matureOnHairpin <- function(mature.in, hairpin.in){
	mirna.m <- readDNAStringSet(mature.in, format="fasta")
    mirna.p <- readDNAStringSet(hairpin.in, format="fasta")
   
    #definign the location of mature miRNA on precursors
	tmp <- bowtie_build(references=hairpin.in, outdir=getwd(), prefix=sub(".fa","",hairpin.in), force=TRUE)
	bowtie(sequences=mature.in, index=sub(".fa","",hairpin.in), type="single", force=TRUE, a=TRUE, best=TRUE, strata=TRUE, sam=TRUE, v=0, f=TRUE, outfile="mature_on_precursor.sam") 
    as.bam <- function(x){
        asBam(x,sub(".sam$","",x),overwrite=T)
        sortBam(sub(".sam$",".bam",x),sub(".sam$","S",x))
        indexBam(sub(".sam$","S.bam",x))
   }
   as.bam("mature_on_precursor.sam")
   #param <- ScanBamParam(what=c("rname","seq"))
   mature.GA <- readGAlignments("mature_on_precursor.bam", use.names=TRUE)
   save(mature.GA, file="mature.GA.rda")
   return(mature.GA)
   #mature.GA contains the locatin of mature miRNAs on precursors
}

.trim <- function(in.dir=dir(), adapter3="AGATCGGAAGAGCACACGTCT", adapter5="GTTCAGAGTTCTACAGTCCGACGATC", out.dir, cutadapt.path="/usr/local/bin/cutadapt", wait=TRUE, parallel=FALSE){
	 unlink(out.dir,recursive = TRUE, force = TRUE)
	 dir.create(out.dir)
	 ls.txt <- in.dir
	 ls.txt <- ls.txt[grep(".fastq$", ls.txt)]
	 if(length(ls.txt)==0){
 	    cat("\nIt seems that no fastq files are present.\n")
 	    return()
	 }
	 test <- NULL
	 test <- system(paste(cutadapt.path," --version",sep=""), intern = TRUE)
	 if(length(test)==0){
	    cat("\ncutadapt is not installed.\n")
	    return()
	 }
#	 for(input in ls.txt){
#	     output <- sub(".fastq", "_trimmed.fastq", input)
#	 	log <- sub(".fastq", "_trimmed.log", input)
#	 	system(paste(cutadapt.path," -f fastq -a ", adapter3, " -g ", adapter5," -e 0.15 -O 10 -m 14 ", input," -o ",out.dir, "/", output," > ", out.dir,"/", log, sep=""), wait=wait)
#	 }
	 trim.sub <- function(input, cutadapt.path, adapter3, adapter5, out.dir){
	 	output <- sub(".fastq", "_trimmed.fastq", input)
		log <- sub(".fastq", "_trimmed.log", input)
		system(paste(cutadapt.path," -f fastq -a ", adapter3, " -g ", adapter5," -e 0.15 -O 10 -m 14 ", input," -o ",out.dir, "/", output," > ", out.dir,"/", log, sep=""), wait=wait)
        cat(".")
	 }
	 if(parallel){
	#	    require(BiocParallel) || stop("\nMissing BiocParallel Package\n")
            p <- MulticoreParam()
	 	    tmp.log <- bplapply(ls.txt, trim.sub, cutadapt.path=cutadapt.path, adapter3=adapter3, adapter5=adapter5, out.dir=out.dir, BPPARAM=p)
     }else{
		 	tmp.log <- lapply(ls.txt, trim.sub, cutadapt.path=cutadapt.path, adapter3=adapter3, adapter5=adapter5, out.dir=out.dir)
     }
	 Sys.sleep(30)
	 cat("\n")
}

.plotDensity <- function (mat, ylab = "density", xlab = "x", type = "l", col = 1:6, na.rm = TRUE,...) {
    x.density <- apply(mat, 2, density, na.rm = na.rm)
    all.x <- do.call(cbind, lapply(x.density, function(x) x$x))
    all.y <- do.call(cbind, lapply(x.density, function(x) x$y))
    matplot(all.x, all.y, ylab = ylab, xlab = xlab, type = type, col = col,...)
    invisible(list(all.x = all.x, all.y = all.y))
}

.length.stat <- function(in.dir=dir()){
#	require(Biostrings)||stop("\nMissing Biostrings package\n")
    ls.txt <- in.dir
    ls.txt <- ls.txt[grep("_trimmed.fastq$", ls.txt)]
	cat("\n")
	stat.l <- lapply(ls.txt, function(x){
		   out <- sub(".fastq", ".fasta", x)
		   system(paste("perl -ne 'y/@/>/;print($_.<>)&&<>&&<>' ",x," > ", out, sep=""))
		   tmp <- width(readDNAStringSet(out, format="fasta"))
		   cat(".")
		   return(tmp)
		   })
    names(stat.l) <- ls.txt
    max.l <- max(sapply(stat.l, length))
    stat.l <- lapply(stat.l, function(x,y){
			   tmp <- c(x, rep(0,(max.l-length(x))))
		   }, y=max.l)
    stat.l <- as.data.frame(stat.l)
	stat.l<- as.matrix(stat.l)
	stat.n <- strsplit(dimnames(stat.l)[[2]],"_")
	stat.n <- sapply(stat.n, function(x)x[1])
	pdf("length_distribution.pdf")
    .plotDensity(stat.l, lty = 1, lwd = 2, col = 1:dim(stat.l)[[2]], main="Length distribution", xlim=c(12,52))
    x.ax <- legend(1, 1, legend = stat.n, lty = 1, lwd = 2, col = 1:dim(stat.l)[[2]], plot = FALSE)$rect$w
    legend(par("usr")[2] - (par("usr")[2] - par("usr")[1])/100 - x.ax, par("usr")[4] - (par("usr")[4] - par("usr")[3])/100, 
	legend = stat.n, lty = 1, lwd = 2, col = 1:dim(stat.l)[[2]], cex=0.5)
	dev.off()
	cat("\n")
}


.reading.log <- function(in.dir=dir()){
   ls.txt <- in.dir
   ls.txt <- ls.txt[grep("_trimmed.log$", ls.txt)]
   if(length(ls.txt)==0){
      cat("\nIt seems that log files are not present in this folder.\n")
	  return()
   }
   grab <- function(x){
      con <- file(x, "r")
      tmp <- readLines(con)
	  close(con)
      tmp <- tmp[grep("Too short reads", tmp)]
	  tmp <-sub("Too short reads:","",tmp)
	  tmp <- strsplit(tmp, "\\(")
	  tmp <- tmp[[1]][1]
	  tmp <- gsub(" ","", tmp)
	  tmp <- as.numeric(tmp)
	  return(tmp)
   }
   tmp1 <- sapply(ls.txt, grab)
   grab <- function(x){
      con <- file(x, "r")
      tmp <- readLines(con)
	  close(con)
      tmp <- tmp[grep("Trimmed reads", tmp)]
	  tmp <-sub("Trimmed reads:","",tmp)
	  tmp <- strsplit(tmp, "\\(")
	  tmp <- tmp[[1]][1]
	  tmp <- gsub(" ","", tmp)
	  tmp <- as.numeric(tmp)
	  return(tmp)
   }   
   tmp2 <- sapply(ls.txt, grab)
   grab <- function(x){
      con <- file(x, "r")
      tmp <- readLines(con)
	  close(con)
      tmp <- tmp[grep("Processed reads", tmp)]
	  tmp <-sub("Processed reads:","",tmp)
	  tmp <- strsplit(tmp, "\\(")
	  tmp <- tmp[[1]][1]
	  tmp <- gsub(" ","", tmp)
	  tmp <- as.numeric(tmp)
	  return(tmp)
   }
   tmp3 <- sapply(ls.txt, grab)
  
   tmp <- cbind(tmp3,tmp2,tmp1)
   dimnames(tmp)[[2]] <- c("Processed reads","Trimmed reads","Discarded reads")
   
   return(tmp)
}

.shrimp <- function(x, db.name="harpin-ls", threads=1, shrimp.folder){
	system(paste(shrimp.folder,"/bin/gmapper-ls --strata -o 1 --qv-offset 33 -Q -L ",db.name," ",x," -N ",threads," --mode mirna -w 170% -E --un ",x,"_un-miRNA.fastq > ./miRNA/",x,".sam 2> ./miRNA/",x,".log ",sep=""), wait=TRUE)
    cat(".")
}

.countMature <- function(sam, matureGA){
#	require(Rsamtools)
#	require(GenomicAlignments)
	as.bam <- function(x){
        asBam(x,sub(".sam$","",x),overwrite=T)
        sortBam(sub(".sam$",".bam",x),sub(".sam$","S",x))
        indexBam(sub(".sam$","S.bam",x))
		return(sub(".sam$","S.bam",x))
	}
    bam <- as.bam(sam)
    load(matureGA)
	#loaded mature.GA GAlignments

   .extractMatureCounts <- function(matureGA, BamFileName){
        s.GA <- readGAlignments(BamFileName, use.names=T)
        tmp.v <- countOverlaps(matureGA, s.GA)
        return(tmp.v)
   }
   sample.counts <- .extractMatureCounts(matureGA=mature.GA, BamFileName=bam)
   names.s <- names(sample.counts)
   sample.counts <- data.frame(names.s, sample.counts)
   names(sample.counts) <- c("miRNA","counts")
   d.counts <- sample.counts$counts[which(duplicated(sample.counts$miRNA))]
   names(d.counts) <- sample.counts$miRNA[which(duplicated(sample.counts$miRNA))]
   sample.counts.u <- sample.counts[setdiff(seq(1,dim(sample.counts)[1]),which(duplicated(sample.counts$miRNA))),]
   #unique in duplicated
   sample.counts.ud <- sample.counts.u[which(as.character(sample.counts.u$miRNA)%in%names(d.counts)),]
   #unique without duplicated
   sample.counts.u <- sample.counts.u[setdiff(seq(1,dim(sample.counts.u)[1]),which(as.character(sample.counts.u$miRNA)%in%as.character(sample.counts.ud$miRNA))),]
   #collapsing duplicated counts
   for(i in 1:dim(sample.counts.ud)[1]){
     sum.d <- sum(d.counts[which(names(d.counts)==as.character(sample.counts.ud$miRNA)[i])])
	 sample.counts.ud$counts[i] <- sum(sample.counts.ud$counts[i],sum.d)
   }
   #coumbining duplicated miRNAs with duplicated collapsed 
   sample.counts.u <- rbind(sample.counts.u, sample.counts.ud)
   sample.counts.u <- sample.counts.u[order(sample.counts.u$miRNA),]
   cat(".")   
   return(sample.counts.u)
}


wrapperMirnaCounts <- function(working.dir, out.dir, org="hsa", threads=1, cutadapt.path="/usr/local/bin/cutadapt", parallel=FALSE,...){
    #downloading shrimp
	Try(shrimpDirLocation.Available <- get("shrimpDirLocation.Available",envir=affylmGUIenvironment))
	if(!shrimpDirLocation.Available){
		downloadShrimp()
	}
    Try(shrimpDirLocation <- get("shrimpDirLocation",envir=affylmGUIenvironment))
    #setting working dir
    log <- paste(date(),"Setting working dir",sep=" ")
	 cat("\n",log,"\n")
    cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
    if(length(working.dir)==0){
           log <- paste(date(),"Working dir is missing!",sep=" ")
		    cat("\n",log,"\n")
           cat(log, file="analysis.log", sep="\n", append=TRUE)
           return()
    }
    setwd(working.dir)
        dir.check <- dir()
        dir.check <- dir.check[grep("fastq$",dir.check)]
        if(length( dir.check)==0){
                    log <- paste(date(),"It seems that the folder",working.dir, "does not contains fastq files",sep=" ")
					 cat("\n",log,"\n")
                    cat(log, file="analysis.log", sep="\n", append=TRUE)
                    return()
        }
        #downloading the latest version of hairpin an mature miRNAs ofr a specific organism 
	    log <- paste(date(),"Downloading the latest version of hairpin and mature miRNAs for",org,sep=" ")
		cat("\n",log,"\n")
	    cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)    
        .downloadMirbase(org=org)
        log <- paste(date(),"Latest version of hairpin and mature miRNAs for",org,"was downloaded",sep=" ")
	    cat("\n",log,"\n")
        cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
        #create a shrimp db using hairpin
	    log <- paste(date(),"Starting creation SHRIMP hairpin database",sep=" ")
		cat("\n",log,"\n")
	    cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
        .makeDb.R(fasta.file="harpin.fa", db.name="harpin-ls", shrimp.folder=shrimpDirLocation)
#		Sys.sleep(10)
        log <- paste(date(),"SHRIMP db was created",sep=" ")
	    cat("\n",log,"\n")
        cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
        #mappping mature miRNAs on hairpin
        log <- paste(date(),"Mapping mature miRNAs on hairpin",sep=" ")
		cat("\n",log,"\n")
        cat(log, file="analysis.log", sep="\n", append=TRUE)
        .matureOnHairpin(mature.in="mature.fa", hairpin.in="harpin.fa")
#		Sys.sleep(10)
        log <- paste(date(),"Mature miRNAs were mapped on hairpin",sep=" ")
	    cat("\n",log,"\n")
        cat(log, file="analysis.log", sep="\n", append=TRUE)
        #removing adapters
	    log <- paste(date(),"Start fastq trimming with cutadapt",sep=" ")
		 cat("\n",log,"\n")
	    cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
        .trim(in.dir=dir(), out.dir=out.dir, cutadapt.path=cutadapt.path, parallel=parallel)
		cat("\n")
		setwd(out.dir)	   
        log <- paste(date(),"Fastq files were trimmed",sep=" ")
	    cat("\n",log,"\n")
        cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
		#length stat
        log <- paste(date(),"Evaluating the fragment length distribution",sep=" ")
	    cat("\n",log,"\n")
        cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
		.length.stat(in.dir=dir())
        log <- paste(date(),"Length distribution is saved in length_distribution.pdf",sep=" ")
	    cat("\n",log,"\n")
        cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
	    tmp <- .reading.log(in.dir=dir())
	    write.table(tmp,"trimming.log", sep="\t", col.names=NA)
        log <- paste(date(),"Trimming statistics are saved in trimming.log file",sep=" ")
	    cat("\n",log,"\n")
        cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)

        dir <- dir()
        dir <-dir[grep("fastq$",dir)]
        #creating the folder in which shrimp mapping results are going
        system("mkdir miRNA")
        #mapping miRNAs
	    log <- paste(date(),"SHRIMP mapping started",sep=" ")
		cat("\n",log,"\n")
	    cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
        sapply(dir, .shrimp, db.name="../harpin-ls", shrimp.folder=shrimpDirLocation, threads=threads)
		cat("\n")
        log <- paste(date(),"SHRIMP mapping is finished",sep=" ")
	    cat("\n",log,"\n")
        cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
        #counting mature miRNAs
        setwd("miRNA")
	    log <- paste(date(),"miRNA counting is started",sep=" ")
		cat("\n",log,"\n")
	    cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
        dir <- dir()
        dir <-dir[grep(".sam$",dir)]
		if(parallel==FALSE){
            all.counts <- lapply(dir, .countMature, matureGA="../../mature.GA.rda")
			cat("\n")
		}else{
		#	require(BiocParallel) || stop("\nMissing BiocParallel Package\n")
            p <- MulticoreParam()
			all.counts <- bplapply(dir, .countMature, matureGA="../../mature.GA.rda", BPPARAM=p)
			cat("\n")
		}
        all.counts <- as.data.frame(all.counts)
        rownames(all.counts) <- as.character(all.counts$miRNA)
        all.counts <- all.counts[,setdiff(seq(1:dim(all.counts)[2]),grep("miRNA",names(all.counts)))]
        names(all.counts) <- dir
        log <- paste(date(),"miRNA counting is finished",sep=" ")
	    cat("\n",log,"\n")
        cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
        save(all.counts, file="all_counts.Rda")
		file.copy(from=paste(working.dir,"/trimmed/miRNA/all_counts.Rda",sep=""),to= paste(working.dir,"/all_counts.Rda",sep=""), overwrite=TRUE)        
		tmp.files <- dir(paste(working.dir,"/trimmed/miRNA/",sep=""))
		tmp.files <- tmp.files[grep("S.bam", tmp.files)] 
		file.copy(from=paste(working.dir,"/trimmed/miRNA/",tmp.files,sep=""),to= paste(working.dir,"/",tmp.files,sep=""), overwrite=TRUE)        
		tmp.files <- dir(paste(working.dir,"/trimmed/miRNA/",sep=""))
		tmp.files <- tmp.files[grep(".log$", tmp.files)] 
		file.copy(from=paste(working.dir,"/trimmed/miRNA/",tmp.files,sep=""),to= paste(working.dir,"/",tmp.files,sep=""), overwrite=TRUE)
		tmp.files <- dir(paste(working.dir,"/trimmed/",sep=""))
		tmp.files <- tmp.files[grep(".log$", tmp.files)] 
		file.copy(from=paste(working.dir,"/trimmed/",tmp.files,sep=""),to= paste(working.dir,"/",tmp.files,sep=""), overwrite=TRUE)
		file.copy(from=paste(working.dir,"/trimmed/length_distribution.pdf",sep=""),to= paste(working.dir,"/length_distribution.pdf",sep=""), overwrite=TRUE)
		
		
		#clean up
        setwd(working.dir)
		unlink(out.dir, recursive = TRUE, force = TRUE)
        log <- paste(date(),"Temporary folders and files are purged",sep=" ")
	    cat("\n",log,"\n")
        cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
		#de
        log <- paste(date(),"Starting Differential expression analysis with DESeq2",sep=" ")
        cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
		cat("\n",log,"\n")
   #     require(DESeq2)||stop("\nMissing DESeq2\n")
        groups <- strsplit(names(all.counts),"_")
        groups <- sapply(groups, function(x)x[2])
        if(length(unique(groups)) == 0){
            log <- paste(date(),"the sample format does not contain info on the experimental covariates",sep=" ")
			cat("\n",log,"\n")
            cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
            return()
        }else if(length(unique(groups)) == 1){
            log <- paste(date(),"ONly one covariate was found. The present implementation supports only 2 different covariates",sep=" ")
			cat("\n",log,"\n")
            cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
            return()
        }else if(length(unique(groups)) > 2){
            log <- paste(date(),"The present implementation support only 2 different covariates",sep=" ")
			cat("\n",log,"\n")
            cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
            return()
        }else if(length(unique(groups)) == 2){
                colData <- as.data.frame(groups)
                dimnames(colData) <- list(names(all.counts),"groups")
                dds<-DESeqDataSetFromMatrix(countData = all.counts,colData = colData, design = ~groups)
                dds <- DESeq(dds)
                res <- results(dds)
                log <- paste(date(),"Differential expression was calculated",sep=" ")
                cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
			    cat("\n",log,"\n")
                write.table(all.counts, "raw.counts.txt",sep="\t", col.names=NA)
                write.table(res, "results.txt",sep="\t", col.names=NA)
                rld <- rlog(dds, blind=TRUE)
                rld <- assay(rld)
                write.table(rld, "rlognorm.counts.txt",sep="\t", col.names=NA)
                pdf("dispersion.pdf")
                plotDispEsts(dds)
                dev.off()
                save(all.counts, res, rld, file="all.counts.Rda")
                log <- paste(date(),"Dispersion plot, differential expression results, raw and normalized counts, bam files, statistics file are saved in results.zip.\nPlease read REDME for more information\n",sep=" ")
			    cat("\n",log,"\n")
                cat(log, file=paste(working.dir,"/analysis.log",sep=""), sep="\n", append=TRUE)
				system("rm -fR mature_on_precursor.bam")
				system("rm -fR mature_on_precursor.bam.bai")
			    dir <- dir()
			    to.be.zipped <- c(dir[grep(".bam$",dir)], dir[grep(".bai$",dir)], dir[grep(".log$",dir)])
				tmp.zip <- date()
				tmp.zip <- gsub("  "," ",tmp.zip) 
				tmp.zip <- gsub(" ","_",tmp.zip) 
				tmp.zip <- gsub(":","-",tmp.zip)
                cat("Content:", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE)
				cat("README: this file", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE) 
				cat("raw.counts.txt: miRNAs unnormalized counts", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE) 
				cat("length_distribution.pdf: Length distribution of the trimmed reads", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE) 
				cat("rlognorm.counts.txt: miRNAs log2 normalized counts for data visualization. E.g. clustering", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE) 
				cat("dispersion.pdf: DESeq dispersion estimatin plot.", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE)
				cat("results.txt: DESeq2 Differential expression results.", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE)
				cat("all.counts.Rda: miRNAs unnormalized counts as all.counts R object. To be used for further analysis", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE) 
				cat("analysis.log: log of the full analysis pipeline", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE) 
				cat("SampleName_trimmed.log: log files produced by cutadapt", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE) 
				cat("SampleName_trimmed.fastq.log: log files produced by SHRiMP", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE) 
				cat("SampleName_trimmed.fastqS.bam: sorted and indexed bam files", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE) 
				cat("SampleName_trimmed.fastqS.bam.bai: bam file indexes", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE) 
				cat("harpin.fa: miRNA precursor fasta file", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE)
				cat("mature.fa: miRNA mature fasta file", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE) 
				cat("mature_on_precursorS.bam: sorted bam containing the mapping position of mature miRNAs on their precursors", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE) 
				cat("mature_on_precursorS.bam.bai: index to the bam file containing the mapping position of mature miRNAs on their precursors", file=paste(working.dir,"/README",sep=""), sep="\n", append=TRUE) 				
                zip(paste("results_",tmp.zip,".zip",sep=""),c("README","results.txt","length_distribution.pdf","all.counts.Rda","dispersion.pdf","raw.counts.txt","rlognorm.counts.txt","harpin.fa","mature.fa", to.be.zipped))
        }
	    system("rm -fR harpin*")
	    system("rm -fR hairpin*")
	    system("rm -fR mature*")
		system("rm -fR *log")
		system("rm -fR *bai")
		system("rm -fR *bam")
		system("rm -fR all_counts.Rda")
		system("rm -fR *txt")
		system("rm -fR *pdf")
        return(paste("results_",tmp.zip,".zip",sep=""))
}


miRNAde <- function(){
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
    Try(tkmessageBox(title="miRNA DE",message="Set the directory in which your miRNA fastq files are located.\nFiles should have the format:SampleName_ExperimentGroup_Lane_Read_FlowCellIndex.fastq",type="ok"))
    Try(SetWD())
	#organism selection
    Try(ttGetOrg<-tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.deiconify(ttGetOrg))
    Try(tkgrab.set(ttGetOrg))
    Try(tkfocus(ttGetOrg))
    Try(tkwm.title(ttGetOrg,"mirBase Organism Symbol"))
    Try(tkgrid(tklabel(ttGetOrg,text="    ")))
    Try(Org <- "")
    Try(Local.Org <- tclVar(init=Org))
    Try(entry.Org <-tkentry(ttGetOrg,width="3",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.Org,bg="white"))
    Try(tkgrid(tklabel(ttGetOrg,text="Enter the symbol for organism. E.g. mmu for M. musculus.\nCheck organism naming convention at http://www.mirbase.org/",font=.affylmGUIglobals$affylmGUIfont2)))
    Try(tkgrid(entry.Org))
    onOK <- function()
    {
        Try(Org <- tclvalue(Local.Org))
        if(nchar(Org)==0)
          Org <- "Unselected"
        Try(tclvalue(.affylmGUIglobals$OrgTcl) <- Org)
        Try(tkgrab.release(ttGetOrg));Try(tkdestroy(ttGetOrg));Try(tkfocus(.affylmGUIglobals$ttMain))
    }
    Try(OK.but <-tkbutton(ttGetOrg,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(tklabel(ttGetOrg,text="    ")))
    Try(tkgrid(OK.but))
    Try(tkgrid.configure(OK.but))
    Try(tkgrid(tklabel(ttGetOrg,text="       ")))
    Try(tkfocus(entry.Org))
    Try(tkbind(entry.Org, "<Return>",onOK))
    Try(tkbind(ttGetOrg, "<Destroy>", function(){Try(tkgrab.release(ttGetOrg));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
    Try(tkwait.window(ttGetOrg))
    Try(tkfocus(.affylmGUIglobals$ttMain))
	
	#Threads selection selection
    Try(ttGetThreads<-tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.deiconify(ttGetThreads))
    Try(tkgrab.set(ttGetThreads))
    Try(tkfocus(ttGetThreads))
    Try(tkwm.title(ttGetThreads,"Threads"))
    Try(tkgrid(tklabel(ttGetThreads,text="    ")))
    Try(Threads <- "")
    Try(Local.Threads <- tclVar(init=Threads))
    Try(entry.Threads <-tkentry(ttGetThreads,width="2",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.Threads,bg="white"))
    Try(tkgrid(tklabel(ttGetThreads,text="Please enter the number of cores to be used",font=.affylmGUIglobals$affylmGUIfont2)))
    Try(tkgrid(entry.Threads))
    onOK <- function()
    {
        Try(Threads <- tclvalue(Local.Threads))
        if(nchar(Threads)==0)
          Threads <- 1
        Try(tclvalue(.affylmGUIglobals$ThreadsTcl) <- Threads)
        Try(tkgrab.release(ttGetThreads));Try(tkdestroy(ttGetThreads));Try(tkfocus(.affylmGUIglobals$ttMain))
    }
    Try(OK.but <-tkbutton(ttGetThreads,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(tklabel(ttGetThreads,text="    ")))
    Try(tkgrid(OK.but))
    Try(tkgrid.configure(OK.but))
    Try(tkgrid(tklabel(ttGetThreads,text="       ")))
    Try(tkfocus(entry.Threads))
    Try(tkbind(entry.Threads, "<Return>",onOK))
    Try(tkbind(ttGetThreads, "<Destroy>", function(){Try(tkgrab.release(ttGetThreads));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
    Try(tkwait.window(ttGetThreads))
    Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(biocparallel <<- FALSE)
    Try(mbVal <- tkmessageBox(title="Parallel R",
                 message="Do you want to use a parallel version of R that will use all available cores?",
                 icon="question",type="yesno",default="no"))
                 try(if(tclvalue(mbVal)=="yes") biocparallel <<- TRUE)
	
	Try(zip.info <- wrapperMirnaCounts(working.dir=getwd(), out.dir="trimmed", org=tclvalue(Local.Org), threads=as.numeric(tclvalue(Local.Threads)), parallel=biocparallel))
    Try(load("all.counts.Rda"))
	Try(tmp <- strsplit(names(all.counts),"_"))
	Try(tmp.n <- sapply(tmp, function(x)x[1]))
	Try(tmp.fn <- names(all.counts))
	Try(tmp.t <- sapply(tmp, function(x)x[2]))
	Try(tmp.df <- cbind(tmp.n,tmp.fn,tmp.t))
	Try(tmp.df <- as.data.frame(tmp.df))
	Try(names(tmp.df) <- c("Name","FileName","Target"))
	Try(rownames(tmp.df) <- tmp.df[,2])
	Try(write.table(tmp.df, "target_tmp.txt", sep="\t", row.names=FALSE))
	Try(Targets <- read.table("target_tmp.txt", header = TRUE, sep = "\t", quote = "\"", as.is = TRUE))
	Try(assign("Targets", Targets, affylmGUIenvironment))
    Try(Targets <- get("Targets",envir=affylmGUIenvironment))
    Try(rownames(Targets) <- Targets$FileName) 
    Try(var.tmp.pd<-data.frame(names(Targets)))
    Try(names(var.tmp.pd)<-"labelDescription" )
    Try(rownames(var.tmp.pd)<-names(Targets))
    Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
    Try(NormalizedAffyData <- new("ExpressionSet", assayData = assayDataNew(exprs=as.matrix(all.counts)) , phenoData=tmp1.pd, annotation=tclvalue(Local.Org)))
  	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
    Try(assign("NGS.Available",TRUE,affylmGUIenvironment))
  	Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
    Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
  	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="NGS counts from miRanalyser",font=.affylmGUIglobals$affylmGUIfontTree))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
  	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status" ,text="NGS data",font=.affylmGUIglobals$affylmGUIfontTree))
  	Try(if("Name" %in% colnames(Targets))
  	         SlideNamesVec <- Targets$Name)
  	Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
  	Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
   	Try(GetlimmaDataSetName())
    Try(tkmessageBox(title="miRNA DE",message=paste("Analysis is finished and results are in ",zip.info,sep=""),type="ok"))
}

#saving the filtered subset
   .SaveDESeq2TopTable <- function(correction, threshold, deTable)
   {
      Try(FileName <- tclvalue(tkgetSaveFile(initialfile=paste("topTable",".p-adjust.",correction,".threshold.",threshold,".xls",sep=""),filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
      Try(if(!nchar(FileName))
      return())
      Try(write.table(deTable,file=FileName,quote=FALSE, sep="\t", col.names=NA))
   }


deseq2Processing <- function(){
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkmessageBox(title="miRNA DESeq2",message="Set folder where miRNA DESeq2 results are saved.",type="ok"))
	Try(SetWD())
	Try(dir <- dir())
	if(length(which(dir=="all.counts.Rda"))==0){
		Try(tkmessageBox(title="miRNA DESeq2",message="The file all.counts.Rda is not present in this folder.",type="ok"))
		Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
		Try(return())
	}
    Try(load("all.counts.Rda"))
    #Filtering results
    Try(ttIfDialog<-tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.deiconify(ttIfDialog))
    Try(tkgrab.set(ttIfDialog))
    Try(tkfocus(ttIfDialog))
    Try(tkwm.title(ttIfDialog,"Selecting the threshold for the detection of differentially expressed miRNAs"))
    Try(tkgrid(tklabel(ttIfDialog,text="    ")))

    Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
    Try(HowManyQuestion1 <- tklabel(frame1,text="Log2 Fold Change",font=.affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(HowManyQuestion1))
    Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
    Try(permutationsTcl <- tclVar(1))
    Try(I1.but  <- tkradiobutton(frame1,text="none",variable=permutationsTcl,value=0,font=.affylmGUIglobals$affylmGUIfont2))
    Try(I2.but  <- tkradiobutton(frame1,text="0.5",variable=permutationsTcl,value=0.5,font=.affylmGUIglobals$affylmGUIfont2))
    Try(I3.but  <- tkradiobutton(frame1,text="1",variable=permutationsTcl,value=1,font=.affylmGUIglobals$affylmGUIfont2))
    Try(I4.but  <- tkradiobutton(frame1,text="2",variable=permutationsTcl,value=2,font=.affylmGUIglobals$affylmGUIfont2))

    Try(tkgrid(I1.but,sticky="w"))
    Try(tkgrid(I2.but,sticky="w"))
    Try(tkgrid(I3.but,sticky="w"))
    Try(tkgrid(I4.but,sticky="w"))
    Try(tkgrid.configure(HowManyQuestion1,I1.but,I2.but,I3.but,I4.but,sticky="w"))

    Try(frame2 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
    Try(cutoffLabel <- tklabel(frame2,text="Cut off p-value threshold",font=.affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(cutoffLabel,sticky="w"))
    Try(tkgrid.configure(cutoffLabel,sticky="w"))
    Try(cutoffTcl <- tclVar("0.05"))
    Try(F1.but <- tkradiobutton(frame2,text="none",variable=cutoffTcl,value="1",font=.affylmGUIglobals$affylmGUIfont2))
    Try(F2.but <- tkradiobutton(frame2,text="0.1",variable=cutoffTcl,value="0.1",font=.affylmGUIglobals$affylmGUIfont2))
    Try(F3.but <- tkradiobutton(frame2,text="0.05",variable=cutoffTcl,value="0.05",font=.affylmGUIglobals$affylmGUIfont2))
    Try(F4.but <- tkradiobutton(frame2,text="0.005",variable=cutoffTcl,value="0.005",font=.affylmGUIglobals$affylmGUIfont2))
    Try(F5.but <- tkradiobutton(frame2,text="0.001",variable=cutoffTcl,value="0.001",font=.affylmGUIglobals$affylmGUIfont2))
    Try(F6.but <- tkradiobutton(frame2,text="0.0005",variable=cutoffTcl,value="0.0005",font=.affylmGUIglobals$affylmGUIfont2))

    Try(tkgrid(F1.but,sticky="w"))
    Try(tkgrid(F2.but,sticky="w"))
    Try(tkgrid(F3.but,sticky="w"))
    Try(tkgrid(F4.but,sticky="w"))
    Try(tkgrid(F5.but,sticky="w"))
    Try(tkgrid(F6.but,sticky="w"))
    Try(tkgrid.configure(cutoffLabel,F1.but,F2.but,F3.but,F4.but,F5.but,F6.but,sticky="w"))

    Try(onOK <- function()
   {
                   fcVal <- as.character(tclvalue(permutationsTcl))
                   pVal <- as.numeric(tclvalue(cutoffTcl))
                   Try(fcpVal <<- paste(fcVal, pVal, sep=";"))
                   Try(tkgrab.release(ttIfDialog))
                   Try(tkdestroy(ttIfDialog))
                   Try(tkfocus(.affylmGUIglobals$ttMain))
   })
   Try(frame3 <- tkframe(ttIfDialog,borderwidth=2))
   Try(onCancel <- function() {Try(fcpVal <<- ""); Try(tkgrab.release(ttIfDialog));Try(tkdestroy(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain))})
   Try(OK.but <-tkbutton(frame3,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
   Try(Cancel.but <-tkbutton(frame3,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

   Try(tkgrid(tklabel(frame3,text="    "),OK.but,Cancel.but,tklabel(frame3,text="    ")))

   Try(tkgrid(tklabel(ttIfDialog,text="    "),frame1,frame2,tklabel(ttIfDialog,text="  ")))
   Try(tkgrid(tklabel(ttIfDialog,text="    ")))
   Try(tkgrid(tklabel(ttIfDialog,text="    "),frame3,tklabel(ttIfDialog,text="  ")))
   Try(tkgrid(tklabel(ttIfDialog,text="    ")))
   Try(tkgrid.configure(frame1,frame3,sticky="w"))

   Try(tkfocus(ttIfDialog))
   Try(tkbind(ttIfDialog, "<Destroy>", function() {Try(tkgrab.release(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
   Try(tkwait.window(ttIfDialog))
   if(fcpVal==""){
           Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
           return()
   }
   Try(tmp<-strsplit(fcpVal, ";"))
   Try(fcThreshold <- as.numeric(tmp[[1]][1]))
   Try(pThreshold <- as.numeric(tmp[[1]][2]))
   ################################
   Try(res <- res[!is.na(res$padj),])        
   Try(selected <- res[res$padj <= pThreshold, ])
   Try(selected <- selected[abs(selected$log2FoldChange) >= fcThreshold, ])
   if(dim(selected)[1] == 0){
              Try(tkmessageBox(title="DESeq2 analysis",message=paste("No differential expression was detected using:\n","Log2 FC Threshold ",fcThreshold, "\np-value threshold ",pThreshold,sep=""),type="ok",icon="info"))
		      Try(tkfocus(.affylmGUIglobals$ttMain))
			  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
              Try(return())
   }
   #plot de
   Try(.plotDE <- function(res, selected, fcThreshold, pThreshold){
	             plot(log10(res$baseMean), res$log2FoldChange, type="n", ylab="Log2 Fold Change", xlab="Log10 Mean counts")
	             points(log10(res$baseMean), res$log2FoldChange, pch=19, cex=0.3, col="black")
	             points(log10(selected$baseMean), selected$log2FoldChange, pch=19, cex=0.5, col="red")
	             abline(h=0, col="black")
	             abline(h=fcThreshold, col="red")
	             abline(h=-fcThreshold, col="green")
    })
    Try(par(mfrow=c(1,1)))
    Try(.plotDE(res=res, selected=selected, fcThreshold=fcThreshold, pThreshold=pThreshold))
    Try(correction<-paste("FC_", fcThreshold,"_adj-p_", sep=""))
    Try(.SaveDESeq2TopTable(correction=correction, threshold=pThreshold, selected))

    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}

#pathways enrichment
.openmiRNAFile <- function(FileName)
      {
		 Try(tempFileName <- tclvalue(tkgetOpenFile(filetypes="{{DE Files} {.xls}} {{All files} *}")))
               if(!nchar(tempFileName))
               {
                  tkfocus(.affylmGUIglobals$ttMain)
                  return()
               }
         mySel<-read.table(tempFileName, sep="\t", header=T, as.is=TRUE, row.names=1)
         return(mySel)
      }

loadmirnapath <- function (mirnafile = "mirna_input.txt", mirnacol = "miRNA.id", 
	      assayidcol = "ASSAYID", groupcol = "GROUP", filterflagcol = "FILTERFLAG", 
	      expressioncol = NA, foldchangecol = NA, pvaluecol = NA) 
	  {
	      mirnaTable <- read.table(mirnafile, header = TRUE, sep = "\t", 
	          fill = FALSE, comment.char = "", check.names = FALSE, 
	          quote = "\"")
	      columns = c(mirnacol = mirnacol, assayidcol = assayidcol, 
	          groupcol = groupcol, filterflagcol = filterflagcol, foldchangecol=foldchangecol,pvaluecol=pvaluecol)
	      if (!is.na(groupcol)) {
	          groupcount = length(levels(as.factor(mirnaTable[, groupcol])))
	      }
	      else {
	          groupcount = 0
	      }
	      if (any(colnames(mirnaTable) %in% filterflagcol)) {
	          state = "filtered"
	      }
	      else {
	          state = "unfiltered"
	      }
	      mirnaobj <- new("mirnapath", mirnaTable = mirnaTable, columns = columns, 
	          groupcount = groupcount, state = state)
	      return(mirnaobj)
	  }


permuting <- function(perm) {
	        mirnaobj <- get("mirnaobj", envir = .GlobalEnv)
            mirnacol <- get("mirnacol", envir = .GlobalEnv)
            genecol <- get("genecol", envir = .GlobalEnv)
            mirnagene <- get("mirnagene", envir = .GlobalEnv)
            groupcol <- get("groupcol", envir = .GlobalEnv)
            pathwaycol <- get("pathwaycol", envir = .GlobalEnv)
            pathwayidcol <- get("pathwayidcol", envir = .GlobalEnv)
            filterflagcol <- get("filterflagcol", envir = .GlobalEnv)
			
			groupData <- get("groupData", envir = .GlobalEnv)
			groupPathways <- get("groupPathways", envir = .GlobalEnv)
			groupmirnaGene <- get("groupmirnaGene", envir = .GlobalEnv)
			groupmirnas <- get("groupmirnas", envir = .GlobalEnv)
			
			
	        if (perm == 0) {
                filteredmirnas <- unique(as.character(groupData[groupData[, 
                  filterflagcol] == 1, mirnacol]))
                filteredmirnas <- filteredmirnas[!filteredmirnas %in% 
                  ""]
            }
            else {
                filteredmirnas <- unique(as.character(groupData[groupData[, 
                  filterflagcol] == 1, mirnacol]))
                filteredmirnas <- filteredmirnas[!filteredmirnas %in% 
                  ""]
                filteredmirnas <- sample(groupmirnas, length(filteredmirnas))
            }
            filteredmirnaGene <- mirnaobj@mirnaGene[mirnaobj@mirnaGene[, 
                mirnacol] %in% filteredmirnas, ]
		
				###
				enrich.bis <- function(pathGenes) {
                pathGenes = unique(pathGenes)
                univmirnaGene <- groupmirnaGene[groupmirnaGene[, 
                  genecol] %in% pathGenes, ]
                if (length(univmirnaGene) > dim(groupmirnaGene)[2]) {
                  univmirnaGene <- matrix(ncol = dim(groupmirnaGene)[2], 
                    univmirnaGene)
                }
                else {
                  univmirnaGene <- matrix(ncol = dim(groupmirnaGene)[2], 
                    byrow = TRUE, univmirnaGene)
                }
                colnames(univmirnaGene) <- colnames(groupmirnaGene)
                univmirnagenecount <- dim(univmirnaGene)[1]
                enrichmirnaGene <- univmirnaGene[univmirnaGene[, 
                  mirnacol] %in% filteredmirnas, ]
                if (length(enrichmirnaGene) > dim(groupmirnaGene)[2]) {
                  enrichmirnaGene <- matrix(ncol = dim(groupmirnaGene)[2], 
                    enrichmirnaGene)
                }
                else {
                  enrichmirnaGene <- matrix(ncol = dim(groupmirnaGene)[2], 
                    byrow = TRUE, enrichmirnaGene)
                }
                enrichedmirnagenecount <- dim(enrichmirnaGene)[1]
                numenrichmirna = 0
                numenrichgenes = 0
                if (enrichedmirnagenecount > 0) {
                  colnames(enrichmirnaGene) <- colnames(univmirnaGene)
                  rownames(enrichmirnaGene) <- 1:dim(enrichmirnaGene)[1]
                  numenrichmirna = length(unique(enrichmirnaGene[, 
                    mirnacol]))
                  numenrichgenes = length(unique(enrichmirnaGene[, 
                    genecol]))
                }
                r1 <- list(`Pathway miRNA-Gene Count` = univmirnagenecount, 
                  `Enriched miRNA-Gene Count` = enrichedmirnagenecount, 
                  `Enriched miRNA-Genes` = enrichmirnaGene, `Genes Enriched` = numenrichgenes, 
                  `miRNAs Enriched` = numenrichmirna)
                return(r1)
            }
				
				###
				
				
            pathsizes <- do.call(rbind, tapply(as.character(groupPathways[, 
                genecol]), groupPathways[, pathwaycol], enrich.bis))
            pathsizes = pathsizes[sapply(pathsizes[, "Enriched miRNA-Gene Count"], 
                function(i) {
                  i[[1]] > 0
                }), ]
            nFilteredmirnaGene = dim(filteredmirnaGene)[1]
            nmirnaGene = dim(groupmirnaGene)[1]
            useCts = do.call(c, pathsizes[, "Enriched miRNA-Gene Count"])
            gCounts = do.call(c, pathsizes[, "Pathway miRNA-Gene Count"])
            pvs <- phyper(useCts - 1, nFilteredmirnaGene, nmirnaGene - 
                nFilteredmirnaGene, gCounts, lower.tail = FALSE)
            names(pvs) = rownames(pathsizes)
            ord <- order(pvs)
            if (perm == 0) {
                r1 = list(pvalues = pvs[ord], `Measured pathway mirnaGenes` = gCounts[ord], 
                  `Enriched pathway mirnaGenes` = useCts[ord], 
                  `Total mirnaGenes` = nmirnaGene, `Total filtered mirnaGenes` = nFilteredmirnaGene, 
                  `Enriched miRNA-Genes` = pathsizes[ord, "Enriched miRNA-Genes"], 
                  `Genes Enriched` = sapply(pathsizes[ord, "Genes Enriched"], 
                    c), `miRNAs Enriched` = sapply(pathsizes[ord, 
                    "miRNAs Enriched"], c))
                r1
            }
            else {
                r1 = list(pvalues = pvs)
                r1
            }
        }

enrich <- function(group, permutations=permutations) {
	    mirnaobj <- get("mirnaobj", envir = .GlobalEnv)
	    mirnacol <- get("mirnacol", envir = .GlobalEnv)
	    genecol <- get("genecol", envir = .GlobalEnv)
	    mirnagene <- get("mirnagene", envir = .GlobalEnv)
	    groupcol <- get("groupcol", envir = .GlobalEnv)
	    pathwaycol <- get("pathwaycol", envir = .GlobalEnv)
	    pathwayidcol <- get("pathwayidcol", envir = .GlobalEnv)
	    filterflagcol <- get("filterflagcol", envir = .GlobalEnv)
	    
        groupData <- mirnaobj@mirnaTable[mirnaobj@mirnaTable[, 
            groupcol] %in% group, ]
        groupmirnas <- unique(as.character(groupData[, mirnacol]))
        groupmirnas <- groupmirnas[!groupmirnas %in% ""]
        groupmirnaGene <- as.matrix(mirnaobj@mirnaGene[mirnaobj@mirnaGene[, 
            mirnacol] %in% groupmirnas, ])
        groupgenes <- unique(as.character(groupmirnaGene[, genecol]))
        groupPathways <- as.matrix(mirnaobj@mirnaPathways[mirnaobj@mirnaPathways[, 
            genecol] %in% groupgenes, ])
        groupPathways[, pathwayidcol] = gsub("^[ ]+", "", groupPathways[, 
            pathwayidcol])
		groupData <<- groupData
		groupPathways <<- groupPathways
		groupmirnaGene <<- groupmirnaGene
		groupmirnas <<- groupmirnas
        permresults <- lapply(0:permutations, permuting)
        if (permutations > 0) {
            permIDs = sort(unique(do.call(c, lapply(1:length(permresults), 
                function(j) {
                  names(permresults[[j]]$pvalues)
                }))))
            permtable = do.call(rbind, lapply(1:length(permresults), 
                function(j) {
                  pTemp = permresults[[j]]$pvalues[permIDs]
                  names(pTemp) = permIDs
                  pTemp[is.na(pTemp)] = 1
                  pTemp
                }))
            permps = apply(permtable, 2, function(i) {
                (rank(i)[1]/length(i))
            })
            permresults[[1]]$permpvalues = permps
        }
        permresults[[1]]
    }
		  

runEnrichment <- function (Composite = TRUE, groups = NULL, permutations = 0){
    mirnaobj <- get("mirnaobj", envir = .GlobalEnv)
    mirnacol <<- mirnaobj@columns["mirnacol"]
    genecol <<- mirnaobj@columns["genecol"]
    mirnagene <<- mirnaobj@columns["mirnagene"]
    groupcol <<- mirnaobj@columns["groupcol"]
    pathwaycol <<- mirnaobj@columns["pathwaycol"]
    pathwayidcol <<- mirnaobj@columns["pathwayidcol"]
    filterflagcol <<- mirnaobj@columns["filterflagcol"]
	mirnacol <- get("mirnacol", envir = .GlobalEnv)
	genecol <- get("genecol", envir = .GlobalEnv)
	mirnagene <- get("mirnagene", envir = .GlobalEnv)
	groupcol <- get("groupcol", envir = .GlobalEnv)
	pathwaycol <- get("pathwaycol", envir = .GlobalEnv)
	pathwayidcol <- get("pathwayidcol", envir = .GlobalEnv)
	filterflagcol <- get("filterflagcol", envir = .GlobalEnv)
	
    if (is.na(mirnacol)) {
        stop("mirnaobj@columns has no value for mirnacol")
    }
    if (is.na(genecol)) {
        stop("mirnaobj@columns has no value for genecol")
    }
    if (is.na(mirnagene)) {
        stop("mirnaobj@columns has no value for mirnagene")
    }
    if (is.na(groupcol)) {
        stop("mirnaobj@columns has no value for groupcol")
    }
    if (is.na(pathwaycol)) {
        stop("mirnaobj@columns has no value for pathwaycol")
    }
    if (is.na(pathwayidcol)) {
        stop("mirnaobj@columns has no value for pathwayidcol")
    }
    if (is.na(filterflagcol)) {
        stop("mirnaobj@columns has no value for filterflagcol")
    }
    if (is.null(groups)) {
        groups <- levels(as.factor(mirnaobj@mirnaTable[, mirnaobj@columns["groupcol"]]))
    }
    groupResults <- lapply(groups, enrich, permutations=permutations)
	names(groupResults) = groups
    mirnaobj@enrichment = groupResults
    mirnaobj@state = "enriched"
    if (!"pathwayList" %in% slotNames(mirnaobj) | length(mirnaobj@pathwayList) == 
        0) {
        pathwayTable = unique(mirnaobj@mirnaPathways[, c(pathwayidcol, 
            pathwaycol)])
        pathwayList = pathwayTable[, pathwaycol]
        names(pathwayList) = pathwayTable[, pathwayidcol]
        mirnaobj@pathwayList = pathwayList
    }
    return(mirnaobj)
}


mirnaTable <- function (mirnaobj, groups = NULL, format = "Tall", Significance = 0.2, 
    na.char = NA, pvalueTypes = c("pvalues", "permpvalues"), 
    maxStringLength = NA, pathwaysNames=hs.path.name) 
{
    pathwaycol = mirnaobj@columns["pathwaycol"]
    pathwayidcol = mirnaobj@columns["pathwayidcol"]
    pvalueTypes <- pvalueTypes[pvalueTypes %in% names(mirnaobj@enrichment[[1]])]
    if (length(pvalueTypes) == 0) {
        stop("The pvalueTypes argument does not match the enrichment\nP-value columns.")
    }
    if (is.null(groups)) {
        groups = names(mirnaobj@enrichment)
    }
    else {
        groups = groups[groups %in% names(mirnaobj@enrichment)]
    }
    fulltable <- do.call(rbind, lapply(as.character(groups), 
        function(group) {
            t1 <- data.frame(check.names = FALSE, mirnaobj@enrichment[[group]][c(pvalueTypes, 
                "Measured pathway mirnaGenes", "Enriched pathway mirnaGenes", 
                "Genes Enriched", "miRNAs Enriched", "Total mirnaGenes", 
                "Total filtered mirnaGenes")], Group = rep(group, 
                length(mirnaobj@enrichment[[group]][[1]])))
            pvaltest <- t1[, pvalueTypes] <= Significance
            if (length(pvalueTypes) > 1) {
                pvaltest <- apply(pvaltest, 1, function(i) {
                  any(i)
                })
            }
            t1 <- t1[pvaltest, ]
			if(dim(t1)[1] == 0){
				cat("\nNo pathways, associated to predicted miRNA-targets were detected as enriched\n")
				return()
			}
            t1 <- data.frame(check.names = FALSE, t1, pathwayidcol = rownames(t1), 
                `Pathway Name` = mirnaobj@pathwayList[rownames(t1)])
            colnames(t1)[colnames(t1) == "pathwayidcol"] = pathwayidcol
            t1[, pathwayidcol] = as.character(t1[, pathwayidcol])
            t1
        }))
    if (!is.na(maxStringLength)) {
        fulltable[, !colnames(fulltable) %in% pathwayidcol] = apply(fulltable[, 
            !colnames(fulltable) %in% pathwayidcol], 2, function(i) {
            if (all(is.character(i))) {
                j = sapply(i, function(k) {
                  k = substr(k, 1, min(nchar(k), maxStringLength))
                })
            }
        })
    }
    if (format == "Tall") {
        fulltable
    }
    else if (format == "SuperTall") {
        SuperTall <- do.call(rbind, apply(fulltable, 1, function(i) {
            pathwayid <- i[pathwayidcol][[1]]
            group <- i["Group"][[1]]
            GMtable <- mirnaobj@enrichment[[group]]["Enriched miRNA-Genes"][[1]][pathwayid][[1]]
            SuperTall1 <- data.frame(check.names = FALSE, do.call(rbind, 
                lapply(1:dim(GMtable)[1], function(k2) i)), GMtable)
            SuperTall1
        }))
        SuperTall
    }
    else if (format == "Wide") {
        widetable <- reshape(fulltable, direction = "wide", idvar = pathwayidcol, 
            timevar = "Group", drop = colnames(fulltable)[!colnames(fulltable) %in% 
                c(pathwayidcol, "Group", pvalueTypes)])
        if (!is.na(na.char)) {
            widetable[is.na(widetable)] <- na.char
        }
        widetable[, pathwaycol] <- mirnaobj@pathwayList[widetable[, 
            1]]
        widetable <- widetable[, c(pathwayidcol, pathwaycol, 
            colnames(widetable)[!colnames(widetable) %in% c(pathwayidcol, 
                pathwaycol)])]
        widetable
    }
}


.SaveMirPathTopTable <- function(finaltable, permutations.n, pvalue.t)
{
   Try(FileName <- tclvalue(tkgetSaveFile(initialfile=paste("miRPath_results_",".permutations.",permutations.n,".pvalue.",pvalue.t,".xls",sep=""),filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
   Try(if(!nchar(FileName))
   return())
   Try(write.table(finaltable,file=FileName,quote=FALSE, sep="\t", col.names=NA))
}


mirPath <- function(){
#	require(miRNApath)||stop("\nMissing miRNApath\n")
#	require(miRNAtap)||stop("\nMissing miRNAtap\n")
#	require(miRNAtap.db)||stop("\nMissing miRNAtap.db\n")
#	require(KEGG.db)||stop("\nKEGG.db\n")
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkmessageBox(title="miRNAtap",message="Set folder where miRNA DESeq2 filtered DE are saved.",type="ok"))
	Try(cat("\nLoading differentially expressed miRNAs\n"))
	Try(SetWD())
	Try(mySel<- .openmiRNAFile())
	Try(mySel <- cbind(rownames(mySel), rep(1, dim(mySel)[1]), rep(1, dim(mySel)[1]), mySel))
	Try(mySel <- as.data.frame(mySel))
	Try(names(mySel)[1:3] <- c("miRNA.id","GROUP", "ASSAYID"))
	
	Try(tmp.mirna <- as.character(sapply(as.character(mySel$miRNA.id), function(x)sub("hsa-","",x))))
	Try(tmp.mirna <- as.character(sapply(as.character(tmp.mirna), function(x)sub("-3p$","",x))))
	Try(tmp.mirna <- as.character(sapply(as.character(tmp.mirna), function(x)sub("-5p$","",x))))
	Try(mySel$miRNA.id <- tmp.mirna)
	Try(cat("\nLoading targetscan data\n"))
	Try(pred.tg <- lapply(tmp.mirna, function(x) getTargetsFromSource(mirna=x,  species = "hsa", source='targetscan')))
#	Try(tg.size <- sapply(pred.tg, function(x)dim(x)[1]))
    Try(cat("\nLoading pictar data\n"))
	Try(pred.pg <- lapply(tmp.mirna, function(x) getTargetsFromSource(mirna=x,  species = "hsa", source='pictar')))
#	Try(pg.size <- sapply(pred.pg, function(x)dim(x)[1]))
    Try(cat("\nLoading diana data\n"))
	Try(pred.dg <- lapply(tmp.mirna, function(x) getTargetsFromSource(mirna=x,  species = "hsa", source='diana')))
#	Try(dg.size <- sapply(pred.dg, function(x)dim(x)[1]))
    Try(cat("\nLoading miranda data\n"))
	Try(pred.mg <- lapply(tmp.mirna, function(x) getTargetsFromSource(mirna=x,  species = "hsa", source='miranda')))
#	Try(mg.size <- sapply(pred.mg, function(x)dim(x)[1]))
#	Try(size.df <-cbind(tmp.mirna, tg.size,pg.size,dg.size,mg.size))
#	Try(size.df <- as.data.frame(size.df))
#	Try(names(size.df) <- c("mirna.id","targetscan","pictar","diana","miranda"))
#	Try(size.max <- apply(size.df[,2:5],1, function(x)max(as.numeric(x))))
#	Try(size.df <- size.df[which(size.max > 0),])
	#select prediction
	Try(cat("\nselecting prediction gene set\n"))
    Try(ttGetFilterMethod <- tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.deiconify(ttGetFilterMethod))
    Try(tkgrab.set(ttGetFilterMethod))
    Try(tkfocus(ttGetFilterMethod))
    Try(tkwm.title(ttGetFilterMethod,"miRNA target prediction db"))

    Try(tkgrid(tklabel(ttGetFilterMethod,text="    ")))
    Try(ttGetFilterMethodTcl <- tclVar("targetscan"))
    Try(rbIQR.5 <- tkradiobutton(ttGetFilterMethod,text="targetscan",variable=ttGetFilterMethodTcl,value="targetscan",font=.affylmGUIglobals$affylmGUIfont2))
    Try(rbIQR.25<-tkradiobutton(ttGetFilterMethod,text="pictar",variable=ttGetFilterMethodTcl,value="pictar",font=.affylmGUIglobals$affylmGUIfont2))
    Try(rbIQR.1<-tkradiobutton(ttGetFilterMethod,text="diana",variable=ttGetFilterMethodTcl,value="diana",font=.affylmGUIglobals$affylmGUIfont2))
    Try(rbIQR.2<-tkradiobutton(ttGetFilterMethod,text="miranda",variable=ttGetFilterMethodTcl,value="miranda",font=.affylmGUIglobals$affylmGUIfont2))

    Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.5))
    Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.25))
    Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.1))
	Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.2))
    Try(tkgrid.configure(rbIQR.5,rbIQR.25,rbIQR.1,rbIQR.2,columnspan=2,sticky="w"))
    Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),tklabel(ttGetFilterMethod,text="    ")))
    Try(ReturnVal <- "")
    Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGetFilterMethod));Try(tkdestroy(ttGetFilterMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})
    Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGetFilterMethodTcl));Try(tkgrab.release(ttGetFilterMethod));Try(tkdestroy(ttGetFilterMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})
    Try(onHelp <- function() tkmessageBox(title="Selecting the miRNA target prediction db", message="Selecting the mRNA target prediction db",icon="info"))
    Try(Help.but <- tkbutton(ttGetFilterMethod,text=" Help ",command=function()Try(onHelp()),font=.affylmGUIglobals$affylmGUIfont2))
    Try(OK.but     <- tkbutton(ttGetFilterMethod,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
    Try(Cancel.but <- tkbutton(ttGetFilterMethod,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

    Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),OK.but,Cancel.but, Help.but,tklabel(ttGetFilterMethod,text="    ")))
    Try(tkgrid.configure(OK.but,sticky="e"))
    Try(tkgrid.configure(Cancel.but,sticky="w"))
    Try(tkgrid.configure(Help.but,sticky="e"))
    Try(tkgrid(tklabel(ttGetFilterMethod,text="    ")))

    Try(tkbind(ttGetFilterMethod,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetFilterMethod));Try(tkfocus(.affylmGUIglobals$ttMain));}))
    Try(tkbind(OK.but, "<Return>",onOK))
    Try(tkbind(Cancel.but, "<Return>",onCancel))      
    Try(tkbind(Help.but, "<Return>",onCancel)) 
    Try(tkwait.window(ttGetFilterMethod))
    if(is.na(ReturnVal)){
                Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                return()
    }else if(ReturnVal=="targetscan"){
		Try(pred.lst <- pred.tg)
    }else if(ReturnVal=="pictar"){
		Try(pred.lst <- pred.pg)
    }else if(ReturnVal=="diana"){
		Try(pred.lst <- pred.dg)
    }else if(ReturnVal=="miranda"){
		Try(pred.lst <- pred.mg)
    }
	##############
	Try(pred.size <- sapply(pred.lst, function(x)dim(x)[1]))
	Try(names(pred.lst) <- mySel$miRNA.id)
	Try(pred.lst <- pred.lst[which(pred.size > 0)])
	mirna.eg <- NULL
	for(i in 1:length(pred.lst)){
		Try(tmp <- paste(names(pred.lst[i]), pred.lst[[i]]$GeneID, sep="_"))
		Try(mirna.eg <- c(mirna.eg, tmp))
	}
	Try(mirna.eg <- strsplit(mirna.eg, "_"))
	Try(tmp1 <- sapply(mirna.eg, function(x)x[1]))
	Try(tmp2 <- sapply(mirna.eg, function(x)x[2]))
	Try(mirna.eg <- cbind(tmp1,tmp2))
	Try(dimnames(mirna.eg)[[2]] <- c("miRNA.id","EG"))
	Try(mySel <- mySel[which(pred.size > 0),])
	Try(tmp.date <- gsub(":","-",gsub(" ","_",date())))
	Try(mirna.filename <- paste("mirna_",tmp.date,".txt",sep=""))
	Try(eg.filename <- paste("eg_",tmp.date,".txt",sep=""))
	Try(write.table(mySel, mirna.filename, sep="\t", row.names=FALSE))
	Try(write.table(mirna.eg, eg.filename, sep="\t", row.names=FALSE))
	Try(cat("\nLoading miRNA data\n"))
	Try(mirnaobj <- loadmirnapath(mirnafile=mirna.filename, pvaluecol="padj", foldchangecol="log2FoldChange", groupcol="GROUP", mirnacol="miRNA.id", assayidcol="ASSAYID"))
	############
    Try(ttIfDialog<-tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.deiconify(ttIfDialog))
    Try(tkgrab.set(ttIfDialog))
    Try(tkfocus(ttIfDialog))
    Try(tkwm.title(ttIfDialog,"Selecting the threshold for the detection of differentially expressed miRNAs"))
    Try(tkgrid(tklabel(ttIfDialog,text="    ")))

    Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
    Try(HowManyQuestion1 <- tklabel(frame1,text="Number of permutations",font=.affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(HowManyQuestion1))
    Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
    Try(permutationsTcl <- tclVar(0))
    Try(I1.but  <- tkradiobutton(frame1,text="none",variable=permutationsTcl,value=0,font=.affylmGUIglobals$affylmGUIfont2))
    Try(I2.but  <- tkradiobutton(frame1,text="10",variable=permutationsTcl,value=10,font=.affylmGUIglobals$affylmGUIfont2))
    Try(I3.but  <- tkradiobutton(frame1,text="100",variable=permutationsTcl,value=100,font=.affylmGUIglobals$affylmGUIfont2))
    Try(I4.but  <- tkradiobutton(frame1,text="1000",variable=permutationsTcl,value=1000,font=.affylmGUIglobals$affylmGUIfont2))
    Try(I5.but  <- tkradiobutton(frame1,text="10000",variable=permutationsTcl,value=10000,font=.affylmGUIglobals$affylmGUIfont2))

    Try(tkgrid(I1.but,sticky="w"))
    Try(tkgrid(I2.but,sticky="w"))
    Try(tkgrid(I3.but,sticky="w"))
    Try(tkgrid(I4.but,sticky="w"))
	Try(tkgrid(I5.but,sticky="w"))
    Try(tkgrid.configure(HowManyQuestion1,I1.but,I2.but,I3.but,I4.but,I5.but,sticky="w"))

    Try(frame2 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
    Try(cutoffLabel <- tklabel(frame2,text="Significance p-value threshold",font=.affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(cutoffLabel,sticky="w"))
    Try(tkgrid.configure(cutoffLabel,sticky="w"))
    Try(cutoffTcl <- tclVar("0.1"))
    Try(F1.but <- tkradiobutton(frame2,text="none",variable=cutoffTcl,value="1",font=.affylmGUIglobals$affylmGUIfont2))
    Try(F2.but <- tkradiobutton(frame2,text="0.1",variable=cutoffTcl,value="0.1",font=.affylmGUIglobals$affylmGUIfont2))
    Try(F3.but <- tkradiobutton(frame2,text="0.05",variable=cutoffTcl,value="0.05",font=.affylmGUIglobals$affylmGUIfont2))
    Try(F4.but <- tkradiobutton(frame2,text="0.005",variable=cutoffTcl,value="0.005",font=.affylmGUIglobals$affylmGUIfont2))
    Try(F5.but <- tkradiobutton(frame2,text="0.001",variable=cutoffTcl,value="0.001",font=.affylmGUIglobals$affylmGUIfont2))
    Try(F6.but <- tkradiobutton(frame2,text="0.0005",variable=cutoffTcl,value="0.0005",font=.affylmGUIglobals$affylmGUIfont2))

    Try(tkgrid(F1.but,sticky="w"))
    Try(tkgrid(F2.but,sticky="w"))
    Try(tkgrid(F3.but,sticky="w"))
    Try(tkgrid(F4.but,sticky="w"))
    Try(tkgrid(F5.but,sticky="w"))
    Try(tkgrid(F6.but,sticky="w"))
    Try(tkgrid.configure(cutoffLabel,F1.but,F2.but,F3.but,F4.but,F5.but,F6.but,sticky="w"))

    Try(onOK <- function()
   {
                   fcVal <- as.character(tclvalue(permutationsTcl))
                   pVal <- as.numeric(tclvalue(cutoffTcl))
                   Try(fcpVal <<- paste(fcVal, pVal, sep=";"))
                   Try(tkgrab.release(ttIfDialog))
                   Try(tkdestroy(ttIfDialog))
                   Try(tkfocus(.affylmGUIglobals$ttMain))
   })
   Try(frame3 <- tkframe(ttIfDialog,borderwidth=2))
   Try(onCancel <- function() {Try(fcpVal <<- ""); Try(tkgrab.release(ttIfDialog));Try(tkdestroy(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain))})
   Try(OK.but <-tkbutton(frame3,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
   Try(Cancel.but <-tkbutton(frame3,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

   Try(tkgrid(tklabel(frame3,text="    "),OK.but,Cancel.but,tklabel(frame3,text="    ")))

   Try(tkgrid(tklabel(ttIfDialog,text="    "),frame1,frame2,tklabel(ttIfDialog,text="  ")))
   Try(tkgrid(tklabel(ttIfDialog,text="    ")))
   Try(tkgrid(tklabel(ttIfDialog,text="    "),frame3,tklabel(ttIfDialog,text="  ")))
   Try(tkgrid(tklabel(ttIfDialog,text="    ")))
   Try(tkgrid.configure(frame1,frame3,sticky="w"))

   Try(tkfocus(ttIfDialog))
   Try(tkbind(ttIfDialog, "<Destroy>", function() {Try(tkgrab.release(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
   Try(tkwait.window(ttIfDialog))
   if(fcpVal==""){
           Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
           return()
   }
   Try(tmp<-strsplit(fcpVal, ";"))
   Try(permutations.n <- as.numeric(tmp[[1]][1]))
   Try(pvalue.t <- as.numeric(tmp[[1]][2]))
   ############
    Try(cat("\nSelecting differentially expressed miRNAs\n"))
	
	Try(mirnaobj <- filtermirnapath( mirnaobj, pvalue = max(mySel$padj)))
	Try(cat("\nLoading miRNA-gene association data\n"))
	Try(mirnaobj <- loadmirnatogene(mirnafile=eg.filename, mirnaobj=mirnaobj, mirnacol="miRNA.id", genecol="EG"))
    
	Try(hs.path <- as.data.frame(KEGGEXTID2PATHID))
	Try(names(hs.path) <- c("KEGG.ID","EG"))
	Try(hs.path.name <- as.data.frame(KEGGPATHID2NAME))
	Try(names(hs.path.name) <- c("KEGG.ID","PATH.NAME"))
	Try(kegg.filename <- paste("kegg_",tmp.date,".txt",sep=""))
	Try(write.table(hs.path, kegg.filename, sep="\t", row.names=FALSE))
	Try(cat("\nLoading KEGG-gene association data\n"))
	Try(mirnaobj <- loadmirnapathways( mirnaobj=mirnaobj,pathwayfile=kegg.filename, pathwaycol="KEGG.ID", genecol="EG"))  
	Try(cat("\nRunning Pathways enrichment data\n"))
	Try(mirnaobj <<- mirnaobj)
	Try(mirnaobj <- runEnrichment(Composite=TRUE, permutations=permutations.n))
	Try(cat("\nFinalizing results\n"))
    Try(finaltable <- mirnaTable(mirnaobj, groups=NULL, format="Tall", Significance=pvalue.t, pvalueTypes=c("pvalues","permpvalues"),maxStringLength=42))
	Try(tmp.n <- sapply(rownames(finaltable), function(x)substring(x,4,8)))
	Try(hs.path.name <- hs.path.name[which(hs.path.name$KEGG.ID %in% tmp.n),])
	Try(finaltable[,dim(finaltable)[2]] <- paste(names(tmp.n),hs.path.name$PATH.NAME, sep=":"))
	.SaveMirPathTopTable(finaltable, permutations.n=permutations.n, pvalue.t=pvalue.t)	
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}

Try the oneChannelGUI package in your browser

Any scripts or data that you put into this service are public.

oneChannelGUI documentation built on Nov. 17, 2017, 11:02 a.m.