R/generaltoolsmenu.R

Defines functions genomeStudioReformat setBinDir tuxedoSetup openPdf closePdf

Documented in closePdf genomeStudioReformat openPdf setBinDir tuxedoSetup

#set of functions, directly/indirectly involved, in oneChannelGUI generalToolMenu
#oneChannelGUI   filteringTable filtering a tab delimited file on the basis of a list of probesets
#oneChannelGUI colExtract extract a user defined colum from a tab delimited file with header
#oneChannelGUI geneExonLibs queries affymetrix web site to download exon and gene 1.0 ST WT library files
#RETIRED oneChannelGUI ngsperlDownload creating dir with ngs perl scripts
#oneChannelGUI bowtieDownload download bowtie and picard tools and build a binary form of ref genome for non coding precursors
#               alos downloading tophat and cufflinks for linux and mac 
#              bowtiesGenomes  downloades and builds chromosome level genomes references for bowtie
#              embeds also makeGeneScaffold for gene level analysis, which creates gene-level oriented scaffolds  
#              bowtieBuilt downloads prebuilt cromosome oriented bowtie references from:
#               http://sourceforge.net/p/ochguiextras/home/oneChannelGUI.extras/
#oneChannelGUI aptFolder setting the folder were apt tools are located (save data in localdata.txt in etc)
#oneChannelGUI javaFolder setting the folder were java is located
#oneChannelGUI deleteLocalData delete data in localdata.txt resetting aptDir and libDirLocation
#oneChannelGUI buildingLocalAnnotation updates gene level annotation using the netaffx annotation data
#                                      exon level annotation is done using the UCSC exon-level annotation data
#oneChannelGUI refseqDownload retrieve the latest Hs, Mm, Rn refseq fasta file
#oneChannelGUI madscrosshybDownload and creation of mads derived mps file only available for Hs and Mm core  NOT FINISHED
#oneChannelGUI updateLibs run an update of the Bioconductor libraries
#oneChannelGUI variantExons the function updates the table available in oneChannelGUI that contains only variant exons
#             for the core set. variant exons are those that are present only in a subset of isoforms associated to a gene to the UCSC browser
#oneChannelGUI exportFASTA  Export non-coding RNA fasta file for RNA-seq
#oneChannelGUI meVDownload setting the folder were meV software (http://www.tm4.org/mev/) is located  (save data in localdata.txt in etc)
#oneChannelGUI extPckInfo show which external software are available and in which dir
#oneChannelGUI combining2eSet combine two tables with the same row names
#oneChannelGUI wrapNGS wrapping function to install all expernal software needed for RNA-seq
#oneChannelGUI makeGeneScaffold creating Grange object for UCSC browser needed to map reads on UCSC genes  located in stand alone functions
#              part of the  bowtiesGenomes function  it returns a list of GRanges chromosomes encompassing the positions of all annotated USCS genes that encode for a protein
#oneChannelGUI genomeStudioReformat the function convert a genomestudio output in a format suitable to be loaded on oneChannelGUI
#oneChannelGUI setBinDir setting the dir in which create the soft lnks for tuxido suite
#oneChannelGUI openPdf needed under linux to print pdf
#oneChannelGUI closePdf needed under linux to print pdf
#################################################################################
#################################################################################
#this file contains a set of function that perfomr basic R function useful for handlying microarray data.
#this function filter a table on the basis of a vector of data present in an other file
"filteringTable" <- function(){
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(tkmessageBox(title="Table subsetting",message="Open the file to be filtered. This file should be tab delimited with an header."))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(tempFileName <- tclvalue(tkgetOpenFile(filetypes="{{Text Files} {.txt}} {{All files} *}")))
    if(!nchar(tempFileName))
    {
       tkfocus(.affylmGUIglobals$ttMain)
       return()
    }
    Try(saving.file <- paste(tempFileName, ".filtered.by.",sep=""))
    Try(mySel<-read.table(tempFileName, sep="\t", header=T, as.is=TRUE, quote=""))
    Try(tkmessageBox(title="Table subsetting",message="Open the file to be used to filter the previous file.\nThis file should contain a single column with an header equal to \nthe one that should be used for filtering in the tab delimited file."))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(tempFileName <- tclvalue(tkgetOpenFile(filetypes="{{Text Files} {.txt}} {{All files} *}")))
    if(!nchar(tempFileName))
    {
       tkfocus(.affylmGUIglobals$ttMain)
       return()
    }
    Try(tmp <- as.vector(unlist(strsplit(tempFileName , "/"))))
    Try(saving.file <- paste(saving.file, tmp[length(tmp)],sep=""))
    Try(myFilter<-read.table(tempFileName, sep="\t", header=T, as.is=TRUE, quote=""))
    Try(col.for.filter <- which(names(mySel)==names(myFilter)[1]))
    Try(mySel <- mySel[which(mySel[,col.for.filter]%in%myFilter[,1]),])
    Try(tkmessageBox(title="Table subsetting",message="Saving the filtered table."))
    Try(tkfocus(.affylmGUIglobals$ttMain))
	  Try(FileName <- tclvalue(tkgetSaveFile(initialfile=saving.file, filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
    Try(if(!nchar(FileName))
		    	return())
		Try(write.table(mySel,file=FileName,quote=FALSE,col.names=NA,sep="\t"))
		 Try(tkfocus(.affylmGUIglobals$ttMain))
   
}
################################################################################
"colExtract" <- function(){
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(tkmessageBox(title="Column extraction",message="Open the file to be manipulated. This file should be tab delimited with an header."))
    Try(tempFileName <- tclvalue(tkgetOpenFile(filetypes="{{Text Files} {.txt}} {{All files} *}")))
    if(!nchar(tempFileName))
    {
       tkfocus(.affylmGUIglobals$ttMain)
       return()
    }
    Try(mySel<-read.table(tempFileName, sep="\t", header=T, as.is=TRUE, quote=""))
    Try(mycol <- names(mySel))
    Try(mycol <- paste(mycol, "=",seq(1, length(mycol)), sep="", collapse=" "))
    
          #selecting the column to be removed
                 Try(ttcolExtract<-tktoplevel(.affylmGUIglobals$ttMain))
                 Try(tkwm.deiconify(ttcolExtract))
                 Try(tkgrab.set(ttcolExtract))
                 Try(tkfocus(ttcolExtract))
                 Try(tkwm.title(ttcolExtract,"Defining the column to be estracted"))
                 Try(tkgrid(tklabel(ttcolExtract,text="    ")))
                 Try(colnum <- "1")
                 Try(Local.colExtract <- tclVar(init=colnum))
                 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 columnof interest\n", mycol,collapse=" "),font=.affylmGUIglobals$affylmGUIfont2)))
                 Try(tkgrid(entry.colExtract))
                 onOK <- function()
                 {
                     Try(colnum <- as.numeric(tclvalue(Local.colExtract)))
                     Try(assign("colnum", 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(colnum <- get("colnum", affylmGUIenvironment))
                 if(colnum > length(names(mySel))){
                         Try(tkmessageBox(title="Column extraction",message="You have selected a non existing column!"))
                          Try(tkfocus(.affylmGUIglobals$ttMain))
                         return()
                 }
    
    Try(tempFileName <- as.vector(unlist(strsplit(tempFileName, "/"))))
    Try(if(length(tempFileName) > 1)  tempFileName <- tempFileName[length(tempFileName)])
    Try(saving.file <- paste("col.",colnum,".from.",tempFileName,".txt",sep=""))
    Try(tkmessageBox(title="Column extraction",message="Saving the extracted column."))
    Try(tkfocus(.affylmGUIglobals$ttMain))
	  Try(FileName <- tclvalue(tkgetSaveFile(initialfile=saving.file, filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
    Try(if(!nchar(FileName))
		    	return())
    Try(myout <- as.character(as.vector(mySel[,colnum])))
    Try(zz <- file(FileName, "w"))
    Try(writeLines(myout, con = zz, sep = "\n"))
    Try(close(zz))
     Try(tkfocus(.affylmGUIglobals$ttMain))
}
################################################################################
#save affy libraries in allylibs dir as new dir in oneChannelPath
 "geneExonLibs" <- function(){
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(tkmessageBox(title="Gene Exon 1.0 ST libraries",message="This routine installs, in a user defined folder,\nall library files needed for analysis of Gene/Exon Affymetrix arrays."))
      Try(myWD <- getwd())
      #Try(SetWD())
      Try(localdata  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/etc/localData.txt", sep=""))
      Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
      Try(libDirLocation <- myinfo[which(myinfo[,1]=="libDirLocation"),2])
      Try(if(is.na(libDirLocation)) libDirLocation <- "")
      if(libDirLocation != ""){
             Try(assign("libDirLocation", libDirLocation, affylmGUIenvironment)) 
             Try(mbVal <- tkmessageBox(title="Gene Exon 1.0 ST libraries",
				    											message="There already a folder defined for Affymetrix libraries.\nDo you want to change it?",
						    									icon="question",type="yesno",default="no"
								    						 )#end of tkmessageBox
		        )#end of Try(mbVal..
    		    if(tclvalue(mbVal)=="no"){
			            Try(tkfocus(.affylmGUIglobals$ttMain))
			            Try(setwd(myWD))
			            return()
		       } else{
                    Try(.downloadLibs())
                    Try(setwd(myWD))
                     Try(tkfocus(.affylmGUIglobals$ttMain))
                    return()
           } 
      }
   Try(.downloadLibs())
   Try(tkfocus(.affylmGUIglobals$ttMain))
   Try(setwd(myWD))
}

".downloadLibs" <- function(){
                     Try(tkfocus(.affylmGUIglobals$ttMain))
                     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                     Try(libDirLocation  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/affylibs", sep=""))
                     Try(dir.create(libDirLocation, showWarnings = TRUE, recursive = FALSE))
                     Try(setwd(libDirLocation))
                     Try(assign("libDirLocation", libDirLocation, affylmGUIenvironment))#directory where affy library files are located
                     Try(cat("\nBegin downloads of library files.....\n"))
                     Try(cat("Be patient!\n"))
                     Try(download.file("http://www.bioinformatica.unito.it/downloads/HuEx.zip", "HuEx.zip", mode="wb"))
                     Try(download.file("http://www.bioinformatica.unito.it/downloads/HuGene.zip","HuGene.zip", mode="wb"))
                     Try(download.file("http://www.bioinformatica.unito.it/downloads/MoEx.zip", "MoEx.zip", mode="wb"))
                     Try(download.file("http://www.bioinformatica.unito.it/downloads/MoGene.zip","MoGene.zip", mode="wb"))
                     Try(download.file("http://www.bioinformatica.unito.it/downloads/RaEx.zip","RaEx.zip", mode="wb"))
                     Try(download.file("http://www.bioinformatica.unito.it/downloads/RaGene.zip","RaGene.zip", mode="wb"))
					 Try(download.file("http://www.bioinformatica.unito.it/downloads/HTA_2.0.zip","HTA_2.0.zip", mode="wb"))
                     #in file exondata.zip are located transcripts annotation and variant exons
                     #generated with the function buildingLocalAnnotation()
                     #and with the function variantExons()
                     #are zipped and loaded on www.bioinformatica.unito.it to be downloaded in oneChannelGUI affylibs dir
                     #the first time an exon array is loaded (to be made)
                     Try(download.file("http://www.bioinformatica.unito.it/downloads/exondata.zip","exondata.zip", mode="wb"))
                     Try(cat("\nEnd downloads of 7 library files.....\n"))
                     Try(cat("\nBegin unzip library files.....\n"))
                     if(.Platform$OS.type=="windows"){
                         Try(unzip("exondata.zip"))
                         Try(unzip("HuGene.zip"))
                         Try(unzip("HuEx.zip"))
                         Try(unzip("MoEx.zip"))
                         Try(unzip("MoGene.zip"))
                         Try(unzip("RaEx.zip"))
                         Try(unzip("RaGene.zip"))
						 Try(unzip("HTA_2.0.zip"))
                     } else{
                         Try(system(paste("unzip exondata.zip", sep="")))
                         Try(system(paste("unzip HuGene.zip", sep="")))
                         Try(system(paste("unzip HuEx.zip")))
                         Try(system(paste("unzip MoEx.zip")))
                         Try(system(paste("unzip MoGene.zip")))
                         Try(system(paste("unzip RaEx.zip")))
                         Try(system(paste("unzip RaGene.zip")))
						 Try(system(paste("unzip HTA_2.0.zip")))
                     }
                     Try(cat("\nEnd unzip library files.....\n"))
                     Try(cat("\nLibrary files are ready to be used in ", getwd(),"\n"))
                     #save the info to be recovered in a new session
                     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]=="libDirLocation"),2] <- libDirLocation)
                     Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
                     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                      Try(tkfocus(.affylmGUIglobals$ttMain))
}
#######################################################################################################
#define the folder where apt tools are locate
"aptFolder" <- function(){
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
      Try(tkmessageBox(title="APT tools folder",message="Please select the folder where APT tools are located."))
      Try(myWD <- getwd())
      #Try(SetWD())
      Try(aptDir <- get("aptDir",envir=affylmGUIenvironment))
      if(is.na(aptDir)){aptDir <- ""}
      if(aptDir == ""){
            Try(SetED())
            Try(aptDir <- getwd())
            if(length(grep("apt-probeset-summarize", dir(paste(aptDir, "/bin", sep="")))) == 0){
                      Try(tkmessageBox(title="APT tools dir ",message="You have not correctly defined the main folder where APT tools are located!",icon="error"))
                      assign("aptDir.Available",FALSE,affylmGUIenvironment)
                      assign("aptDir", "" ,affylmGUIenvironment)
                      Try(setwd(myWD))
                      #Try(return())
            } else {
                       Try(localdata  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/etc/localData.txt", sep=""))
                       Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
                       Try(myinfo[which(myinfo[,1]=="aptDir"),2] <- aptDir)
                       Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
                       assign("aptDir.Available",TRUE,affylmGUIenvironment)
                       assign("aptDir", aptDir ,affylmGUIenvironment)
                       Try(setwd(myWD))
                       #Try(return())
            }
      } else{
                      Try(mbVal <- tkmessageBox(title="APT tools folder",
				    											message="There already a folder defined for APT tools.\nDo you want to change it?",
						    									icon="question",type="yesno",default="no"
								    						 )#end of tkmessageBox
		                  )#end of Try(mbVal..
    		              if(tclvalue(mbVal)=="no"){
			                        Try(tkfocus(.affylmGUIglobals$ttMain))
			                        Try(setwd(myWD))
			                        return()
		                  } 
                      if(tclvalue(mbVal)=="yes"){
                              Try(SetED())
                              Try(aptDir <- getwd())
                              if(length(grep("apt-probeset-summarize", dir(paste(aptDir, "/bin", sep="")))) == 0){
                                  Try(tkmessageBox(title="APT tools dir ",message="You have not correctly defined the main folder where APT tools are located!",icon="error"))
                                  assign("aptDir.Available",FALSE,affylmGUIenvironment)
                                  assign("aptDir", "" ,affylmGUIenvironment)
                                  Try(setwd(myWD))
                                  #Try(return())
                              } else {
                                 Try(localdata  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/etc/localData.txt", sep=""))
                                 Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
                                 Try(myinfo[which(myinfo[,1]=="aptDir"),2] <- aptDir)
                                 Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
                                 assign("aptDir.Available",TRUE,affylmGUIenvironment)
                                 assign("aptDir", aptDir ,affylmGUIenvironment)
                                 Try(setwd(myWD))
                                 #Try(return())
                             }
                      }      
           }
           
#           Try(mbVal <- tkmessageBox(title="RefSeq Fasta",
#				    											message="Do you wish to download reference sequence for exon-level analysis?\nIf you answer NO oneChannelGUI you can also do it later. Be patient!",
#						    									icon="question",type="yesno",default="no"
#								    						 )#end of tkmessageBox
#		  )#end of Try(mbVal..
#    	if(tclvalue(mbVal)=="yes"){
#			            Try(tkfocus(.affylmGUIglobals$ttMain))
#			            Try(refseqDownload())
#                  Try(tkmessageBox(title="APT tools folder",message="Please install the BLAST executable in the apt/blast dir.\nDownload the BAST from ftp://ftp.ncbi.nih.gov/blast/executables/LATEST"))
#      }
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(tkfocus(.affylmGUIglobals$ttMain))
}
###########################################################################################
#define the folder where apt tools are locate
"javaFolder" <- function(){
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
      Try(tkmessageBox(title="JAVA folder",message="Please select the folder where JAVA is located."))
      Try(myWD <- getwd())
      #Try(SetWD())
      Try(javaDir <- get("javaDir",envir=affylmGUIenvironment))
      if(is.na(javaDir)){javaDir <- ""}
      if(javaDir == ""){
            Try(SetED())
            Try(javaDir <- getwd())
            #javaDir <- paste('"',javaDir,"/bin/",'"', sep="")
            #javabin <- paste(javaDir, "/java -version", sep="")
            if(length(grep("java", dir(paste(javaDir, "/bin", sep="")))) == 0){
                      Try(tkmessageBox(title="Java dir ",message="You have not correctly defined the main folder where java binary is located!\nIn windows should be C:/somewhere/Java/jre6",icon="error"))
                      assign("javaDir.Available",FALSE,affylmGUIenvironment)
                      assign("javaDir", "" ,affylmGUIenvironment)
                      Try(setwd(myWD))
                      #Try(return())
            } else {
                       Try(localdata  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/etc/localData.txt", sep=""))
                       Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
                       Try(myinfo[which(myinfo[,1]=="javaDir"),2] <- javaDir)
                       Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
                       assign("javaDir.Available",TRUE,affylmGUIenvironment)
                       assign("javaDir", javaDir ,affylmGUIenvironment)
                       Try(setwd(myWD))
                       #Try(return())
            }
      } else{
                      Try(mbVal <- tkmessageBox(title="Java folder",
				    											message="There already a folder defined for Java.\nDo you want to change it?",
						    									icon="question",type="yesno",default="no"
								    						 )#end of tkmessageBox
		                  )#end of Try(mbVal..
    		              if(tclvalue(mbVal)=="no"){
			                        Try(tkfocus(.affylmGUIglobals$ttMain))
			                        Try(setwd(myWD))
			                        return()
		                  } 
                      if(tclvalue(mbVal)=="yes"){
                              Try(SetED())
                              Try(javaDir <- getwd())
                              if(length(grep("java", dir(paste(javaDir, "/bin", sep="")))) == 0){
                                   Try(tkmessageBox(title="Java dir ",message="You have not correctly defined the main folder where java binary is located!\nIn windows should be C:/somewhere/Java/jre6",icon="error"))
                                   assign("javaDir.Available",FALSE,affylmGUIenvironment)
                                   assign("javaDir", "" ,affylmGUIenvironment)
                                   Try(setwd(myWD))
                                   #Try(return())
                              } else {
                                   Try(localdata  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/etc/localData.txt", sep=""))
                                   Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
                                   Try(myinfo[which(myinfo[,1]=="javaDir"),2] <- javaDir)
                                   Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
                                   assign("javaDir.Available",TRUE,affylmGUIenvironment)
                                   assign("javaDir", javaDir ,affylmGUIenvironment)
                                   Try(setwd(myWD))
                                   #Try(return())
                              }
                      }      
           }
           
#           Try(mbVal <- tkmessageBox(title="RefSeq Fasta",
#				    											message="Do you wish to download reference sequence for exon-level analysis?\nIf you answer NO oneChannelGUI you can also do it later. Be patient!",
#						    									icon="question",type="yesno",default="no"
#								    						 )#end of tkmessageBox
#		  )#end of Try(mbVal..
#    	if(tclvalue(mbVal)=="yes"){
#			            Try(tkfocus(.affylmGUIglobals$ttMain))
#			            Try(refseqDownload())
#                  Try(tkmessageBox(title="APT tools folder",message="Please install the BLAST executable in the apt/blast dir.\nDownload the BAST from ftp://ftp.ncbi.nih.gov/blast/executables/LATEST"))
#      }
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(tkfocus(.affylmGUIglobals$ttMain))
}
###########################################################################################
"deleteLocalData" <- function(){
          Try(tkfocus(.affylmGUIglobals$ttMain))
          Try(mbVal <- tkmessageBox(title="Local setting",
				    											message="Do you want to the delete the local setting for Gene Exon arrays analysis?",
						    									icon="question",type="yesno",default="no"
								    						 )#end of tkmessageBox
		        )#end of Try(mbVal..
    		    if(tclvalue(mbVal)=="no"){
			            Try(tkfocus(.affylmGUIglobals$ttMain))
			            return()
		       } else{
                    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]=="libDirLocation"),2] <- "")
                    Try(myinfo[which(myinfo[,1]=="aptDir"),2] <- "")
                    Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names= F, quote=F))
                    Try(tkmessageBox(title="Local settings",message="Local setting were reset."))
                    return()
           } 

}
################################################################################
#building gene and exon annotation for oneChannelGUI 
"buildingLocalAnnotation" <- function(){
     Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
   
    Try(libDirLocation <- paste(path.package("oneChannelGUI", quiet = FALSE), "/affylibs/", sep = ""))
    #gathering affy libs and apt tools folders
    Try(netaffxUpdates  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/etc/netaffxUpdates.txt", sep=""))
    Try(cat(readLines(netaffxUpdates), sep="\n"))
    #username
    Try(ttGetUserName<-tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.deiconify(ttGetUserName))
    Try(tkgrab.set(ttGetUserName))
    Try(tkfocus(ttGetUserName))
    Try(tkwm.title(ttGetUserName,"NetAffx User Name"))
    Try(tkgrid(tklabel(ttGetUserName,text="    ")))
    Try(UserNameText <- "")
    Try(Local.UserName <- tclVar(init=UserNameText))
    Try(entry.UserName <-tkentry(ttGetUserName,width="30",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.UserName,bg="white"))
    Try(tkgrid(tklabel(ttGetUserName,text="Please enter your NetAffx User Name.",font=.affylmGUIglobals$affylmGUIfont2)))
    Try(tkgrid(entry.UserName))
    onOK <- function()
    {
       Try(UserNameText <- tclvalue(Local.UserName))
       if(nchar(UserNameText)==0)
           UserNameText <- "Unselected"
       Try(assign("UserNameText",UserNameText,affylmGUIenvironment))
       Try(tclvalue(.affylmGUIglobals$UserNameTcl) <- UserNameText)
       Try(tkgrab.release(ttGetUserName));Try(tkdestroy(ttGetUserName));Try(tkfocus(.affylmGUIglobals$ttMain))
    }
    Try(OK.but <-tkbutton(ttGetUserName,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(tklabel(ttGetUserName,text="    ")))
    Try(tkgrid(OK.but))
    Try(tkgrid.configure(OK.but))
    Try(tkgrid(tklabel(ttGetUserName,text="       ")))
    Try(tkfocus(entry.UserName))
    Try(tkbind(entry.UserName, "<Return>",onOK))
    Try(tkbind(ttGetUserName, "<Destroy>", function(){Try(tkgrab.release(ttGetUserName));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
    Try(tkwait.window(ttGetUserName))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    #########################
    #password
    Try(ttGetUserPw<-tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.deiconify(ttGetUserPw))
    Try(tkgrab.set(ttGetUserPw))
    Try(tkfocus(ttGetUserPw))
    Try(tkwm.title(ttGetUserPw,"NetAffx User Password"))
    Try(tkgrid(tklabel(ttGetUserPw,text="    ")))
    Try(UserPwText <- "")
    Try(Local.UserPw <- tclVar(init=UserPwText))
    Try(entry.UserPw <-tkentry(ttGetUserPw,width="20",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.UserPw,bg="white"))
    Try(tkgrid(tklabel(ttGetUserPw,text="Please enter your NetAffx User Password.",font=.affylmGUIglobals$affylmGUIfont2)))
    Try(tkgrid(entry.UserPw))
    onOK <- function()
    {
       Try(UserPwText <- tclvalue(Local.UserPw))
       if(nchar(UserPwText)==0)
           UserPwText <- "Unselected"
       Try(assign("UserPwText",UserPwText,affylmGUIenvironment))
       Try(tclvalue(.affylmGUIglobals$UserPwTcl) <- UserPwText)
       Try(tkgrab.release(ttGetUserPw));Try(tkdestroy(ttGetUserPw));Try(tkfocus(.affylmGUIglobals$ttMain))
    }
    Try(OK.but <-tkbutton(ttGetUserPw,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(tklabel(ttGetUserPw,text="    ")))
    Try(tkgrid(OK.but))
    Try(tkgrid.configure(OK.but))
    Try(tkgrid(tklabel(ttGetUserPw,text="       ")))
    Try(tkfocus(entry.UserPw))
    Try(tkbind(entry.UserPw, "<Return>",onOK))
    Try(tkbind(ttGetUserPw, "<Destroy>", function(){Try(tkgrab.release(ttGetUserPw));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
    Try(tkwait.window(ttGetUserPw))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    #########################
    Try(username.tmp <- get("UserNameText", env=affylmGUIenvironment))
    Try(userpw.tmp <- get("UserPwText", env=affylmGUIenvironment))
    if(username.tmp != "Unselected" & userpw.tmp != "Unselected"){
         Try(rsrc <- NetAffxResource(user = username.tmp, password = userpw.tmp, affxLicence = "BIOCON0808"))
         Try(rsrc)
         #selecting the annotation to be updated
         Try(ttIfDialog<-tktoplevel(.affylmGUIglobals$ttMain))
         Try(tkwm.deiconify(ttIfDialog))
         Try(tkgrab.set(ttIfDialog))
         Try(tkfocus(ttIfDialog))
         Try(tkwm.title(ttIfDialog,"Defining the Gene level annotation file to be updated"))
         Try(tkgrid(tklabel(ttIfDialog,text="    ")))
         Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
         Try(HowManyQuestion1 <- tklabel(frame1,text="Select the genechip of interest",font=.affylmGUIglobals$affylmGUIfont2))
         Try(tkgrid(HowManyQuestion1))
         Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
         Try(netaffxTcl <- tclVar("none"))
         Try(I1.but  <- tkradiobutton(frame1,text="Human exon genechip: HuEx",variable=netaffxTcl,value="HuEx",font=.affylmGUIglobals$affylmGUIfont2))
 #        Try(I2.but  <- tkradiobutton(frame1,text="Human gene genechip: HuGene",variable=netaffxTcl,value="HuGene-",font=.affylmGUIglobals$affylmGUIfont2))
         Try(I3.but  <- tkradiobutton(frame1,text="Mouse exon genechip: MoEx",variable=netaffxTcl,value="MoEx",font=.affylmGUIglobals$affylmGUIfont2))
 #        Try(I4.but  <- tkradiobutton(frame1,text="Mouse gene genechip: MoGene",variable=netaffxTcl,value="MoGene-",font=.affylmGUIglobals$affylmGUIfont2))
         Try(I5.but  <- tkradiobutton(frame1,text="Rat exon genechip: RaEx",variable=netaffxTcl,value="RaEx",font=.affylmGUIglobals$affylmGUIfont2))
  #       Try(I6.but  <- tkradiobutton(frame1,text="Rat gene genechip: RaGene",variable=netaffxTcl,value="RaGene-",font=.affylmGUIglobals$affylmGUIfont2))
         Try(I7.but  <- tkradiobutton(frame1,text="None",variable=netaffxTcl,value="none",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(I6.but,sticky="w"))
         Try(tkgrid(I7.but,sticky="w"))
         Try(tkgrid.configure(HowManyQuestion1,I1.but,I3.but,I5.but,I7.but,sticky="w"))
         Try(onOK <- function()
         {
             Try(ReturnNetaffx <<- as.character(tclvalue(netaffxTcl)))
             Try(tkgrab.release(ttIfDialog))
             Try(tkdestroy(ttIfDialog))
             Try(tkfocus(.affylmGUIglobals$ttMain))
         })
         Try(frame3 <- tkframe(ttIfDialog,borderwidth=2))
         Try(onCancel <- function() {
              Try(tkgrab.release(ttIfDialog))
              Try(tkdestroy(ttIfDialog))
              Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
         })
         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,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(ReturnNetaffx == "none"){
                Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
          	    Try(tkfocus(.affylmGUIglobals$ttMain))
                Try(return())
         }
         if(ReturnNetaffx != "none"){
               Try(annos <- rsrc[[grep(ReturnNetaffx, names(rsrc))]])
               #gene level
               Try(anno <- affxAnnotation(annos)[[grep("Transcript Cluster Annotations, CSV", affxDescription(rsrc[[grep(ReturnNetaffx, names(rsrc))]]))]])   #"transcript clusters Annotation, CSV Format"
               Try(df <- readAnnotation(rsrc, annotation = anno, content=FALSE))
               Try(df1 <- as.character(unlist(strsplit(df, ".zip"))))
               Try(df1 <- as.character(unlist(strsplit(df1,'/'))))
               Try(df1 <- df1[length(df1)])
               Try(conn <- unz(df, df1))
               Try(tmp <- readLines(conn, n=500))
               Try(myskip <- grep("transcript_cluster_id", tmp))
               Try(df.ann <- read.csv(conn, skip= (myskip - 1), header=T, as.is=T))
               Try(df.ann <- df.ann[,which(names(df.ann)%in%c("probeset_id", "gene_assignment"))])
               #IMPORTANT to build the GENE level oneChannelGUI annotation file I use only the first assignment mapped on the gen_assignment field in the annotation files
               
               geneAnnExtraction <- function(x){
                                                 mx <- strsplit(x, '//')
                                                 mx <- as.vector(unlist(mx))
                                                 if(length(mx) >= 4){
                                                       mx <- mx[1:4]
                                                       mxtmp <- gsub(" ", "", mx[c(1:2,4)])
                                                       mx <- c(mxtmp[1:2], mx[3], mxtmp[3])
                                                       return(mx)
                                                 } else{
                                                     mx <- rep(NA, 4)
                                                     return(mx)
                                                 }
                                    }
               
               myann <- sapply(df.ann[,2], geneAnnExtraction)
               myann <- t(myann)
               rownames(myann) <- df.ann[,1]
               df.ann <- cbind(df.ann[,1], myann)
               df.ann <- as.data.frame(df.ann)
               names(df.ann) <- c("PROBESETID","ACC","SYMBOL","DESCRIPTION","CYTOBAND")
               
               #exon level
               if(length(grep("Probeset Annotations, CSV Format", affxDescription(rsrc[[grep(ReturnNetaffx, names(rsrc))]]))) > 0){
                 Try(annops <- affxAnnotation(annos)[[grep("Probeset Annotations, CSV Format", affxDescription(rsrc[[grep(ReturnNetaffx, names(rsrc))]]))]])   #"exon probe set level Annotation, CSV Format"
                 Try(dfps <- readAnnotation(rsrc, annotation = annops, content=FALSE))
                 Try(df1ps <- as.character(unlist(strsplit(dfps, ".zip"))))
                 Try(df1ps <- as.character(unlist(strsplit(df1ps,'/'))))
                 Try(df1ps <- df1ps[length(df1ps)])
                 Try(connps <- unz(dfps, df1ps))

                 Try(tmpps <- readLines(connps, n=500))
                 Try(myskipps <- grep("probeset_id", tmpps))
                 Try(df.annps <- read.csv(connps, skip= (myskipps - 1), header=T, as.is=T))
                 Try(df.annps <- df.annps[,which(names(df.annps)%in%c("probeset_id", "seqname", "strand", "start", "stop", "transcript_cluster_id","level"))])
                 Try(names(df.annps) <- c("EPROBESETID", "CHR", "STRAND", "START", "STOP", "GPROBESETID","ANNLEVEL"))
               }
               ####
               if(ReturnNetaffx == "HuEx"){
                       huex.annotation <- df.ann
                       save(huex.annotation, file="huex.annotation.rda", ascii=T)
                       #hs exon-level probesets
                       cat("\nCreating annotation for Hs exon-level probesets. \nBased on USCS golden path data from hg19 genome release\n")
                       download.file("ftp://hgdownload.cse.ucsc.edu/goldenPath/hg19/database/affyAllExonProbes.txt.gz", "affyAllExonProbes.txt.gz", mode="wb")
                       cat(".")
                       zz <- gzfile("affyAllExonProbes.txt.gz","r")
                       cat(".")
                       tmp <- readLines(con=zz)
                       cat(".")
                       close(zz)
                       tmp <- strsplit(tmp, "\t")
                       cat(".")
                       tmp <- as.data.frame(do.call(rbind, tmp), stringsAsFactors=F)
                       cat(".")
                       names(tmp) <- c("X", "CHR", "START", "STOP", "NAME", "SCORE", "STRAND")
                       tmp1 <- tmp$NAME
                       tmp1 <- strsplit(as.character(tmp1), "\\|")
                       cat(".")
                       eid <- sapply(tmp1, function(x)x[1])
                       cat(".")
                       eann <- sapply(tmp1, function(x)x[2])
                       cat(".")
                       crosshybhuex.annotation <- data.frame(eid, as.character(tmp[,2]), as.character(tmp[,3]), as.character(tmp[,4]), as.character(tmp[,7]), eann, as.character(tmp[,6]), stringsAsFactors=F)
                       names(crosshybhuex.annotation) <- c("EPROBESETID", "CHR", "START", "STOP", "STRAND", "ANNLEVEL", "SCORE")
                       cat(".")
                       df.annps <- df.annps[which(df.annps$EPROBESETID %in% crosshybhuex.annotation$EPROBESETID),]
                       crosshybhuex.annotation <- crosshybhuex.annotation[which(crosshybhuex.annotation$EPROBESETID %in% df.annps$EPROBESETID),]
                       df.annps <- df.annps[order(df.annps$EPROBESETID),]
                       crosshybhuex.annotation <- crosshybhuex.annotation[order(crosshybhuex.annotation$EPROBESETID),]
                       if(identical(as.character(df.annps$EPROBESETID), crosshybhuex.annotation$EPROBESETID)){
                                     crosshybhuex.annotation <- cbind(crosshybhuex.annotation$EPROBESETID, as.character(df.annps$GPROBESETID), crosshybhuex.annotation[,2:dim(crosshybhuex.annotation)[2]])
                                     names(crosshybhuex.annotation)[1] <- "EPROBESETID"
                                     names(crosshybhuex.annotation)[2] <- "GPROBESETID"
                                     save(crosshybhuex.annotation, file="crosshybhuex.annotation.rda")
                       } else{
                                     cat("\nInternal error in buildingLocalAnnotation function. \nPlease report to oneChannelGUI maintainer raffaele.calogero@unito.it\n")
                                      Try(tkfocus(.affylmGUIglobals$ttMain))
                                     return()
                       }
               }
               if(ReturnNetaffx == "HuGene-"){
                       hugene.annotation <- df.ann
                       save(hugene.annotation, file="hugene.annotation.rda", ascii=T)
               }
               if(ReturnNetaffx == "MoEx"){
                       moex.annotation <- df.ann
                       save(moex.annotation, file="moex.annotation.rda", ascii=T)
                       #mm exon-level probesets
                       cat("\nCreating annotation for Mm exon-level probesets. \nBased on USCS golden path data from mm9 genome release\n")
                       download.file("ftp://hgdownload.cse.ucsc.edu/goldenPath/mm9/database/affyAllExonProbes.txt.gz", "affyAllExonProbes.txt.gz", mode="wb")
                       cat(".")
                       zz <- gzfile("affyAllExonProbes.txt.gz","r")
                       cat(".")
                       tmp <- readLines(con=zz)
                       cat(".")
                       close(zz)
                       tmp <- strsplit(tmp, "\t")
                       cat(".")
                       tmp <- as.data.frame(do.call(rbind, tmp), stringsAsFactors=F)
                       cat(".")
                       names(tmp) <- c("X", "CHR", "START", "STOP", "NAME", "SCORE", "STRAND")
                       tmp1 <- tmp$NAME
                       tmp1 <- strsplit(as.character(tmp1), "\\|")
                       cat(".")
                       eid <- sapply(tmp1, function(x)x[1])
                       cat(".")
                       eann <- sapply(tmp1, function(x)x[2])
                       cat(".")
                       crosshybmoex.annotation <- data.frame(eid, as.character(tmp[,2]), as.character(tmp[,3]), as.character(tmp[,4]), as.character(tmp[,7]), eann, as.character(tmp[,6]), stringsAsFactors=F)
                       names(crosshybmoex.annotation) <- c("EPROBESETID", "CHR", "START", "STOP", "STRAND", "ANNLEVEL", "SCORE")
                       cat(".")
                       df.annps <- df.annps[which(df.annps$EPROBESETID %in% crosshybmoex.annotation$EPROBESETID),]
                       crosshybmoex.annotation <- crosshybmoex.annotation[which(crosshybmoex.annotation$EPROBESETID %in% df.annps$EPROBESETID),]
                       df.annps <- df.annps[order(df.annps$EPROBESETID),]
                       crosshybmoex.annotation <- crosshybmoex.annotation[order(crosshybmoex.annotation$EPROBESETID),]
                       if(identical(as.character(df.annps$EPROBESETID), crosshybmoex.annotation$EPROBESETID)){
                                     crosshybmoex.annotation <- cbind(crosshybmoex.annotation$EPROBESETID, as.character(df.annps$GPROBESETID), crosshybmoex.annotation[,2:dim(crosshybmoex.annotation)[2]])
                                     names(crosshybmoex.annotation)[1] <- "EPROBESETID"
                                     names(crosshybmoex.annotation)[2] <- "GPROBESETID"
                                     save(crosshybmoex.annotation, file="crosshybmoex.annotation.rda")
                       } else{
                                     cat("\nInternal error in buildingLocalAnnotation function. \nPlease report to oneChannelGUI maintainer raffaele.calogero@unito.it\n")
                                      Try(tkfocus(.affylmGUIglobals$ttMain))
                                     return()
                       }
               }
               if(ReturnNetaffx == "MoGene-"){
                       mogene.annotation <- df.ann
                       save(mogene.annotation, file="mogene.annotation.rda", ascii=T)
               }
               if(ReturnNetaffx == "RaEx"){
                       raex.annotation <- df.ann
                       save(raex.annotation, file="raex.annotation.rda", ascii=T)
                       #rm exon-level probesets
                       cat("\nCreating annotation for Rn exon-level probesets. \nBased on USCS golden path data from rn4 genome release\n")
                       download.file("ftp://hgdownload.cse.ucsc.edu/goldenPath/rn4/database/affyAllExonProbes.txt.gz", "affyAllExonProbes.txt.gz", mode="wb")
                       cat(".")
                       zz <- gzfile("affyAllExonProbes.txt.gz","r")
                       cat(".")
                       tmp <- readLines(con=zz)
                       cat(".")
                       close(zz)
                       tmp <- strsplit(tmp, "\t")
                       cat(".")
                       tmp <- as.data.frame(do.call(rbind, tmp), stringsAsFactors=F)
                       cat(".")
                       names(tmp) <- c("X", "CHR", "START", "STOP", "NAME", "SCORE", "STRAND")
                       tmp1 <- tmp$NAME
                       tmp1 <- strsplit(as.character(tmp1), "\\|")
                       cat(".")
                       eid <- sapply(tmp1, function(x)x[1])
                       cat(".")
                       eann <- sapply(tmp1, function(x)x[2])
                       cat(".")
                       crosshybraex.annotation <- data.frame(eid, as.character(tmp[,2]), as.character(tmp[,3]), as.character(tmp[,4]), as.character(tmp[,7]), eann, as.character(tmp[,6]), stringsAsFactors=F)
                       names(crosshybraex.annotation) <- c("EPROBESETID", "CHR", "START", "STOP", "STRAND", "ANNLEVEL", "SCORE")
                       cat(".")
                       df.annps <- df.annps[which(df.annps$EPROBESETID %in% crosshybraex.annotation$EPROBESETID),]
                       crosshybraex.annotation <- crosshybraex.annotation[which(crosshybraex.annotation$EPROBESETID %in% df.annps$EPROBESETID),]
                       df.annps <- df.annps[order(df.annps$EPROBESETID),]
                       crosshybraex.annotation <- crosshybraex.annotation[order(crosshybraex.annotation$EPROBESETID),]
                       if(identical(as.character(df.annps$EPROBESETID), crosshybraex.annotation$EPROBESETID)){
                                     crosshybraex.annotation <- cbind(crosshybraex.annotation$EPROBESETID, as.character(df.annps$GPROBESETID), crosshybraex.annotation[,2:dim(crosshybraex.annotation)[2]])
                                     names(crosshybraex.annotation)[1] <- "EPROBESETID"
                                     names(crosshybraex.annotation)[2] <- "GPROBESETID"
                                     save(crosshybraex.annotation, file="crosshybraex.annotation.rda")
                       } else{
                                     cat("\nInternal error in buildingLocalAnnotation function. \nPlease report to oneChannelGUI maintainer raffaele.calogero@unito.it\n")
                                      Try(tkfocus(.affylmGUIglobals$ttMain))
                                     return()
                       }
               }
               if(ReturnNetaffx == "RaGene-"){
                       ragene.annotation <- df.ann
                       save(ragene.annotation, file="ragene.annotation.rda", ascii=T)
               }
               
               Try(tkmessageBox(title="Annotation data update",message=paste("\n", ReturnNetaffx, "annotation file was correctly updated in oneChannelGUI\n"),type="ok",icon="info"))
               Try(zz <- file(netaffxUpdates, "a"))  # open an output file connection
               Try(writeLines(paste(ReturnNetaffx, "annotation file was updated on", as.character(Sys.Date())), zz))
               Try(close(zz))
         }
    } else {
         Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
         Try(tkmessageBox(title="Annotation update",message="User or password for netaffx was not inserted!",type="ok",icon="error"))
   	     Try(tkfocus(.affylmGUIglobals$ttMain))
         Try(return())
    }
    
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
     Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(return())
}
################################################################################
"refseqDownload" <- function(){
       Try(tkfocus(.affylmGUIglobals$ttMain))
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
       Try(aptDir <- get("aptDir",envir=affylmGUIenvironment))
       Try(home <- getwd())
       Try(blastDir <- paste(aptDir, "/blast/", sep=""))
       Try(setwd(blastDir))
       Try(cat("\nBegin downloads of fasta files.....\n"))
       Try(cat("Be patient!\n"))
       #require(Biostrings) || stop("library Biostrings could not be found !")
       Try(download.file("ftp://ftp.ncbi.nih.gov/refseq/H_sapiens/mRNA_Prot/human.rna.fna.gz", "human.rna.fna.gz", mode="wb"))
       #Try(refseq <- read.DNAStringSet(zz, "fasta"))
       #Try(write.XStringSet(refseq, file="hs.fa", format="fasta"))
       Try(download.file("ftp://ftp.ncbi.nih.gov/refseq/M_musculus/mRNA_Prot/mouse.rna.fna.gz", "mouse.rna.fna.gz", mode="wb"))
       Try(download.file("ftp://ftp.ncbi.nih.gov/refseq/R_norvegicus/mRNA_Prot/rat.rna.fna.gz", "rat.rna.fna.gz", mode="wb"))
       Try(cat("\nEnd downloads of 3 RefSeq fasta files.....\n"))
       Try(mbVal <- tkmessageBox(title="RefSeq Fasta",
				    											message=paste("Do you wish to unpack manually the gz files in ", getwd(), "\n If you answer NO oneChannelGUI will handle unpacking,\nbut the procedure can be quite long. Be patient!"),
						    									icon="question",type="yesno",default="no"
								    						 )#end of tkmessageBox
		  )#end of Try(mbVal..
    	if(tclvalue(mbVal)=="yes"){
			            Try(tkfocus(.affylmGUIglobals$ttMain))
			            Try(cat("\nRefSeq fasta gz files are located in ", getwd(),"\n"))
			            Try(setwd(home))
			            return()
		  }
      Try(zz <- gzfile("human.rna.fna.gz", "r"))
      Try(refseq <- readFASTA(zz, strip.desc=TRUE))
      Try(writeFASTA(refseq, file="human.rna.fna", width=80))
      Try(zz <- gzfile("mouse.rna.fna.gz", "r"))
      Try(refseq <- readFASTA(zz, strip.desc=TRUE))
      Try(writeFASTA(refseq, file="mouse.rna.fna", width=80))
      Try(zz <- gzfile("rat.rna.fna.gz", "r"))
      Try(refseq <- readFASTA(zz, strip.desc=TRUE))
      Try(writeFASTA(refseq, file="rat.rna.fna", width=80))
                 
      Try(cat("\nRefSeq fasta files are ready to be used in ", getwd(),"\n"))
      Try(setwd(home))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
       Try(tkfocus(.affylmGUIglobals$ttMain))              
}

################################################################################
#"madscrosshybDownload" <- function(){
#    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
#    Try(home <- getwd())
#    Try(libDirLocation <- paste(path.package("oneChannelGUI", quiet = FALSE), "/affylibs/", sep = ""))
#    Try(setwd(libDirLocation))
    #gathering affy libs and apt tools folders
#    Try(cat("\nBegin downloads of MADS CrossHyb data.....\n"))
#    Try(cat("Be patient!\n"))
#    Try(download.file("http://biogibbs.stanford.edu/~yxing/MADS/Human_CrossHyb.txt", "Human_CrossHyb.txt", mode="w"))
#    Try(download.file("http://biogibbs.stanford.edu/~yxing/MADS/Mouse_CrossHyb.txt", "Mouse_CrossHyb.txt", mode="w"))
#    Try(download.file("http://biogibbs.stanford.edu/~yxing/MADS/Human_CrossHyb_core.txt", "Human_CrossHyb_core.txt", mode="w"))
#    Try(download.file("http://biogibbs.stanford.edu/~yxing/MADS/Mouse_CrossHyb_core.txt", "Mouse_CrossHyb_core.txt", mode="w"))
#    Try(cat("\nEnd downloads of Human and Mouse MADS crosshyb files.....\n"))
#    hs <- read.table("Human_CrossHyb_core.txt", sep="\t", header=T, as.is=T)
    
    #building a mps without crosshyb exon probe sets, selecting bad probes on the basis of MADS approach
#    mm <- read.table("Mouse_CrossHyb_core.txt", sep="\t", header=T, as.is=T)
#    crossRefs <- which(mm$MaxCorrCrossHybRefseqEvidence > 0)
    #hist(MaxCorrWithCrossHybTranscript[crossRefs])
#    mm.cross <- mm[crossRefs,]
#    mm.cross <- mm.cross[which(mm.cross$MaxCorrWithCrossHybTranscript >= 0.2),]
#    mps <- mps[grep("core", mps)]
#    mps <- mps[grep("mps$", mps)]
#    mps.df <- read.table(mps, sep="\t", header=T, as.is=T)
#    for(i in 1:dim(mm.cross)[1]){
#      tmp <- mps.df[which(mps.df[,2] == mm.cross$TranscriptClusterId[1]),]
#      tmp.p <- as.character(unlist(strsplit(as.character(tmp[3])," ")))
#      tmp.p <- tmp.p[which(tmp.p != as.character(mm.cross$ProbesetId[1]))]
#      tmp.p <- paste(tmp.p, collapse=" ")
#      mps.df[which(mps.df[,2] == mm.cross$TranscriptClusterId[1]),3] <- tmp.p
      #write.table.....
#    } 
#    Try(setwd(home))
#}

################################################################################
"updateLibs" <- function(){
     Try(tkfocus(.affylmGUIglobals$ttMain))
     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
     Try(mbVal <- tkmessageBox(title="Updating Bioconductor Libraries",
				    											message="You are updating all Bioconductor libraries files. \nThe process might take some time!", icon="question",type="yesno",default="yes"
								    						 )#end of tkmessageBox
		  )#end of Try(mbVal..
    	if(tclvalue(mbVal)=="no"){
			            Try(tkfocus(.affylmGUIglobals$ttMain))
                  return()
		  }
      source("http://bioconductor.org/biocLite.R")
      update.packages(repos=biocinstallRepos(), ask=FALSE)
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
       Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(return())
}
################################################################################
#inernal function used in variantExons
".outvsp" <- function(ov, affyR, vspR, chr, genome){
              # myout <- list("affyname"=names(affyR)[ov[2]],"affystart"=start(affyR)[ov[2]], 
              #                "affyend"=end(affyR)[ov[2]], "affywidth"=width(affyR)[ov[2]],
              #                "vspname"=names(vspR)[ov[1]],"vspstart"=start(vspR)[ov[1]], 
              #                "vspend"=end(vspR)[ov[1]], "vspwidth"=width(vspR)[ov[1]])
              affyname <- strsplit(names(affyR)[ov[2]],"\\.")[[1]][1]
              affystrand <- strsplit(names(affyR)[ov[2]],"\\.")[[1]][2]
              vspname <- strsplit(names(vspR)[ov[1]],"\\.")[[1]][1]
              vspstrand <- strsplit(names(vspR)[ov[1]],"\\.")[[1]][2]
              
              myout <- c(affyname,start(affyR)[ov[2]],end(affyR)[ov[2]], width(affyR)[ov[2]], affystrand,
                         vspname, start(vspR)[ov[1]], end(vspR)[ov[1]], width(vspR)[ov[1]], vspstrand,as.character(sub("chr","", chr)), genome)
   
}

"variantExons" <- function(){
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
    #require(IRanges) || stop("\nMissing IRanges library\n")
    #loading exon level annotation
 for(j in c("huex","moex","raex")){
    out.all <- NULL
   if(j=="huex"){
                 genome <- "organism=Human&version=hg19"
               
                data(HuExExonProbesetLocation)
                 subject<- get("HuExExonProbesetLocation",envir=.GlobalEnv)
   }
   if(j=="moex"){  
                 genome <- "organism=Mouse&version=mm9"
                
                 data(MoExExonProbesetLocation)
                 subject<- get("MoExExonProbesetLocation",envir=.GlobalEnv)
   }
   if(j=="raex"){
                 genome <- "organism=Rattus&version=rn4"
                 
                 data(RaExExonProbesetLocation)
                 subject<- get("RaExExonProbesetLocation",envir=.GlobalEnv)
   }
   #retrieving variant exon file
   vsp.file <- paste("http://www6.unito.it/RRE/Query/ensembleQuery.php?", genome, sep="")
   tmpfile <- tempfile(tmpdir = getwd())
   download.file(vsp.file, tmpfile, mode="w")
   query <- read.table(tmpfile, header=T, as.is=T, sep="\t")
   chr <- unique(query$chromosome)
   chr <- chr[setdiff(seq(1,length(chr)),grep("_", chr))]
   exoncore <-  subject[which(subject$ANNLEVEL == "core"),]
   for(i in chr){
      vsp.tmp <- query[which(query$chromosome==i),]
      vspRanges <- IRanges(start=vsp.tmp$start, end=vsp.tmp$end, names=paste(vsp.tmp$"transcript_id", vsp.tmp$"strand", sep="."))
      #retrieving exon level annotation
      exonchr <-  subject[which(subject$CHR == i),]
      affyRanges <- IRanges(start=as.numeric(exonchr$START), end=as.numeric(exonchr$STOP), names=paste(as.character(exonchr$EPROBESETID),exonchr$STRAND,sep="."))
      ov <- findOverlaps(affyRanges, query=vspRanges)
      ov <- matchMatrix(ov)
      out <- apply(ov, 1,.outvsp, affyR=affyRanges, vspR=vspRanges, chr=i, genome=genome)
      out <- t(out)
      out <- out[which(out[,5] == out[,10]),]
      out.all <- rbind(out.all, out)
   }   
   dimnames(out.all)[[2]] <-  c("affyname", "affystart", "affyend", "affywidth", "affystrand","vspname", "vspstart", "vspend", "vspwidth","vspstrand","chr","genome")
   if(j == "huex"){
                       huex.variantexons <- out.all
                       save(huex.variantexons, file="huex.variantexons.rda", ascii=T)
                       cat("\n huex.variantexons.rda variant exons dataset is now ready to be now copied in oneChannelGUI data dir\n")
   }
   if(j == "moex"){
                       moex.variantexons <- out.all
                       save(moex.variantexons, file="moex.variantexons.rda", ascii=T)
                       cat("\n moex.variantexons.rda variant exons dataset is now ready to be now copied in oneChannelGUI data dir\n")
   }
   if(j == "raex"){
                       raex.variantexons <- out.all
                       save(raex.variantexons, file="raex.variantexons.rda", ascii=T)
                       cat("\n raex.variantexons.rda variant exons dataset is now ready to be now copied in oneChannelGUI data dir\n")
   }
 }
 Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkfocus(.affylmGUIglobals$ttMain))
}
################################################################################
"exportFASTA" <- function(){
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  #require(Biostrings) || stop("\nMissing Biostrings library\n")
  #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.1<-tkradiobutton(ttGetOrganism,text="R. norvegicus",variable=ttGetOrganismTcl,value="rn",font=.affylmGUIglobals$affylmGUIfont2))
 Try(rbIQR.15<-tkradiobutton(ttGetOrganism,text="B. taurus",variable=ttGetOrganismTcl,value="bo",font=.affylmGUIglobals$affylmGUIfont2))
 
  Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.5))
	Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.25))
  Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.1))
  Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.15))

	Try(tkgrid.configure(rbIQR.5,rbIQR.25,rbIQR.1, rbIQR.15,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"))
  #miRbase19
  Try(load(paste(find.package(package="oneChannelGUI"),"/data/hairpin.rda",sep="")))
  if(ReturnVal == ""){
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
       Try(return())
  } else if (ReturnVal == "hs"){
       #hsa precursor
       Try(hsfa <- hairpin[grep("^hsa-",names(hairpin))])
       Try(writeXStringSet(hsfa, file="ncHs.fa"))
       Try(tkmessageBox(title="FASTA reference file",message="The fasta reference file for non-coding RNA quantification is saved in ncHs.fa\n Use it for mapping NGS reads",type="ok", icon="info"))
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
        Try(tkfocus(.affylmGUIglobals$ttMain))
       Try(return())
  } else if (ReturnVal == "mm"){
       #mmu precursor
       Try(mmfa <- hairpin[grep("^hsa-",names(hairpin))])
       Try(writeXStringSet(mmfa, file="ncMm.fa"))
       Try(tkmessageBox(title="FASTA reference file",message="The fasta reference file for non-coding RNA quantification is saved in ncMm.fa\n Use it for mapping NGS reads",type="ok", icon="info"))
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
        Try(tkfocus(.affylmGUIglobals$ttMain))
       Try(return())
  } else if (ReturnVal == "rn"){
       #rno precursor
      Try(rnfa <- hairpin[grep("^rno-",names(hairpin))])
       Try(writeXStringSet(rnfa, file="ncRn.fa"))
       Try(tkmessageBox(title="FASTA reference file",message="The fasta reference file for non-coding RNA quantification is saved in ncRn.fa\n Use it for mapping NGS reads",type="ok", icon="info"))
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
        Try(tkfocus(.affylmGUIglobals$ttMain))
       Try(return())

  }
  else if (ReturnVal == "bo"){
       #bta precursor
      Try(bofa <- hairpin[grep("^bta-",names(hairpin))])
       Try(writeXStringSet(bofa, file="ncBo.fa"))
       Try(tkmessageBox(title="FASTA reference file",message="The fasta reference file for non-coding RNA quantification is saved in ncBo.fa\n Use it for mapping NGS reads",type="ok", icon="info"))
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
        Try(tkfocus(.affylmGUIglobals$ttMain))
       Try(return())

  }
}
################################################################################
"ngsperlDownload" <- function(){
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(tkmessageBox(title="NGS perl scripts",message="This routine creates a folder for the perl scripts used to reformat NGS primary mapping output."))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(myWD <- getwd())
      #Try(SetWD())
      Try(perlDirLocation <- get("perlDirLocation",envir=affylmGUIenvironment))
      if(perlDirLocation != ""){
             Try(mbVal <- tkmessageBox(title="NGS perl scripts",
				    											message="There already a folder defined for NGS perl scripts.\nDo you want to change it?",
						    									icon="question",type="yesno",default="no"
								    						 )#end of tkmessageBox
		        )#end of Try(mbVal..
    	      if(tclvalue(mbVal)=="no"){
			            Try(tkfocus(.affylmGUIglobals$ttMain))
			            Try(setwd(myWD))
			            return()
		        } 
     }
     Try(perlDirLocation  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/ngsperl", sep=""))
     Try(dir.create(perlDirLocation, showWarnings = TRUE, recursive = FALSE))
     Try(setwd(perlDirLocation))
     Try(assign("perlDirLocation", perlDirLocation, affylmGUIenvironment))#directory where NGS perl scripts are located
     Try(cat("\nBegin downloads of NGS scripts.....\n"))
     Try(download.file("http://sourceforge.net/projects/ochguiextras/files/ngsperl.zip/download", "ngsperl.zip", mode="wb"))
     if(.Platform$OS.type=="windows"){
                            Try(unzip("ngsperl.zip"))
                       #     Try(setwd("ngsperl"))
                       #     Try(system('XCOPY /S *.* ..'))
                       #     Try(setwd(".."))
     } else{
                            Try(system(paste("unzip ngsperl.zip", sep="")))
                       #     Try(setwd("ngsperl"))
                       #     Try(system("mv * .."))
                       #     Try(setwd(".."))
     }
     Try(cat("\nEnd unzip NGS scripts.....\n"))
     Try(cat("\nNGS scripts are ready to be used in ", getwd(),"\n"))
     #save the info to be recovered in a new session
     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]=="perlDirLocation"),2] <- perlDirLocation)
     Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
     Try(assign("perlDirLocation", perlDirLocation, affylmGUIenvironment))
     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(tkfocus(.affylmGUIglobals$ttMain))
     Try(setwd(myWD))
}
################################################################################
"meVDownload" <- function(){
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
      Try(tkmessageBox(title="meV software",message="This routine creates a folder to install the meV software."))
      Try(myWD <- getwd())
      #Try(SetWD())
      Try(meVDirLocation.Available <- get("meVDirLocation.Available",envir=affylmGUIenvironment))
      if(meVDirLocation.Available){
             Try(mbVal <- tkmessageBox(title="meV software",
				    											message="There already a folder defined for meV software.\nDo you want to change it?",
						    									icon="question",type="yesno",default="no"
								    						 )#end of tkmessageBox
		        )#end of Try(mbVal..
    	      if(tclvalue(mbVal)=="no"){
			            Try(tkfocus(.affylmGUIglobals$ttMain))
			            Try(setwd(myWD))
			            return()
		        } 
     }
     Try(meVDirLocation  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/meV", sep=""))
     Try(dir.create(meVDirLocation, showWarnings = TRUE, recursive = FALSE))
     Try(setwd(meVDirLocation))
     Try(assign("meVDirLocation", meVDirLocation, affylmGUIenvironment))#directory where NGS perl scripts are located
     Try(cat("\nBegin downloads of meV.....\n"))
     #defining which program to be downloaded
     Try(ttGetMev <- tktoplevel(.affylmGUIglobals$ttMain))
     Try(tkwm.deiconify(ttGetMev))
     Try(tkgrab.set(ttGetMev))
     Try(tkfocus(ttGetMev))
     Try(tkwm.title(ttGetMev,"Which OS are you using?"))
	
     Try(tkgrid(tklabel(ttGetMev,text="    ")))
     Try(ttGetMevTcl <- tclVar("win"))
     Try(rbIQR.win <- tkradiobutton(ttGetMev,text="windows                  ",variable=ttGetMevTcl,value="win",font=.affylmGUIglobals$affylmGUIfont2))
     Try(rbIQR.mac<-tkradiobutton(ttGetMev,text="mac                  ",variable=ttGetMevTcl,value="mac",font=.affylmGUIglobals$affylmGUIfont2))
     Try(rbIQR.linux<-tkradiobutton(ttGetMev,text="linux               ",variable=ttGetMevTcl,value="linux",font=.affylmGUIglobals$affylmGUIfont2))
     
     Try(tkgrid(tklabel(ttGetMev,text="    "),rbIQR.win))
     Try(tkgrid(tklabel(ttGetMev,text="    "),rbIQR.mac))
     Try(tkgrid(tklabel(ttGetMev,text="    "),rbIQR.linux))

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

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

     Try(tkbind(ttGetMev,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetMev));Try(tkfocus(.affylmGUIglobals$ttMain));}))
     Try(tkbind(OK.but, "<Return>",onOK))
     Try(tkbind(Cancel.but, "<Return>",onCancel))      
     Try(tkwait.window(ttGetMev))
     if(ReturnVal=="win"){
            Try(download.file("http://sourceforge.net/projects/mev-tm4/files/mev-tm4/MeV%204.8/MeV_4_8_0_r2721_win.zip/download", "mev.zip", mode="wb"))
            Try(unzip("mev.zip"))
            Try(setwd("MeV_4_8_0"))
            Try(system('XCOPY /S *.* ..'))
            Try(setwd(".."))

            Try(cat("\nThe MeV downloaded version is MeV_4_8_0\n"))
     } else if (ReturnVal=="mac"){
            Try(download.file("http://sourceforge.net/projects/mev-tm4/files/mev-tm4/MeV%204.8/MeV_4_8_0_r2721_mac.tgz/download", "mev.tgz", mode="wb"))
            Try(system(paste("gzip -d ","mev.tgz", sep="")))
            Try(system(paste("tar xvf ","mev.tar", sep="")))
            Try(cat("\nThe MeV downloaded version is MeV_4_8_0\n"))
            Try(setwd("MeV_4_8_0"))
            Try(system("cp -fR * .."))
            Try(setwd(".."))
            Try(system("rm -fR MeV_4_8_0"))
     } else if (ReturnVal=="linux"){
            Try(download.file("http://sourceforge.net/projects/mev-tm4/files/mev-tm4/MeV%204.8/MeV_4_8_0_r2721_linux.tar.gz/download", "mev.tar.gz", mode="wb"))
           Try(system(paste("gzip -d ","mev.tar.gz", sep="")))
            Try(system(paste("tar xvf ","mev.tar", sep="")))
            Try(cat("\nThe MeV downloaded version is MeV_4_8_0\n"))
            Try(setwd("MeV_4_8_0"))
            Try(system("cp -fR * .."))
            Try(setwd(".."))
     }
     Try(cat("\nEnd unzip meV files.....\n"))
     Try(cat("\nMeV software is ready to be used in ", getwd(),"\n"))
     #save the info to be recovered in a new session
     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]=="meVDirLocation"),2] <- meVDirLocation)
     Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
     Try(assign("meVDirLocation", meVDirLocation, affylmGUIenvironment))
     assign("meVDirLocation.Available",TRUE,affylmGUIenvironment)
     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(tkfocus(.affylmGUIglobals$ttMain))
     Try(setwd(myWD))
}
################################################################################
#external package info
"extPckInfo" <- function(){
     Try(etcDir  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/etc", sep=""))
     Try(localdata <- paste(etcDir, "/localData.txt", sep=""))
     Try(tmp <- system("perl -v 2>&1", intern = T))
     Try(if(length(tmp) > 0) perl.version <- tmp[2])
#     Try(tmp <- system("python -V 2>&1", intern = T))
#     Try(if(length(tmp) > 0) python.version <- tmp)
     Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
     Try(perlDirLocation <- get("perlDirLocation",envir=affylmGUIenvironment))
#     Try(pythonDirLocation <- get("pythonDirLocation",envir=affylmGUIenvironment))
     Try(bowtieRefs <- get("bowtieRefs",envir=affylmGUIenvironment))
     Try(installed <- names(bowtieRefs)[which(bowtieRefs=="Y")])
     
     Try(tkmessageBox(title="External Packages associated to oneChannelGUI",message=paste("Affymetrix libraries: ", myinfo[1,2],
                                                                                          "\nAPT tools: ",myinfo[2,2],
                                                                                          "\nmeV clustering tool: ",myinfo[3,2],
                                                                                          "\nBowtie short reads aligner: ",myinfo[4,2],
                                                                                          "\nJava: ",myinfo[5,2],
                                                                                          "\nBowtie genomes: ", paste(installed, collapse=", "),
                                                                                          "\nPerl software: ", perl.version,
                                                                                          "\nPerl scripts: ", perlDirLocation,
                                                                                          "\n",sep="")))
     Try(tkfocus(.affylmGUIglobals$ttMain))                                                                                      
}
################################################################################
"combining2eSet" <- function(){
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(tkmessageBox(title="combining two datasets",message="This routine combines two matrices having the same number of row and the same row identifiers."))
    Try(tempFileName1 <- tclvalue(tkgetOpenFile(filetypes = "{{Text Files} {.txt}} {{All files} *}")))
    if (!nchar(tempFileName1)) {
                tkfocus(.affylmGUIglobals$ttMain)
                return()
    }
    Try(mySel1 <- read.table(tempFileName1, sep = "\t", header = T, as.is = TRUE, row.names=1))
    Try(tempFileName2 <- tclvalue(tkgetOpenFile(filetypes = "{{Text Files} {.txt}} {{All files} *}")))
    if (!nchar(tempFileName2)) {
                tkfocus(.affylmGUIglobals$ttMain)
                return()
    }
    Try(mySel2 <- read.table(tempFileName2, sep = "\t", header = T, as.is = TRUE, row.names=1))
    
    Try(mySel1 <- mySel1[order(rownames(mySel1)),])
    Try(mySel2 <- mySel2[order(rownames(mySel2)),])
    if(identical(rownames(mySel1), rownames(mySel2))){
        tempFileName1 <- unlist(strsplit(tempFileName1, "/"))
        tempFileName1 <- tempFileName1[length(tempFileName1)]
        tempFileName1 <- sub(".txt$", "", tempFileName1) 
        tempFileName2 <- unlist(strsplit(tempFileName2, "/"))
        tempFileName2 <- tempFileName2[length(tempFileName2)]
        tempFileName2 <- sub(".txt$", "", tempFileName2) 
        tempFileName <- paste(tempFileName1, "_", tempFileName2,".txt",sep="")
        Try(mySel <- cbind(mySel1, mySel2))
        Try(write.table(mySel, file = tempFileName,  sep = "\t", quote = FALSE, col.names = NA))
        Try(tkmessageBox(title="Combining two datasets",message=paste("The combined dataset is available in",getwd(),"as",tempFileName,sep="\n")))
         Try(tkfocus(.affylmGUIglobals$ttMain))
        Try(return())
    } else{
      Try(tkmessageBox(title="Combining datasets",message="The two datasets do not have the same row identifiers.\nThey cannot be combined!",icon="error"))
       Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(return())                
    }
     Try(tkfocus(.affylmGUIglobals$ttMain))
}
################################################################################
#using bowtieDownload I can also call the function to download or build the ref genomes for bowtie
#alos downloading tophat and cufflinks
"bowtieDownload" <- function(){
      Try(tkfocus(.affylmGUIglobals$ttMain))
    #  Try(require(Biostrings) || stop("library Biostrings could not be found !"))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
      Try(myWD <- getwd())
      Try(tkmessageBox(title="Bowtie primary mapping of short reads",message="This routine creates a folder to install the bowtie software and \nPicard tools to handle SAM files."))

#      Try(libDirLocation <- get("libDirLocation",envir=affylmGUIenvironment))
#      if(libDirLocation == ""){
#                    Try(.downloadLibs())
#                    Try(setwd(myWD))
#                     Try(tkfocus(.affylmGUIglobals$ttMain))
#      }
      Try(binDir.Available <- get("binDir.Available",envir=affylmGUIenvironment))
      if(!binDir.Available){
	       Try(setBinDir())
	  }
	  #download fastQC
     Try(cat("\nDownloading the fastQC java tool for qc analysis of fastq files\n"))
     Try(fastqcDirLocation  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/FastQC", sep=""))
     Try(assign("fastqcDirLocation", fastqcDirLocation, affylmGUIenvironment))#directory where NGS perl scripts are located
     Try(setwd(path.package("oneChannelGUI", quiet = FALSE)))
     Try(download.file("http://www.bioinformatics.babraham.ac.uk/projects/fastqc/fastqc_v0.11.2.zip", "fastqc.zip", mode="wb"))
     Try(unzip("fastqc.zip"))
     Try(cat("\nThe fastQC downloaded version is fastqc_v0.11.2\n"))
     Try(assign("fastqcDirLocation", fastqcDirLocation, affylmGUIenvironment))
     Try(assign("fastqcDirLocation.Available",TRUE,affylmGUIenvironment))
     #download bowtie
     Try(bowtieDirLocation.Available <- get("bowtieDirLocation.Available",envir=affylmGUIenvironment))
      if(bowtieDirLocation.Available){
             Try(mbVal <- tkmessageBox(title="Bowtie software",
				    											message="There already a folder defined for bowtie software.\nDo you want to change it?",
						    									icon="question",type="yesno",default="no"
								    						 )#end of tkmessageBox
		        )#end of Try(mbVal..
    	      if(tclvalue(mbVal)=="no"){
			            Try(tkfocus(.affylmGUIglobals$ttMain))
			            Try(bowtieDirLocation <- get("bowtieDirLocation",envir=affylmGUIenvironment))
			            Try(setwd(bowtieDirLocation))
		              Try(.bowtieGenomes())
		              Try(setwd(myWD))
	                Try(tkfocus(.affylmGUIglobals$ttMain))
		              Try(return())
		        } 
     }
     Try(bowtieDirLocation  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/bowtie", sep=""))
     Try(dir.create(bowtieDirLocation, showWarnings = TRUE, recursive = FALSE))
     Try(setwd(bowtieDirLocation))
     Try(assign("bowtieDirLocation", bowtieDirLocation, affylmGUIenvironment))#directory where NGS perl scripts are located
     Try(cat("\nBegin downloads of bowtie.....\n"))
     #defining which program to be downloaded
     Try(ttGetBowtie <- tktoplevel(.affylmGUIglobals$ttMain))
     Try(tkwm.deiconify(ttGetBowtie))
     Try(tkgrab.set(ttGetBowtie))
     Try(tkfocus(ttGetBowtie))
     Try(tkwm.title(ttGetBowtie,"Which OS are you using?"))
	
     Try(tkgrid(tklabel(ttGetBowtie,text="    ")))
     Try(ttGetBowtieTcl <- tclVar("win32"))
     Try(rbIQR.win32 <- tkradiobutton(ttGetBowtie,text="windows                  ",variable=ttGetBowtieTcl,value="win32",font=.affylmGUIglobals$affylmGUIfont2))
     Try(rbIQR.mac32<-tkradiobutton(ttGetBowtie,text="mac 32 bits                 ",variable=ttGetBowtieTcl,value="mac32",font=.affylmGUIglobals$affylmGUIfont2))
     Try(rbIQR.mac64<-tkradiobutton(ttGetBowtie,text="mac 64 bits                  ",variable=ttGetBowtieTcl,value="mac64",font=.affylmGUIglobals$affylmGUIfont2))
     Try(rbIQR.linux32<-tkradiobutton(ttGetBowtie,text="linux 32 bits              ",variable=ttGetBowtieTcl,value="linux32",font=.affylmGUIglobals$affylmGUIfont2))
     Try(rbIQR.linux64<-tkradiobutton(ttGetBowtie,text="linux 64 bits               ",variable=ttGetBowtieTcl,value="linux64",font=.affylmGUIglobals$affylmGUIfont2))
     
     Try(tkgrid(tklabel(ttGetBowtie,text="    "),rbIQR.win32))
     Try(tkgrid(tklabel(ttGetBowtie,text="    "),rbIQR.mac32))
     Try(tkgrid(tklabel(ttGetBowtie,text="    "),rbIQR.mac64))
     Try(tkgrid(tklabel(ttGetBowtie,text="    "),rbIQR.linux32))
     Try(tkgrid(tklabel(ttGetBowtie,text="    "),rbIQR.linux64))

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

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

     Try(tkbind(ttGetBowtie,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetBowtie));Try(tkfocus(.affylmGUIglobals$ttMain));}))
     Try(tkbind(OK.but, "<Return>",onOK))
     Try(tkbind(Cancel.but, "<Return>",onCancel))      
     Try(tkwait.window(ttGetBowtie))
     #down-loading gene leve scaffolds
     Try(cat("\nDownloading the gene-level scaffolds for human mouse and rat.\nThose scaffolds are used to build gne-oriented eSets containing RNA-seq mapped data\n"))
     Try(download.file("http://sourceforge.net/projects/ochguiextras/files/gene-level_USCS.GRanges/rn4_gene-level.scaffold.Rda/download", "rn4_gene-level.scaffold.Rda", mode="wb"))
     Try(cat("\nThe The gene-level scaffolds for Rat genome were correctly downloaded\n"))
     Try(download.file("http://sourceforge.net/projects/ochguiextras/files/gene-level_USCS.GRanges/mm9_gene-level.scaffold.Rda/download", "mm9_gene-level.scaffold.Rda", mode="wb"))
     Try(cat("\nThe The gene-level scaffolds for Mouse genome were correctly downloaded\n"))
     Try(download.file("http://sourceforge.net/projects/ochguiextras/files/gene-level_USCS.GRanges/hg19_gene-level.scaffold.Rda/download", "hg19_gene-level.scaffold.Rda", mode="wb"))
     Try(cat("\nThe The gene-level scaffolds for Human genome were correctly downloaded\n"))
     #download mirbase latest
     Try(download.file("ftp://mirbase.org/pub/mirbase/CURRENT/hairpin.fa.zip", "hairpin.fa.zip", mode="wb"))
     #Try(system("gzip -d hairpin.fa.gz"))
	 Try(unzip("hairpin.fa.zip"))
     Try(cat("\nLatest miRbase was correctly downloaded\n"))
     Try(hairpin <- readRNAStringSet("hairpin.fa"))
     Try(hairpin <- DNAStringSet(hairpin))
     Try(save(hairpin,file=paste(find.package(package="oneChannelGUI"),"/data/hairpin.rda",sep="")))

     if(ReturnVal=="win32"){
	        Try(setwd(bowtieDirLocation))
            Try(download.file("http://sourceforge.net/projects/bowtie-bio/files/bowtie/1.1.1/bowtie-1.1.1-mingw-x86_64.zip/download", "bowtie.zip", mode="wb"))
            Try(unzip("bowtie.zip"))
            Try(cat("\nThe Bowtie downloaded version is bowtie_1_1_1\n"))
            Try(setwd("bowtie-1.1.1"))
            Try(system('XCOPY /S *.* ..'))
            Try(setwd(".."))
	        Try(assign("bowtieDirLocation", bowtieDirLocation, affylmGUIenvironment))
	        Try(assign("bowtieDirLocation.Available",TRUE,affylmGUIenvironment))
     } else if (ReturnVal=="mac32"){
	        Try(setwd(bowtieDirLocation))
            Try(download.file("http://sourceforge.net/projects/bowtie-bio/files/bowtie/0.12.7/bowtie-0.12.7-macos-10.5-i386.zip/download", "bowtie.zip", mode="wb"))
            Try(unzip("bowtie.zip"))
            Try(cat("\nThe Bowtie downloaded version is bowtie_0_12_7\n"))

            Try(system(paste("unzip bowtie.zip", sep="")))
            Try(system("cp -fR ./bowtie-0.12.7/* ."))
            Try(system("rm -fR ./bowtie-0.12.7/"))
	        Try(assign("bowtieDirLocation", bowtieDirLocation, affylmGUIenvironment))
	        Try(assign("bowtieDirLocation.Available",TRUE,affylmGUIenvironment))
     } else if (ReturnVal=="mac64"){
	        Try(setwd(bowtieDirLocation))
            Try(download.file("http://sourceforge.net/projects/bowtie-bio/files/bowtie/1.1.1/bowtie-1.1.1-macos-x86_64.zip/download", "bowtie.zip", mode="wb"))
            Try(unzip("bowtie.zip"))
            Try(cat("\nThe Bowtie downloaded version is bowtie_1_1_1\n"))
            Try(system("cp -fR ./bowtie-1.1.1/* ."))
            Try(system("rm -fR ./bowtie-1.1.1/"))
	        Try(assign("bowtieDirLocation", bowtieDirLocation, affylmGUIenvironment))
	        Try(assign("bowtieDirLocation.Available",TRUE,affylmGUIenvironment))
			#tophat
			            Try(tophatDirLocation  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/tophat", sep=""))
				        Try(dir.create(tophatDirLocation, showWarnings = TRUE, recursive = FALSE))
				        Try(setwd(tophatDirLocation))
				        Try(cat("\nBegin downloads of tophat.....\n"))
			            Try(download.file("http://ccb.jhu.edu/software/tophat/downloads/tophat-2.0.13.OSX_x86_64.tar.gz", "tophat.tar.gz", mode="wb"))
			            Try(system("gzip -d tophat.tar.gz"))
			            Try(system("tar xvf tophat.tar"))
			            Try(cat("\nThe TopHat downloaded version is tophat-2.0.411.OSX_x86_64\n"))
			            Try(system("cp -fR ./tophat-2.0.13.OSX_x86_64/* ."))
			            Try(system("rm -fR ./tophat-2.0.13.OSX_x86_64/"))
			            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]=="tophatDirLocation"),2] <- tophatDirLocation)
				        Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
				        Try(assign("tophatDirLocation", tophatDirLocation, affylmGUIenvironment))
				        Try(assign("tophatDirLocation.Available",TRUE,affylmGUIenvironment))
			#cufflinks
			            Try(cuffDirLocation  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/cufflinks", sep=""))
				        Try(dir.create(cuffDirLocation, showWarnings = TRUE, recursive = FALSE))
				        Try(setwd(cuffDirLocation))
				        Try(cat("\nBegin downloads of cufflinks.....\n"))
			            Try(download.file("http://cole-trapnell-lab.github.io/cufflinks/assets/downloads/cufflinks-2.2.1.OSX_x86_64.tar.gz", "cufflinks.tar.gz", mode="wb"))
			            Try(system("gzip -d cufflinks.tar.gz"))
			            Try(system("tar xvf cufflinks.tar"))
			            Try(cat("\nThe Cufflinks downloaded version is cufflinks-2.1.1.OSX_x86_64\n"))
			            Try(system("cp -fR ./cufflinks-2.2.1.OSX_x86_64/* ."))
			            Try(system("rm -fR ./cufflinks-2.2.1.OSX_x86_64/"))
			            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]=="cuffDirLocation"),2] <- cuffDirLocation)
				        Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
				        Try(assign("cuffDirLocation", cuffDirLocation, affylmGUIenvironment))
				        Try(assign("cuffDirLocation.Available",TRUE,affylmGUIenvironment))
		     #samtools  
		                Try(samtoolsDirLocation <- paste(path.package("oneChannelGUI", quiet = FALSE), "/samtools", sep=""))
				        Try(dir.create(samtoolsDirLocation, showWarnings = TRUE, recursive = FALSE))
				        Try(setwd(samtoolsDirLocation))
				        Try(cat("\nBegin downloads of samtools.....\n"))
			            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/tools/samtools_mac64.tar.gz/download", "samtools.tar.gz", mode="wb"))
			            Try(system("gzip -d samtools.tar.gz"))
			            Try(system("tar xvf samtools.tar"))
			            Try(cat("\nThe Samtools downloaded version is samtools-0.1.18\n"))
			            Try(system("cp -fR ./samtools-0.1.18/* ."))
			            Try(system("rm -fR ./samtools-0.1.18/"))
			            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]=="samtoolsDirLocation"),2] <- cuffDirLocation)
				        Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
				        Try(assign("samtoolsDirLocation", samtoolsDirLocation, affylmGUIenvironment))
				        Try(assign("samtoolsDirLocation.Available",TRUE,affylmGUIenvironment))
                        Try(tuxedoSetup())

     } else if (ReturnVal=="linux32"){
	        Try(setwd(bowtieDirLocation))
            Try(download.file("http://sourceforge.net/projects/bowtie-bio/files/bowtie/0.12.7/bowtie-0.12.7-linux-i386.zip/download", "bowtie.zip", mode="wb"))
            Try(system(paste("unzip bowtie.zip", sep="")))
            Try(cat("\nThe Bowtie downloaded version is bowtie_0_12_7\n"))
            Try(system(paste("unzip bowtie.zip", sep="")))
            Try(system("cp -fR ./bowtie-0.12.7/* ."))
            Try(system("rm -fR ./bowtie-0.12.7/"))
            Try(assign("bowtieDirLocation", bowtieDirLocation, affylmGUIenvironment))
	        Try(assign("bowtieDirLocation.Available",TRUE,affylmGUIenvironment))
     } else if (ReturnVal=="linux64"){
	        Try(setwd(bowtieDirLocation))
            Try(download.file("http://sourceforge.net/projects/bowtie-bio/files/bowtie/1.1.1/bowtie-1.1.1-linux-x86_64.zip/download", "bowtie.zip", mode="wb"))
            Try(cat("\nThe Bowtie downloaded version is bowtie_1_1_1\n"))
            Try(system(paste("unzip bowtie.zip", sep="")))
            Try(system("cp -fR ./bowtie-1.1.1/* ."))
            Try(system("rm -fR ./bowtie-1.1.1/"))
	        Try(assign("bowtieDirLocation", bowtieDirLocation, affylmGUIenvironment))
	        Try(assign("bowtieDirLocation.Available",TRUE,affylmGUIenvironment))
			#tophat
			            Try(tophatDirLocation  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/tophat", sep=""))
				        Try(dir.create(tophatDirLocation, showWarnings = TRUE, recursive = FALSE))
				        Try(setwd(tophatDirLocation))
				        Try(cat("\nBegin downloads of tophat.....\n"))
			            Try(download.file("http://ccb.jhu.edu/software/tophat/downloads/tophat-2.0.13.Linux_x86_64.tar.gz", "tophat.tar.gz", mode="wb"))
			            Try(system("gzip -d tophat.tar.gz"))
			            Try(system("tar xvf tophat.tar"))
			            Try(cat("\nThe TopHat downloaded version is tophat-2.0.11.Linux_x86_64\n"))
			            Try(system("cp -fR ./tophat-2.0.13.Linux_x86_64/* ."))
			            Try(system("rm -fR ./tophat-2.0.13.Linux_x86_64/"))
			            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]=="tophatDirLocation"),2] <- tophatDirLocation)
				        Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
				        Try(assign("tophatDirLocation", tophatDirLocation, affylmGUIenvironment))
				        Try(assign("tophatDirLocation.Available",TRUE,affylmGUIenvironment))
				        Try(cat("\nEnd unzip tophat files.....\n"))
			#cufflinks
			            Try(cuffDirLocation  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/cufflinks", sep=""))
				        Try(dir.create(cuffDirLocation, showWarnings = TRUE, recursive = FALSE))
				        Try(setwd(cuffDirLocation))
				        Try(cat("\nBegin downloads of cufflinks.....\n"))
			            Try(download.file("http://cole-trapnell-lab.github.io/cufflinks/assets/downloads/cufflinks-2.2.1.Linux_x86_64.tar.gz", "cufflinks.tar.gz", mode="wb"))
			            Try(system("gzip -d cufflinks.tar.gz"))
			            Try(system("tar xvf cufflinks.tar"))
			            Try(cat("\nThe TopHat downloaded version is cufflinks-2.2.1.Linux_x86_64\n"))
			            Try(system("cp -fR ./cufflinks-2.2.1.Linux_x86_64/* ."))
			            Try(system("rm -fR ./ccufflinks-2.2.1.Linux_x86_64/"))
			            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]=="cuffDirLocation"),2] <- cuffDirLocation)
				        Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
				        Try(assign("cuffDirLocation", cuffDirLocation, affylmGUIenvironment))
				        Try(assign("cuffDirLocation.Available",TRUE,affylmGUIenvironment))
                        Try(cat("\nEnd unzip cufflinks files.....\n"))
		#samtools  
				        Try(samtoolsDirLocation <- paste(path.package("oneChannelGUI", quiet = FALSE), "/samtools", sep=""))
						Try(dir.create(samtoolsDirLocation, showWarnings = TRUE, recursive = FALSE))
						Try(setwd(samtoolsDirLocation))
						Try(cat("\nBegin downloads of samtools.....\n"))
					    Try(download.file("http://sourceforge.net/projects/ochguiextras/files/tools/samtools_linux64.tar.gz/download", "samtools.tar.gz", mode="wb"))
					    Try(system("gzip -d samtools.tar.gz"))
					    Try(system("tar xvf samtools.tar"))
					    Try(cat("\nThe Samtools downloaded version is samtools-0.1.18\n"))
					    Try(system("cp -fR ./samtools-0.1.18/* ."))
					    Try(system("rm -fR ./samtools-0.1.18/"))
					    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]=="samtoolsDirLocation"),2] <- cuffDirLocation)
						Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
						Try(assign("samtoolsDirLocation", samtoolsDirLocation, affylmGUIenvironment))
						Try(assign("samtoolsDirLocation.Available",TRUE,affylmGUIenvironment))
                        Try(tuxedoSetup())
     }
     Try(cat("\nEnd unzip Bowtie files.....\n"))
     Try(cat("\nStart download of Picard tools for sam to bam conversion.....\n"))
     #non ti dimenticare di aggiustare tuttui i nuovi nomi se modifichi la versione di picard
     Try(setwd(bowtieDirLocation))
     Try(download.file("http://sourceforge.net/projects/picard/files/picard-tools/1.119/picard-tools-1.119.zip/download", "picard.zip", mode="wb"))
     Try(cat("\nThe Picard downloaded version is picard-tools-1.115\n"))
     if(ReturnVal=="win32"){
            Try(unzip("picard.zip"))
            Try(setwd("picard-tools-1.119"))
            Try(system('XCOPY /S *.* ..'))
            Try(setwd(".."))
     } else{
            Try(system(paste("unzip picard.zip", sep="")))
            Try(system("cp -fR ./picard-tools-1.119/* ."))
            Try(system("rm -fR ./picard-tools-1.119/"))
            Try(system("chmod -fR +x *"))
     }
     Try(cat("\nBowtie and Picard tools are ready to be used in ", getwd(),"\n"))
     #save the info to be recovered in a new session
     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]=="bowtieDirLocation"),2] <- bowtieDirLocation)
     Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
     Try(cat("\nInstalling bowtie reference sequences for miRNA analysis....\n"))

     Try(cat("\nStart building Hs...\n"))
     Try(hsfa <- hairpin[grep("^hsa-",names(hairpin))])
     Try(writeXStringSet(hsfa, file="ncHs.fa"))
     if(.Platform$OS.type=="windows"){
                Try(system("bowtie-build.exe -f ncHs.fa hs_nc"))
     } else if(.Platform$OS.type!="windows" ){
               Try(system(paste(bowtieDirLocation,"/bowtie-build -f ncHs.fa hs_nc", sep="")))
     }
     Try(cat("\nThe fasta reference file for Hs miRNA has been indexed for Illumina data mapping with bowtie\n"))
     Try(cat("\nStart building Mm...\n"))
     Try(mmfa <- hairpin[grep("^mmu-",names(hairpin))])
     Try(writeXStringSet(mmfa, file="ncMm.fa"))
     if(.Platform$OS.type=="windows" ){
                Try(system("bowtie-build.exe -f ncMm.fa mm_nc"))
     } else if(.Platform$OS.type!="windows" ){
                Try(system(paste(bowtieDirLocation,"/bowtie-build -f ncMm.fa mm_nc", sep="")))
     }
     Try(cat("\nThe fasta reference file for Mm miRNA has been indexed for Illumina data mapping with bowtie\n"))
     Try(cat("\nStart building Rn...\n"))
     Try(rnfa <- hairpin[grep("^rno-",names(hairpin))])
     Try(writeXStringSet(rnfa, file="ncRn.fa"))
     if(.Platform$OS.type=="windows" ){
                Try(system("bowtie-build.exe -f ncRn.fa rn_nc"))
     } else if(.Platform$OS.type!="windows" ){
               Try(system(paste(bowtieDirLocation,"/bowtie-build -f ncRn.fa rn_nc",sep="")))
     }
     Try(cat("\nThe fasta reference file for Rn miRNA has been indexed for Illumina data mapping with bowtie\n"))
     Try(cat("\nStart building Bo...\n"))
     Try(bofa <- hairpin[grep("^bta-",names(hairpin))])
     Try(writeXStringSet(bofa, file="ncBo.fa"))
     if(.Platform$OS.type=="windows" ){
                Try(system("bowtie-build.exe -f ncBo.fa bo_nc"))
     } else if(.Platform$OS.type!="windows" ){
               Try(system(paste(bowtieDirLocation,"/bowtie-build -f ncBo.fa bo_nc", sep="")))
     }
     Try(cat("\nThe fasta reference file for Bovine miRNA has been indexed for Illumina data mapping with bowtie\n"))
     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
     Try(tkfocus(.affylmGUIglobals$ttMain))
     Try(tkmessageBox(title="Bowtie primary mapping of short reads",message="Bowtie is installed with the miRNA precursors sets\nIf you wish to install other reference genomes, please use the function:\nDownload and build hs, mm, rn bowtie reference sets."))
     Try(setwd(myWD))
     #test if java path is defined
     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(myWD <- getwd())
     Try(javaDir <- myinfo[which(myinfo[,1]== "javaDir"),2])
     if(is.na(javaDir)){javaDir <- ""}
     if(javaDir == ""){
          Try(tmp.java <- NULL)
          Try(tmp.java <- system("java -version 2>&1", intern=T))
          if(length(grep("Java", tmp.java)) == 0){
              Try(tkmessageBox(title="Bowtie primary mapping of short reads",message="It seems that java dir is not defined in the system path.\nPlease provide the path for java.\nIn windows should be C:/somewhere/Java/jre6.", icon="error"))
              Try(javaFolder())
          }
     }
     Try(tkfocus(.affylmGUIglobals$ttMain))      
}
################################################################################
################################################################################
"bowtieGenomes" <- function(){
     Try(ptm <- proc.time())
     
    # Try(require(R.utils) || stop("\nMissing R.utils library!\n"))
     Try(tkfocus(.affylmGUIglobals$ttMain))
     #Try(require(Biostrings) || stop("library Biostrings could not be found !"))
     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(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]))
     #which ref
     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("hg19e"))
     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("\nStart Downloading and building chromosome references for bowtie primary mapping.\n"))
     Try(cat("\nBe patient! Download and installation will take a while...\n"))
     
     Try(bowtieRefs <- get("bowtieRefs",envir=affylmGUIenvironment))
     #creating the gene-level scaffold to upload the reads
     Try(gene.scaffold <- makeGeneScaffold(whichRef = ReturnVal1))
     
     #Please not that if bowtie annotation is available the corresponding gene-level scaffold is also present
     #therefore for each bowtieRefs == Y there is also the gene-level scaffold
     if(.Platform$OS.type=="windows" && ReturnVal1=="hg19"){
            Try(cat("\nDownloading Chr22\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_22/hs_ref_GRCh37.p2_chr22.fa.gz", "chr22.fa.gz", mode="wb"))
            Try(gunzip("chr22.fa.gz"))
            Try(system("bowtie-build.exe -f chr22.fa hs_chr22"))
            Try(file.remove("chr22.fa"))
            Try(cat("\nDownloading Chr21\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_21/hs_ref_GRCh37.p2_chr21.fa.gz", "chr21.fa.gz", mode="wb"))
            Try(gunzip("chr21.fa.gz"))
            Try(system("bowtie-build.exe -f chr21.fa hs_chr21"))
            Try(file.remove("chr21.fa"))
            Try(cat("\nDownloading Chr20\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_20/hs_ref_GRCh37.p2_chr20.fa.gz", "chr20.fa.gz", mode="wb"))
            Try(gunzip("chr20.fa.gz"))
            Try(system("bowtie-build.exe -f chr20.fa hs_chr20"))
            Try(file.remove("chr20.fa"))
            Try(cat("\nDownloading Chr19\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_19/hs_ref_GRCh37.p2_chr19.fa.gz", "chr19.fa.gz", mode="wb"))
            Try(gunzip("chr19.fa.gz"))
            Try(system("bowtie-build.exe -f chr19.fa hs_chr19"))
            Try(file.remove("chr19.fa"))
            Try(cat("\nDownloading Chr18\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_18/hs_ref_GRCh37.p2_chr18.fa.gz", "chr18.fa.gz", mode="wb"))
            Try(gunzip("chr18.fa.gz"))
            Try(system("bowtie-build.exe -f chr18.fa hs_chr18"))
            Try(file.remove("chr18.fa"))
            Try(cat("\nDownloading Chr17\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_17/hs_ref_GRCh37.p2_chr17.fa.gz", "chr17.fa.gz", mode="wb"))
            Try(gunzip("chr17.fa.gz"))
            Try(system("bowtie-build.exe -f chr17.fa hs_chr17"))
            Try(file.remove("chr17.fa"))
            Try(cat("\nDownloading Chr16\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_16/hs_ref_GRCh37.p2_chr16.fa.gz", "chr16.fa.gz", mode="wb"))
            Try(gunzip("chr16.fa.gz"))
            Try(system("bowtie-build.exe -f chr16.fa hs_chr16"))
            Try(file.remove("chr16.fa"))
            Try(cat("\nDownloading Chr15\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_15/hs_ref_GRCh37.p2_chr15.fa.gz", "chr15.fa.gz", mode="wb"))
            Try(gunzip("chr15.fa.gz"))
            Try(system("bowtie-build.exe -f chr15.fa hs_chr15"))
            Try(file.remove("chr15.fa"))
            Try(cat("\nDownloading Chr14\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_14/hs_ref_GRCh37.p2_chr14.fa.gz", "chr14.fa.gz", mode="wb"))
            Try(gunzip("chr14.fa.gz"))
            Try(system("bowtie-build.exe -f chr14.fa hs_chr14"))
            Try(file.remove("chr14.fa"))
            Try(cat("\nDownloading Chr13\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_13/hs_ref_GRCh37.p2_chr13.fa.gz", "chr13.fa.gz", mode="wb"))
            Try(gunzip("chr13.fa.gz"))
            Try(system("bowtie-build.exe -f chr13.fa hs_chr13"))
            Try(file.remove("chr13.fa"))
            Try(cat("\nDownloading Chr12\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_12/hs_ref_GRCh37.p2_chr12.fa.gz", "chr12.fa.gz", mode="wb"))
            Try(gunzip("chr12.fa.gz"))
            Try(system("bowtie-build.exe -f chr12.fa hs_chr12"))
            Try(file.remove("chr12.fa"))
            Try(cat("\nDownloading Chr11\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_11/hs_ref_GRCh37.p2_chr11.fa.gz", "chr11.fa.gz", mode="wb"))
            Try(gunzip("chr11.fa.gz"))
            Try(system("bowtie-build.exe -f chr11.fa hs_chr11"))
            Try(file.remove("chr11.fa"))
            Try(cat("\nDownloading Chr10\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_10/hs_ref_GRCh37.p2_chr10.fa.gz", "chr10.fa.gz", mode="wb"))
            Try(gunzip("chr10.fa.gz"))
            Try(system("bowtie-build.exe -f chr10.fa hs_chr10"))
            Try(file.remove("chr10.fa"))
            Try(cat("\nDownloading Chr9\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_09/hs_ref_GRCh37.p2_chr9.fa.gz", "chr09.fa.gz", mode="wb"))
            Try(gunzip("chr09.fa.gz"))
            Try(system("bowtie-build.exe -f chr09.fa hs_chr09"))
            Try(file.remove("chr09.fa"))
            Try(cat("\nDownloading Chr8\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_08/hs_ref_GRCh37.p2_chr8.fa.gz", "chr08.fa.gz", mode="wb"))
            Try(gunzip("chr08.fa.gz"))
            Try(system("bowtie-build.exe -f chr08.fa hs_chr08"))
            Try(file.remove("chr08.fa"))
            Try(cat("\nDownloading Chr7\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_07/hs_ref_GRCh37.p2_chr7.fa.gz", "chr07.fa.gz", mode="wb"))
            Try(gunzip("chr07.fa.gz"))
            Try(system("bowtie-build.exe -f chr07.fa hs_chr07"))
            Try(file.remove("chr07.fa"))
            Try(cat("\nDownloading Chr6\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_06/hs_ref_GRCh37.p2_chr6.fa.gz", "chr06.fa.gz", mode="wb"))
            Try(gunzip("chr06.fa.gz"))
            Try(system("bowtie-build.exe -f chr06.fa hs_chr06"))
            Try(file.remove("chr06.fa"))
            Try(cat("\nDownloading Chr5\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_05/hs_ref_GRCh37.p2_chr5.fa.gz", "chr05.fa.gz", mode="wb"))
            Try(gunzip("chr05.fa.gz"))
            Try(system("bowtie-build.exe -f chr05.fa hs_chr05"))
            Try(file.remove("chr05.fa"))
            Try(cat("\nDownloading Chr4\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_04/hs_ref_GRCh37.p2_chr4.fa.gz", "chr04.fa.gz", mode="wb"))
            Try(gunzip("chr04.fa.gz"))
            Try(system("bowtie-build.exe -f chr04.fa hs_chr04"))
            Try(file.remove("chr04.fa"))
            Try(cat("\nDownloading Ch3\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_03/hs_ref_GRCh37.p2_chr3.fa.gz", "chr03.fa.gz", mode="wb"))
            Try(gunzip("chr03.fa.gz"))
            Try(system("bowtie-build.exe -f chr03.fa hs_chr03"))
            Try(file.remove("chr03.fa"))
            Try(cat("\nDownloading Ch2\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_02/hs_ref_GRCh37.p2_chr2.fa.gz", "chr02.fa.gz", mode="wb"))
            Try(gunzip("chr02.fa.gz"))
            Try(system("bowtie-build.exe -f chr02.fa hs_chr02"))
            Try(file.remove("chr02.fa"))
            Try(cat("\nDownloading Ch1\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_01/hs_ref_GRCh37.p2_chr1.fa.gz", "chr01.fa.gz", mode="wb"))
            Try(gunzip("chr01.fa.gz"))
            Try(system("bowtie-build.exe -f chr01.fa hs_chr01"))
            Try(file.remove("chr01.fa"))
            Try(cat("\nDownloading ChX\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_X/hs_ref_GRCh37.p2_chrX.fa.gz", "chrX.fa.gz", mode="wb"))
            Try(gunzip("chrX.fa.gz"))
            Try(system("bowtie-build.exe -f chrX.fa hs_chrX"))
            Try(file.remove("chrX.fa"))
            Try(cat("\nDownloading ChY\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_Y/hs_ref_GRCh37.p2_chrY.fa.gz", "chrY.fa.gz", mode="wb"))
            Try(gunzip("chrY.fa.gz"))
            Try(system("bowtie-build.exe -f chrY.fa hs_chrY"))
            Try(file.remove("chrY.fa"))
            Try(cat("\nDownloading ChMT\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_MT/hs_ref_GRCh37.p2_chrMT.fa.gz", "chrMT.fa.gz", mode="wb"))
            Try(gunzip("chrMT.fa.gz"))
            Try(system("bowtie-build.exe -f chrMT.fa hs_chrMT"))
            Try(file.remove("chrMT.fa"))
            Try(bowtieRefs[1] <- "Y")
     } else if(.Platform$OS.type!="windows" && ReturnVal1=="hg19"){
            Try(cat("\nDownloading Chr22\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_22/hs_ref_GRCh37.p2_chr22.fa.gz", "chr22.fa.gz", mode="wb"))
            Try(gunzip("chr22.fa.gz"))
            Try(system("bowtie-build -f chr22.fa hs_chr22"))
            Try(file.remove("chr22.fa"))
            Try(cat("\nDownloading Chr21\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_21/hs_ref_GRCh37.p2_chr21.fa.gz", "chr21.fa.gz", mode="wb"))
            Try(gunzip("chr21.fa.gz"))
            Try(system("bowtie-build -f chr21.fa hs_chr21"))
            Try(file.remove("chr21.fa"))
            Try(cat("\nDownloading Chr20\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_20/hs_ref_GRCh37.p2_chr20.fa.gz", "chr20.fa.gz", mode="wb"))
            Try(gunzip("chr20.fa.gz"))
            Try(system("bowtie-build -f chr20.fa hs_chr20"))
            Try(file.remove("chr20.fa"))
            Try(cat("\nDownloading Chr19\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_19/hs_ref_GRCh37.p2_chr19.fa.gz", "chr19.fa.gz", mode="wb"))
            Try(gunzip("chr19.fa.gz"))
            Try(system("bowtie-build -f chr19.fa hs_chr19"))
            Try(file.remove("chr19.fa"))
            Try(cat("\nDownloading Chr18\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_18/hs_ref_GRCh37.p2_chr18.fa.gz", "chr18.fa.gz", mode="wb"))
            Try(gunzip("chr18.fa.gz"))
            Try(system("bowtie-build -f chr18.fa hs_chr18"))
            Try(file.remove("chr18.fa"))
            Try(cat("\nDownloading Chr17\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_17/hs_ref_GRCh37.p2_chr17.fa.gz", "chr17.fa.gz", mode="wb"))
            Try(gunzip("chr17.fa.gz"))
            Try(system("bowtie-build -f chr17.fa hs_chr17"))
            Try(file.remove("chr17.fa"))
            Try(cat("\nDownloading Chr16\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_16/hs_ref_GRCh37.p2_chr16.fa.gz", "chr16.fa.gz", mode="wb"))
            Try(gunzip("chr16.fa.gz"))
            Try(system("bowtie-build -f chr16.fa hs_chr16"))
            Try(file.remove("chr16.fa"))
            Try(cat("\nDownloading Chr15\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_15/hs_ref_GRCh37.p2_chr15.fa.gz", "chr15.fa.gz", mode="wb"))
            Try(gunzip("chr15.fa.gz"))
            Try(system("bowtie-build -f chr15.fa hs_chr15"))
            Try(file.remove("chr15.fa"))
            Try(cat("\nDownloading Chr14\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_14/hs_ref_GRCh37.p2_chr14.fa.gz", "chr14.fa.gz", mode="wb"))
            Try(gunzip("chr14.fa.gz"))
            Try(system("bowtie-build -f chr14.fa hs_chr14"))
            Try(file.remove("chr14.fa"))
            Try(cat("\nDownloading Chr13\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_13/hs_ref_GRCh37.p2_chr13.fa.gz", "chr13.fa.gz", mode="wb"))
            Try(gunzip("chr13.fa.gz"))
            Try(system("bowtie-build -f chr13.fa hs_chr13"))
            Try(file.remove("chr13.fa"))
            Try(cat("\nDownloading Chr12\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_12/hs_ref_GRCh37.p2_chr12.fa.gz", "chr12.fa.gz", mode="wb"))
            Try(gunzip("chr12.fa.gz"))
            Try(system("bowtie-build -f chr12.fa hs_chr12"))
            Try(file.remove("chr12.fa"))
            Try(cat("\nDownloading Chr11\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_11/hs_ref_GRCh37.p2_chr11.fa.gz", "chr11.fa.gz", mode="wb"))
            Try(gunzip("chr11.fa.gz"))
            Try(system("bowtie-build -f chr11.fa hs_chr11"))
            Try(file.remove("chr11.fa"))
            Try(cat("\nDownloading Chr10\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_10/hs_ref_GRCh37.p2_chr10.fa.gz", "chr10.fa.gz", mode="wb"))
            Try(gunzip("chr10.fa.gz"))
            Try(system("bowtie-build -f chr10.fa hs_chr10"))
            Try(file.remove("chr10.fa"))
            Try(cat("\nDownloading Chr09\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_09/hs_ref_GRCh37.p2_chr9.fa.gz", "chr09.fa.gz", mode="wb"))
            Try(gunzip("chr09.fa.gz"))
            Try(system("bowtie-build -f chr09.fa hs_chr09"))
            Try(file.remove("chr09.fa"))
            Try(cat("\nDownloading Chr08\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_08/hs_ref_GRCh37.p2_chr8.fa.gz", "chr08.fa.gz", mode="wb"))
            Try(gunzip("chr08.fa.gz"))
            Try(system("bowtie-build -f chr08.fa hs_chr08"))
            Try(file.remove("chr08.fa"))
            Try(cat("\nDownloading Chr07\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_07/hs_ref_GRCh37.p2_chr7.fa.gz", "chr07.fa.gz", mode="wb"))
            Try(gunzip("chr07.fa.gz"))
            Try(system("bowtie-build -f chr07.fa hs_chr7"))
            Try(file.remove("chr07.fa"))
            Try(cat("\nDownloading Chr06\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_06/hs_ref_GRCh37.p2_chr6.fa.gz", "chr06.fa.gz", mode="wb"))
            Try(gunzip("chr06.fa.gz"))
            Try(system("bowtie-build -f chr06.fa hs_chr6"))
            Try(file.remove("chr06.fa"))
            Try(cat("\nDownloading Chr5\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_05/hs_ref_GRCh37.p2_chr5.fa.gz", "chr05.fa.gz", mode="wb"))
            Try(gunzip("chr05.fa.gz"))
            Try(system("bowtie-build -f chr05.fa hs_chr05"))
            Try(file.remove("chr05.fa"))
            Try(cat("\nDownloading Chr04\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_04/hs_ref_GRCh37.p2_chr4.fa.gz", "chr04.fa.gz", mode="wb"))
            Try(gunzip("chr04.fa.gz"))
            Try(system("bowtie-build -f chr04.fa hs_chr04"))
            Try(file.remove("chr04.fa"))
            Try(cat("\nDownloading Ch03\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_03/hs_ref_GRCh37.p2_chr3.fa.gz", "chr03.fa.gz", mode="wb"))
            Try(gunzip("chr03.fa.gz"))
            Try(system("bowtie-build -f chr03.fa hs_chr3"))
            Try(file.remove("chr03.fa"))
            Try(cat("\nDownloading Ch02\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_02/hs_ref_GRCh37.p2_chr2.fa.gz", "chr02.fa.gz", mode="wb"))
            Try(gunzip("chr02.fa.gz"))
            Try(system("bowtie-build -f chr02.fa hs_chr02"))
            Try(file.remove("chr02.fa"))
            Try(cat("\nDownloading Ch01\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_01/hs_ref_GRCh37.p2_chr1.fa.gz", "chr01.fa.gz", mode="wb"))
            Try(gunzip("chr01.fa.gz"))
            Try(system("bowtie-build -f chr01.fa hs_chr01"))
            Try(file.remove("chr01.fa"))
            Try(cat("\nDownloading ChX\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_X/hs_ref_GRCh37.p2_chrX.fa.gz", "chrX.fa.gz", mode="wb"))
            Try(gunzip("chrX.fa.gz"))
            Try(system("bowtie-build -f chrX.fa hs_chrX"))
            Try(file.remove("chrX.fa"))
            Try(cat("\nDownloading ChY\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_Y/hs_ref_GRCh37.p2_chrY.fa.gz", "chrY.fa.gz", mode="wb"))
            Try(gunzip("chrY.fa.gz"))
            Try(system("bowtie-build -f chrY.fa hs_chrY"))
            Try(file.remove("chrY.fa"))
            Try(cat("\nDownloading ChMT\n"))
            Try(download.file("ftp://ftp.ncbi.nih.gov/genomes/H_sapiens/CHR_MT/hs_ref_GRCh37.p2_chrMT.fa.gz", "chrMT.fa.gz", mode="wb"))
            Try(gunzip("chrMT.fa.gz"))
            Try(system("bowtie-build -f chrMT.fa hs_chrMT"))
            Try(file.remove("chrMT.fa"))
            Try(bowtieRefs[1] <- "Y")
     }
     if(.Platform$OS.type=="windows" && ReturnVal1=="mm9"){
            cat("\nNot implemented, yet\n")
            Try(bowtieRefs[2] <- "N")
     } else if (.Platform$OS.type!="windows" && ReturnVal1=="mm9"){
           cat("\nNot implemented, yet\n")
            Try(bowtieRefs[2] <- "N")
     }
     if(.Platform$OS.type=="windows" && ReturnVal1=="rn4"){
            cat("\nNot implemented, yet\n")
            Try(bowtieRefs[3] <- "N")
     } else if (.Platform$OS.type!="windows" && ReturnVal1=="rn4"){
           cat("\nNot implemented, yet\n")
            Try(bowtieRefs[3] <- "N")
     }
     Try(assign("bowtieRefs",bowtieRefs,affylmGUIenvironment))
     Try(bowtieRefs <- paste(bowtieRefs, collapse=","))
     Try(myinfo[which(myinfo[,1]=="bowtieRefs"),2] <- bowtieRefs)
     Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))     

     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
     Try(tkfocus(.affylmGUIglobals$ttMain))
     Try(setwd(myWD))
     Try(usedtime <- proc.time() - ptm)
     Try(cat("\nUsed CPU time (min) ",usedtime[3]/60,"\n"))
     Try(cat("\nEnd downloading and building chromosome references for bowtie primary mapping.\n"))

     Try(return())
}
###############################################################################
"wrapNGS" <- function(){
   Try(mbVal <- tkmessageBox(title="Installing external software for RNA-seq",
			              message="Do you wish to install all external software needed for RNA-seq?",
			              icon="question",type="yesno",default="yes"
                )#end of tkmessageBox
   )#end of Try(mbVal..
   if(tclvalue(mbVal)=="yes"){
                     Try(tkfocus(.affylmGUIglobals$ttMain))
                     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                     Try(myWD <-getwd())
                     #gathering affy libs and apt tools folders
                     Try(localdata  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/etc/localData.txt", sep=""))
                     Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
                     Try(bowtieDirLocation <- myinfo[which(myinfo[,1]=="bowtieDirLocation"),2])  #loacation of bowtie
                     if(bowtieDirLocation==""){    
                       Try(bowtieDirLocation  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/bowtie", sep=""))
                       Try(dir.create(bowtieDirLocation, showWarnings = TRUE, recursive = FALSE))
                       Try(myinfo[which(myinfo[,1]=="bowtieDirLocation"),2] <- bowtieDirLocation)
                       Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))
                       Try(setwd(myWD))
                       Try(bowtieDownload())
                    #   ngsperlDownload()
                     }
                     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                     Try(return())
   } else{
                    Try(tkfocus(.affylmGUIglobals$ttMain))
                    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                    Try(return())
   } 
}

################################################################################
"bowtieBuilt" <- function(){
   #  Try(require(R.utils) || stop("\nMissing R.utils library!\n"))
     Try(tkfocus(.affylmGUIglobals$ttMain))
   #  Try(require(Biostrings) || stop("library Biostrings could not be found !"))
     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(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]))
     #which ref
     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("\nStart Downloading and building chromosome references for bowte primary mapping.\n"))
     Try(cat("\nBe patient! Download and installation will take a while...\n"))
     
     Try(bowtieRefs <- get("bowtieRefs",envir=affylmGUIenvironment))
     #Please not that if bowtie annotation is available the corresponding gene-level scaffold is also present
     #therefore for each bowtieRefs == Y there is also the gene-level scaffold
     if(.Platform$OS.type=="windows" && ReturnVal1=="hg19"){
            Try(cat("\nDownloading ChrX and ChrY\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chrXY.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr22\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr22.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr21\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr21.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr20\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr20.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr19\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr19.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr18\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr18.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr17\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr17.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr16\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr16.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr15\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr15.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr14\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr14.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr13\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr13.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr12\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr12.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr11\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr11.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr10\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr10.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr9\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr9.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr8\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr8.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr7\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr7.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr6\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr6.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr5\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr5.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr4\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr4.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr3\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr3.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr2\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr2.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr1\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr1.zip/download", "chr.zip", mode="wb"))
            Try(unzip("chr.zip"))
            Try(file.remove("chr.zip"))
            Try(bowtieRefs[1] <- "Y")
     } else if(.Platform$OS.type!="windows" && ReturnVal1=="hg19"){
            Try(cat("\nDownloading ChrX and ChrY\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chrXY.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr22\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr22.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr21\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr21.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr20\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr20.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr19\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr19.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr18\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr18.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr17\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr17.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr16\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr16.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr15\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr15.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr14\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr14.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr13\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr13.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr12\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr12.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr11\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr11.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr10\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr10.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr9\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr9.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr8\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr8.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr7\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr7.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr6\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr6.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr5\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr5.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr4\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr4.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr3\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr3.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr2\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr2.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(cat("\nDownloading Chr1\n"))
            Try(download.file("http://sourceforge.net/projects/ochguiextras/files/bowtie_hs/hs_chr1.zip/download", "chr.zip", mode="wb"))
            Try(system(paste("unzip chr.zip", sep="")))
            Try(file.remove("chr.zip"))
            Try(bowtieRefs[1] <- "Y")
     }
     if(.Platform$OS.type=="windows" && ReturnVal1=="mm9"){
            cat("\nNot implemented, yet\n")
            Try(bowtieRefs[2] <- "N")
     } else if (.Platform$OS.type!="windows" && ReturnVal1=="mm9"){
           cat("\nNot implemented, yet\n")
            Try(bowtieRefs[2] <- "N")
     }
     if(.Platform$OS.type=="windows" && ReturnVal1=="rn4"){
            cat("\nNot implemented, yet\n")
            Try(bowtieRefs[3] <- "N")
     } else if (.Platform$OS.type!="windows" && ReturnVal1=="rn4"){
           cat("\nNot implemented, yet\n")
            Try(bowtieRefs[3] <- "N")
     }
     Try(assign("bowtieRefs",bowtieRefs,affylmGUIenvironment))
     Try(bowtieRefs <- paste(bowtieRefs, collapse=","))
     Try(myinfo[which(myinfo[,1]=="bowtieRefs"),2] <- bowtieRefs)
     Try(write.table(myinfo, localdata, sep="\t", row.names=F, col.names=F, quote=F))     

     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
     Try(tkfocus(.affylmGUIglobals$ttMain))
     Try(setwd(myWD))
     Try(cat("\nEnd downloading built chromosome references for bowtie primary mapping.\n"))

     Try(return())

}
#####################################################################################
genomeStudioReformat <- function(){
    #loading the tab delimited file
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
      Try(tkmessageBox(title="Reformat a GenomeStudio export file",message="Open the Genome Studio exported file."))  
      Try(tempFileName <- tclvalue(tkgetOpenFile(filetypes="{{Text Files} {.txt}} {{All files} *}")))
           if(!nchar(tempFileName))
           {
              tkfocus(.affylmGUIglobals$ttMain)
              return()
           }
       ##start grabbing the first 8 lines
       Try(con <- file(tempFileName, "r", blocking = FALSE))
       Try(gsInfo <- readLines(con, n=8))
       Try(close(con))
       Try(gsInfo <- gsub("\t","",gsInfo))
       Try(mysel <- read.table(tempFileName, sep="\t", header=T, skip=8, fill=T))
       Try(refined.df <- mysel[,grep("AVG_Signal",names(mysel))])
       Try(refined.df <- refined.df[setdiff(seq(1,dim(mysel)[1]),which(duplicated(as.character(mysel$PROBE_ID)))),])
       Try(rnames <- mysel$PROBE_ID[setdiff(seq(1,dim(mysel)[1]),which(duplicated(as.character(mysel$PROBE_ID))))])
       Try(refined.df <- cbind(rnames,refined.df))
       Try(tmp.df <- matrix(rep(" ", dim(refined.df)[2]*8), nrow=8))
       Try(tmp.df[,1]<- gsInfo)
       Try(tmp.df <- rbind(tmp.df, gsub("X","",names(refined.df))))
       Try(tmp.df[9,1] <- "PROBE_ID")
       Try(write.table(tmp.df, file = paste(tempFileName,"_reformatted.txt",sep=""), sep="\t", col.names=F,row.names=F, quote=F))
       #Try(dimnames(tmp.df)[[2]] <- names(refined.df))
       #Try(tmp.df <- rbind(tmp.df,refined.df))
	   Try(write.table(refined.df, file = paste(tempFileName,"_reformatted.txt",sep=""), sep="\t", col.names=F,row.names=F, append=T, quote=F))
       Try(tkmessageBox(title="Reformat GenomeStudio output files",message=paste("The reformated file iis saved in your working directory as: ", paste(tempFileName,"_reformatted.txt",sep=""),"\nis made of ",dim(refined.df)[1]," rows and ",dim(refined.df)[2]," columns",sep=""),icon="info",type="ok"))
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
       Try(tkfocus(.affylmGUIglobals$ttMain))
       Try(return())
}
###############
setBinDir <- function(){
		Try(wd <- tclVar(getwd()))
		Try(
			if(.Platform$OS.type=="windows"){
				Try(tkmessageBox(title="Select user bin folder",message="Not implemented in windows",icon="info",type="ok"))
		        Try(return())
			}
		)
		Try(ttChooseDir <- tktoplevel(.affylmGUIglobals$ttMain))
		Try(tkwm.title(ttChooseDir,"Choose Output directory"))
		Try(tkwm.deiconify(ttChooseDir))
		Try(tkgrab.set(ttChooseDir))
		Try(tkgrid(tklabel(ttChooseDir,text="    ")))
		Try(label1 <- tklabel(ttChooseDir,text="Choose user bin directory:",font=.affylmGUIglobals$affylmGUIfont2))
		Try(tkgrid(tklabel(ttChooseDir,text="    "),label1,sticky="w"))
		Try(tkgrid.configure(label1,columnspan=3))
		Try(tkgrid(tklabel(ttChooseDir,text="    ")))
		#
		#
		Try(
			onBrowse <- function(){
				Try(if(file.exists(gsub("\\\\","/",tclvalue(wd)))) initialdir<-gsub("\\\\","/",tclvalue(wd)) else initialdir<-getwd())
				Try(dir1 <- tclvalue(tkchooseDirectory(title="Please choose the user bin dir",initialdir=initialdir)))
				Try(if(nchar(dir1)>0) tclvalue(wd) <- dir1)
				Try(
					if(.Platform$OS.type=="windows"){
						Try(tclvalue(wd) <- gsub("/","\\\\",tclvalue(wd)))
					}
				)
			} #end of onBrowse <- function()
		)# end of Try
		#
		#
		Try(ReturnVal <- "")
		#
		#
		Try(
			onOK <- function(){
				Try(DirChosen <- tclvalue(wd))
				Try(tkgrab.release(ttChooseDir))
				Try(tkdestroy(ttChooseDir))
				Try(DirChosen <- gsub("\\\\","/",DirChosen))
				Try(ReturnVal <<- DirChosen)
			} #end of onOK <- function()
		)
		#
		#
		Try(
			onCancel <- function(){
				Try(tkgrab.release(ttChooseDir));
				Try(tkdestroy(ttChooseDir))
			} #end of onCancel <- function()
		) #end of try
		#
		#
		Try(Browse.but <- tkbutton(ttChooseDir,text="Browse",command=onBrowse,font=.affylmGUIglobals$affylmGUIfont2))
		Try(OK.but <- tkbutton(ttChooseDir,