R/filemenu.R

Defines functions SaveLimmaFile SetED chooseEDir NewLimmaFile OpenCDFandTargetsfiles OpenLargeFile OpenAFile OpenGeoFile OpenAGeoFile preProcessingNGS myfindOverlaps fromNGStoDf ExportNormalizedExpressionValues1 SaveAsLimmaFile ExportfeatureNames OpenExonandTargetsfiles OpenExonFile OpenExonProbeFile OpenAFile OpenAFile OpenLimmaFile OpenALimmaFile NewLimmaFileNGS tuxedoMenu

Documented in chooseEDir ExportfeatureNames ExportNormalizedExpressionValues1 NewLimmaFile NewLimmaFileNGS OpenAFile OpenAGeoFile OpenALimmaFile OpenCDFandTargetsfiles OpenExonandTargetsfiles OpenExonFile OpenExonProbeFile OpenGeoFile OpenLargeFile OpenLimmaFile SaveAsLimmaFile SaveLimmaFile SetED tuxedoMenu

#set of functions, directly/indirectly involved, in oneChannelGUI fileMenu
#oneChannelGUI annotation(eSet) restoring the annotation function to retrieve annotatio form expression set slot
#oneChannelGUI NewLimmaFileNGS handles only digital data project 
#                   RNA-seq OpenmRNABam
#                   mRNAbowtieRun in RNAseq file
#oneChannelGUI NewLimmaFile open new projects for affy, exon, gene, large tab delimited data
       #contains: affylmGUI SaveLimmaFile() calling oneChannelGUI SaveAsLimmaFile
       #          affylmGUI SetWD
       #          affylmGUI initGlobals
       #          oneChannelGUI OpenCDFandTargetsfiles
       #          oneChannelGUI whichKindOfArray
       #          oneChannelGUI changeMenu
       #          oneChannelGUI files
       #          oneChannelGUI OpenGeofiles
       #          oneChannelGUI OpenBeadStudioFiles which uses:                
       #                BeadExplorer .readBead modified since the original version has an error
#oneChannelGUI SetED #setting dirs where exon libraries and apt tools are located
       #contains oneChannelGUI chooseEDir
#oneChannelGUI OpenCDFandTargetsfiles is a modification of the same affylmGUI function  it is used to load .CEL file in an affy project
       #contains: oneChannelGUI OpenTargetsFileAnNdSetCursor internally defined
       #          oneChannelGUI OpenCDFFileAndSetCursor internally defined
       #          affylmGUI OpenCDFFile
       #          affylmGUI GetlimmaDataSetName
#oneChannelGUI whichKindOfArray this function handles the apt tool dir and exon library files information it is needed to load exon data in an exon project
       #contains: oneChannelGUI .aptDir, written immedialtely after the whichKindOfArray function
       #          oneChannelGUI libraryFilesDir
#oneChannelGUI  .aptDir this is an internal oneChannelGUI function to be used to handle the location of the main APT affymetrix tools dir
#oneChannelGUI libraryFilesDir this function hangles the locationof the exon arrays library files
#oneChannelGUI changeMenu this function modify the affylmGUI menu to oneChannelGUI affy, exon and large menus.
#      #contains: oneChannelGUI OpenALimmaFile function to assign a specific name to the project
#oneChannelGUI OpenLargefiles this function handles the loading of tab delimited files containing array data information
       #contains: oneChannelGUI OpenTargetsFileAndSetCursor internally defined
       #          affylmGUI OpenTargetsFile
       #          oneChannelGUI OpenLargeFile written immediately after the OpenLargefiles          
       #          affylmGUI GetlimmaDataSetName
       #          oneChannelGUI OpenAFile written immediately after the OpenLargeFile
#oneChannelGUI OpenLargeFile calls OpenAFile function
#oneChannelGUI OpenAFile opens the tab delimited file with array data 
#oneChannelGUI OpenGeoFile calls OpenAGeoFile function
#oneChannelGUI OpenAGeoFile opens the tab delimited file GEO siries matrix file
#oneChannelGUI createGeoTarget open an tab delimited file GEO series matrix file and creates a Target file to be used to load that GEO file. 
#oneChannelGUI OpenLimmaFile calls oneChannelGUI OpenALimmaFile
#oneChannelGUI OpenALimmaFile
       #contains oneChannelGUI SaveLimmaFile
       #         oneChannelGUI OpenALimmaFile defined internally
       #         oneChannelGUI changeMenu see above
       
#oneChannelGUI addAnnLib this function attaches a Bioconductor annotation database name to the large tab delimited data sets loaded in the project
#oneChannelGUI OpenExonandTargetsfiles function to handle exon arrays data by APT of flat files
       #contains: oneChannelGUI OpenTargetsFileAndSetCursor internally defined
       #          affylmGUI OpenTargetsFile 
       #          affylmGUI GetlimmaDataSetName
       #          oneChannelGUI  OpenExonFile  written below the function
       #          oneChannelGUI  OpenExonProbeFile   written below the function
       #          oneChannelGUI OpenAFile   written below the function
#oneChannelGUI OpenNgsfiles this function produces an object of the class GenomeDataList containing the 
#              the mapped reads for the chromosomes of the selected organism
#      contains .preProcessingNGS saving mappedReads data in a dir. Data are splitted on the basis of chr mapping
#               .myfindOverlaps
#               .fromNGStoDf combines sample peaks in a matrix of common peaks
#oneChannelGUI .mappingWgenominator this function can be used instead of the more general mapping based on the use of chipseq segmentation
#              The annotation is dinamically generated using getAnnotation() and stored in the affylmGUI environment as GenominatorAnnoData
#              The name of the db is stored in GenominatorDB. The db is located in the same dir where oneChannelGUI is working
#              Ig Genominator was used Genominator.Available is put to TRUE
#              useful to recall the db eData<- ExpData(dbFilename = "gilli.db", tablename = "gf11")
#               alos open MicroRazerS data files
#oneChannelGUI  OpenmRNABam opens RNA-seq bam files and load them as tab delimited counts data
#               OpenmiRNABam opens miRNA-seq bam files and load them as tab delimited counts data
#oneChannelGUI Openfiles modification of OpenNgsfiles
##oneChannelGUI NGSreformat is located in the RNAseq menu
##oneChannelGUI bowtieRun is located in the RNAseq menu
#oneChannelGUI OpenmiRBam opens bam files generated by botwtie on oneChannelGUI and organize them in a eSet
#set of functions, directly/indirectly involved, in oneChannelGUI fileMenu
#oneChannelGUI showDataset describes the content of the loaded data set
#oneChannelGUI ExportNormalizedExpressionValues1 this function exports as a tab delimited file normalized gene level expression 
#               data present in the project in exon case also SI/RP/exon/MiDAS data ere exported if available      
       #contains oneChannelGUI NormalizeNow present in the normalizemenu.R  
#oneChannelGUI targetWidget used for the graphical creation of a target file when .CEL files are available
#oneChannelGUI SaveAsLimmaFile save a project with a specific name
       #contains oneChannelGUI OpenALimmaFile defined internally
#oneChannelGUI OpenmiRanalyserfiles open mature mirNA files produced by http://web.bioinformatics.cicbiogune.es/microRNA/miRanalyser.php
#oneChannelGUI OpenmiRProfiles open mature mirNA files produced by http://srna-tools.cmp.uea.ac.uk/animal/cgi-bin/srna-tools.cgi
#oneChannelGUI OpenmiRExpress open mature mirNA files produced by miRExpress tool  http://miRExpress.mbc.nctu.edu.tw
#oneChannelGUI OpenmiRShrimp open output data generated using as reference the precursor mir dataset converted in a fasta file after conversion of U in T
#oneChannelGUI tuxedoMenu is used to ckange the menu to the NGS ones to see the tuxed suite menu

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

".annotation" <- function(eset){return(eset@annotation)}
################################################################################
SaveLimmaFile <- function () {
    LimmaFileName <- get("LimmaFileName", envir = affylmGUIenvironment)
    if (LimmaFileName == "Untitled") {
        SaveAsLimmaFile()
        try(tkfocus(.affylmGUIglobals$ttMain), silent = TRUE)
        return()
    }
    try(tkconfigure(.affylmGUIglobals$ttMain, cursor = "watch"), 
        silent = TRUE)
    assign("PsetData.Available", FALSE, affylmGUIenvironment)
    Try(save(list = ls(envir = affylmGUIenvironment), file = LimmaFileName, 
        envir = affylmGUIenvironment))
    try(tkconfigure(.affylmGUIglobals$ttMain, cursor = "arrow"), 
        silent = TRUE)
    try(tkfocus(.affylmGUIglobals$ttMain), silent = TRUE)
}


################################################################################
SetED <- function(){
	ED <- chooseEDir()
	if(!nchar(ED)){
		tkfocus(.affylmGUIglobals$ttMain)
		return("")
	}
	Try(setwd(ED))
	tkfocus(.affylmGUIglobals$ttMain)
	return(ED)
}#end of SetED <- function()

chooseEDir <- function(){
	Try(wd <- tclVar(getwd()))
	Try(
		if(.Platform$OS.type=="windows"){
			Try(tclvalue(wd) <- gsub("/","\\\\",tclvalue(wd)))
		}
	)
	Try(ttChooseDir <- tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.title(ttChooseDir,"Choose APT directory"))
	Try(tkwm.deiconify(ttChooseDir))
	Try(tkgrab.set(ttChooseDir))
	Try(tkgrid(tklabel(ttChooseDir,text="    ")))
	Try(label1 <- tklabel(ttChooseDir,text="Choose 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 a working directory for the Limma Analysis",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,text="    OK		",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	Try(Cancel.but <- tkbutton(ttChooseDir,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
	#
	Try(entry1 <- tkentry(ttChooseDir,textvariable=wd,width=40,font=.affylmGUIglobals$affylmGUIfont2))
	#
	Try(tkgrid(tklabel(ttChooseDir,text="    "),entry1))
	Try(tkgrid.configure(entry1,columnspan=3))
	Try(tkgrid(tklabel(ttChooseDir,text="    "),row=3,column=4))
	Try(tkgrid(Browse.but,row=3,column=5))
	Try(tkgrid(tklabel(ttChooseDir,text="    "),row=3,column=6))
	Try(tkgrid(tklabel(ttChooseDir,text="    ")))
	Try(tkgrid(tklabel(ttChooseDir,text="    "),tklabel(ttChooseDir,text="    "),OK.but,Cancel.but))
	Try(tkgrid.configure(Cancel.but,sticky="w"))
	Try(tkgrid(tklabel(ttChooseDir,text="    ")))
	#
	Try(tkfocus(entry1))
	Try(tkbind(ttChooseDir,"<Destroy>",function()tkgrab.release(ttChooseDir)))
	Try(tkbind(entry1,"<Return>",onOK))
	Try(tkwait.window(ttChooseDir))
	Try(tkfocus(.affylmGUIglobals$ttMain))
	#
	return(ReturnVal)
}#end of chooseEDir <- function()


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

NewLimmaFile <- function(){
	####################################################
	Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(ttGetArray <- tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttGetArray))
	Try(tkgrab.set(ttGetArray))
	Try(tkfocus(ttGetArray))
	Try(tkwm.title(ttGetArray,"Selecting the Array/NGS platform"))
	#
	Try(tkgrid(tklabel(ttGetArray,text="    ")))
	Try(ArrayTcl <- tclVar("AFFY"))
	Try(rbAFFY <- tkradiobutton(ttGetArray,text="Affy CEL files: 3 IVT",variable=ArrayTcl,value="AFFY",font=.affylmGUIglobals$affylmGUIfont2))
	Try(rbEXON <- tkradiobutton(ttGetArray,text="EXON 1.0/2.0 ST ARRAYS: probe sets summary from Affymetrix \nExpression Console/APT",variable=ArrayTcl,value="EXON",font=.affylmGUIglobals$affylmGUIfont2))
	Try(rbGENE <- tkradiobutton(ttGetArray,text="GENE 1.0/2.0 ST ARRAYS: probe sets summary from Affymetrix APT",variable=ArrayTcl,value="GENE",font=.affylmGUIglobals$affylmGUIfont2))
	Try(rbLARGE<-tkradiobutton(ttGetArray,text="Large normalized tab delimited data set: any single channel platform\nRNA-seq data in tabular format.",variable=ArrayTcl,value="LARGE",font=.affylmGUIglobals$affylmGUIfont2))
	Try(rbILLU<-tkradiobutton(ttGetArray,text="ILLUMINA: loading data generated by BeadStudio software v1/2/3",variable=ArrayTcl,value="ILLU",font=.affylmGUIglobals$affylmGUIfont2))
	Try(rbGEO<-tkradiobutton(ttGetArray,text="GEO Series Matrix file",variable=ArrayTcl,value="GEO",font=.affylmGUIglobals$affylmGUIfont2))
	
  Try(tkgrid(tklabel(ttGetArray,text="    "),rbAFFY))
	Try(tkgrid(tklabel(ttGetArray,text="    "),rbEXON))
  Try(tkgrid(tklabel(ttGetArray,text="    "),rbGENE))
  Try(tkgrid(tklabel(ttGetArray,text="    "),rbLARGE))
  Try(tkgrid(tklabel(ttGetArray,text="    "),rbILLU))
	Try(tkgrid(tklabel(ttGetArray,text="    "),rbGEO))
	Try(tkgrid.configure(rbAFFY,rbEXON,rbGENE,rbLARGE,rbILLU,rbGEO,columnspan=2,sticky="w"))
	Try(tkgrid(tklabel(ttGetArray,text="    "),tklabel(ttGetArray,text="    ")))
	#
	Try(ReturnVal <- "")
	Try(
		onCancel <- function() {
			Try(ReturnVal <<- "");
			Try(tkgrab.release(ttGetArray));
			Try(tkdestroy(ttGetArray));
			Try(tkfocus(.affylmGUIglobals$ttMain))
			Try(return())
		}
	)
	Try(
		onOK <- function() {
			Try(ReturnVal <<- tclvalue(ArrayTcl));
			Try(tkgrab.release(ttGetArray));
			Try(tkdestroy(ttGetArray));
			Try(tkfocus(.affylmGUIglobals$ttMain))
		}
	)
	#
	Try(OK.but     <- tkbutton(ttGetArray,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	Try(Cancel.but <- tkbutton(ttGetArray,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
	#
	Try(tkgrid(tklabel(ttGetArray,text="    "),OK.but,Cancel.but,tklabel(ttGetArray,text="    ")))
	Try(tkgrid.configure(OK.but,sticky="e"))
	Try(tkgrid.configure(Cancel.but,sticky="w"))
	Try(tkgrid(tklabel(ttGetArray,text="    ")))
	#
	Try(tkbind(ttGetArray,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetArray));Try(tkfocus(.affylmGUIglobals$ttMain));}))
	Try(tkbind(OK.but, "<Return>",onOK))
	Try(tkbind(Cancel.but, "<Return>",onCancel))
	#
	Try(tkwait.window(ttGetArray))
	Try(tkfocus(.affylmGUIglobals$ttMain))
#selecting the array type
  Try(
    if(ReturnVal=="AFFY"){
      Try(assign("whichArrayPlatform","AFFY",affylmGUIenvironment))
##############initialization variables start
                        Try(tt <- "")
                        Try(assign("illuData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("illuData",tt,affylmGUIenvironment))

                        Try(assign("RawAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("NormalizedAffyData.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("unfilteredData.location", tt, affylmGUIenvironment))
                        Try(assign("geoPlatform",  tt, env=affylmGUIenvironment))

                        Try(assign("metaData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("metaData",tt,affylmGUIenvironment))

                        Try(assign("exprConsoleLibs.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exprConsoleLibs", tt ,affylmGUIenvironment))#locate here the library files as a list of data.frames

                        Try(assign("libDir.Available",FALSE,affylmGUIenvironment))
                        Try(assign("libDir", tt ,affylmGUIenvironment))#locate here the library files as a list of data.frames
                        Try(assign("whichLib", tt ,affylmGUIenvironment))#remember the type of exon library loaded

                        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(meVDirLocation <- myinfo[which(myinfo[,1]=="meVDirLocation"),2])
                        Try(if(is.na(meVDirLocation)) meVDirLocation <- tt)
                        if(meVDirLocation != ""){
                          assign("meVDirLocation", meVDirLocation, affylmGUIenvironment)#directory where meV program is located
                          assign("meVDirLocation.Available",TRUE,affylmGUIenvironment)
                        }
#                        Try(perlDirLocation <- myinfo[which(myinfo[,1]=="perlDirLocation"),2])
#                        Try(if(is.na(perlDirLocation)) perlDirLocation <- tt)
#                        if(perlDirLocation != ""){
#                          assign("perlDirLocation", perlDirLocation, affylmGUIenvironment)#directory where ngs perl scripts are located
#                          assign("perlDirLocation.Available",TRUE,affylmGUIenvironment)
#                        }else{
#                                    Try(tkmessageBox(title="NGS Perl scripts",message="NGS perl script not installed.\nInstall them using the routine available in General tools menu.",type="ok",icon="error"))
#                        }


                        
                        Try(assign("exonAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exonAffyData", tt ,affylmGUIenvironment))
                        Try(assign("dabg.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("dabg.p" , tt, affylmGUIenvironment))    
                        Try(assign("midas.p" , tt, affylmGUIenvironment))
                        Try(assign("midas.p.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("spliceIndexData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("spliceIndexData", tt ,affylmGUIenvironment))
                        Try(assign("AltSplRP.e.p" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.e.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("AltSplRP.g" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.g.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("detected.splicing" , tt, affylmGUIenvironment))
                        Try(assign("detected.splicing.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("LinearModelFitExon.Available",FALSE,affylmGUIenvironment))
                        Try(assign("cosie.Available", FALSE ,affylmGUIenvironment))
                        Try(assign("fitExon",tt,affylmGUIenvironment))
                        Try(assign("LinearModelFitExon.Available",FALSE,affylmGUIenvironment))
                        Try(assign("AltSplLimma" , tt, affylmGUIenvironment))
                        Try(assign("AltSplLimma.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("intronicBg.available", TRUE,affylmGUIenvironment))
                        Try(assign("intronicBg", tt,affylmGUIenvironment))

                        Try(assign("maSigProSigs.Available",FALSE,affylmGUIenvironment))

                        Try(assign("Pset.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("MLdesign.Available",FALSE,affylmGUIenvironment))
                        Try(assign("MLdesign", tt ,affylmGUIenvironment))
                        Try(assign("trainAffyData.available", FALSE, env=affylmGUIenvironment))
                        Try(assign("testAffyData.available", FALSE, env=affylmGUIenvironment))
##############initialization variables end
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
    	Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))
	    Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
	    Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
	    Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
	    Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
	    if(limmaDataSetNameText!="Untitled"){
		    Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled"){LimmaFileName <- limmaDataSetNameText} )	# Local assignment only
		    Try(mbVal <- tkmessageBox(title="Start New Analysis",
				    											message=paste("Save changes to ",fixSeps(LimmaFileName),"?",sep=""),
						    									icon="question",type="yesnocancel",default="yes"
								    						 )#end of tkmessageBox
		    )#end of Try(mbVal..
		    if(tclvalue(mbVal)=="yes"){Try(SaveLimmaFile())}
		    if(tclvalue(mbVal)=="cancel"){
			    Try(tkfocus(.affylmGUIglobals$ttMain))
			    return()
		    }#end of if(tclvalue(mbVal)=="cancel")
		    Try(limmaDataSetNameText <- "Untitled")
	    }#end of if(limmaDataSetNameText!="Untitled")
	    #Try(tkmessageBox(title="Working Directory",message="After clicking OK, please select a working directory.",type="ok"))
	    Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(WD <- SetWD())
      Try(tkfocus(.affylmGUIglobals$ttMain))
	    if(WD=="") return()
	    Try(tkdelete(.affylmGUIglobals$mainTree,"RawAffyData.Status"))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFit.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(tkdelete(.affylmGUIglobals$mainTree,"maSIgProData.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","maSIgProData","maSIgProData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"PLM.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","PLM","PLM.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptDabg.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptDabg","AptDabg.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptMidas.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptMidas","AptMidas.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"spliceIndex.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","spliceIndex","spliceIndex.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.e.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.e.Status" ,text="Not Available at exon level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.g.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.g.Status" ,text="Not Available at gene level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"classification.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","classification","classification.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
     	Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFitExon.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFitExon","LinearModelFitExon.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      #NGS
      Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))


	    Try(
		    if(NumContrastParameterizations>0){
			    Try(for (i in (1:NumContrastParameterizations))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("ContrastParameterizations.Status.",i,sep="")))
			    )
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"ContrastParameterizations.Status.1"))
		    }
	    )
	    Try(
		    tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)
	    )#end of Try
	    Try(
		    if(NumParameters>0){
			    Try(for (i in (1:NumParameters))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("Parameters.Status.",i,sep="")))
			    )#end of Try-for..
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"Parameters.Status.1"))
		    }
	    )#end of Try-if...
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters","Parameters.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree))
	    if(NumContrastParameterizations>0){
		    for (contrastParameterizationIndex in (1:NumContrastParameterizations)){
			    Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
			    Try(ParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
			    Try(tkdelete(.affylmGUIglobals$ContrastParameterizationTREE,ParameterizationNameNode))
			    Try(assign("ContrastParameterizationList", deleteItemFromList(ContrastParameterizationList,ParameterizationNameNode),affylmGUIenvironment))
		    }#end of for
	    }#end of if
	    Try(initGlobals())
	    Try(LimmaFileName <- get("LimmaFileName",affylmGUIenvironment))
      Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
      Try(if(.Platform$OS.type=="windows")
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",gsub("/","\\\\",LimmaFileName))))
	             else
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",LimmaFileName)))
      )#end of Try
	    Try(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)		 <- "Please select a Chip Definition (CDF) file.")
	    Try(tclvalue(.affylmGUIglobals$CDFfileName)				 <- "No filename is selected at the moment.	Press the Select CDF File Button.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle) <- "Please select a tab-delimited file listing the CEL files.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileName)		 <- "No filename is selected at the moment.	Press the Select Targets File Button.")
	    Try(OpenCDFandTargetsfiles())
	    Try(tkfocus(.affylmGUIglobals$ttMain))
      })
       #as default the oneChannel Menu reffer to that used for 3'IVT affymrtrix arrays
       Try(if(ReturnVal=="ILLU"){
           Try(assign("whichArrayPlatform","ILLU",affylmGUIenvironment))
##############initialization variables start
                        Try(tt <- "")
                        Try(assign("illuData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("illuData",tt,affylmGUIenvironment))
                        
                        Try(assign("RawAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("NormalizedAffyData.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("unfilteredData.location", tt, affylmGUIenvironment))
                        Try(assign("geoPlatform",  tt, env=affylmGUIenvironment))

                        Try(assign("metaData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("metaData",tt,affylmGUIenvironment))

                        Try(assign("exprConsoleLibs.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exprConsoleLibs", tt ,affylmGUIenvironment))#locate here the library files as a list of data.frames

                        assign("libDir.Available",FALSE,affylmGUIenvironment)
                        assign("libDir", tt ,affylmGUIenvironment)#locate here the library files as a list of data.frames
                        assign("whichLib", tt ,affylmGUIenvironment)#remember the type of exon library loaded

                        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(meVDirLocation <- myinfo[which(myinfo[,1]=="meVDirLocation"),2])
                        Try(if(is.na(meVDirLocation)) meVDirLocation <- tt)
                        if(meVDirLocation != ""){
                          assign("meVDirLocation", meVDirLocation, affylmGUIenvironment)#directory where meV program is located
                          assign("meVDirLocation.Available",TRUE,affylmGUIenvironment)
                        }
#                        Try(perlDirLocation <- myinfo[which(myinfo[,1]=="perlDirLocation"),2])
#                        Try(if(is.na(perlDirLocation)) perlDirLocation <- tt)
#                        if(perlDirLocation != ""){
#                          assign("perlDirLocation", perlDirLocation, affylmGUIenvironment)#directory where ngs perl scripts are located
#                          assign("perlDirLocation.Available",TRUE,affylmGUIenvironment)
#                        }else{
#                                    Try(tkmessageBox(title="NGS Perl scripts",message="NGS perl script not installed.\nInstall them using the routine available in General tools menu.",type="ok",icon="error"))
#                        }

                        
                        Try(assign("exonAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exonAffyData", tt ,affylmGUIenvironment))
                        Try(assign("dabg.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("dabg.p" , tt, affylmGUIenvironment))    
                        Try(assign("midas.p" , tt, affylmGUIenvironment))
                        Try(assign("midas.p.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("spliceIndexData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("spliceIndexData", tt ,affylmGUIenvironment))
                        Try(assign("AltSplRP.e.p" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.e.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("AltSplRP.g" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.g.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("detected.splicing" , tt, affylmGUIenvironment))
                        Try(assign("detected.splicing.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("LinearModelFitExon.Available",FALSE,affylmGUIenvironment))
                        Try(assign("cosie.Available", FALSE ,affylmGUIenvironment))
                        Try(assign("fitExon",tt,affylmGUIenvironment))
                        Try(assign("LinearModelFitExon.Available",FALSE,affylmGUIenvironment))
                        Try(assign("AltSplLimma" , tt, affylmGUIenvironment))
                        Try(assign("AltSplLimma.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("intronicBg.available", TRUE,affylmGUIenvironment))
                        Try(assign("intronicBg", tt,affylmGUIenvironment))

                        Try(assign("maSigProSigs.Available",FALSE,affylmGUIenvironment))

                        Try(assign("Pset.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("MLdesign.Available",FALSE,affylmGUIenvironment))
                        Try(assign("MLdesign", tt ,affylmGUIenvironment))
                        Try(assign("trainAffyData.available", FALSE, env=affylmGUIenvironment))
                        Try(assign("testAffyData.available", FALSE, env=affylmGUIenvironment))
##############initialization variables end
 #         Try(whichKindOfArray())
          #define the right Menu depending on the platform
          Try(tkfocus(.affylmGUIglobals$ttMain))
          Try(changeMenu())#modify the default manu in aplatform specific menu
          Try(tkfocus(.affylmGUIglobals$ttMain))
           #Try(tkmessageBox(title="Selecting the Array Platform",message="Only tab delimited files, with array names in header and 1st column with probe set ids", type="ok", icon="info"))  
           Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
    	     Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))
	         Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
	         Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
	         if(limmaDataSetNameText!="Untitled"){
		         Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled"){LimmaFileName <- limmaDataSetNameText} )	# Local assignment only
		         Try(mbVal <- tkmessageBox(title="Start New Analysis",
				         											message=paste("Save changes to ",fixSeps(LimmaFileName),"?",sep=""),
						         									icon="question",type="yesnocancel",default="yes"
								         						 )#end of tkmessageBox
		         )#end of Try(mbVal..
		         if(tclvalue(mbVal)=="yes"){Try(SaveLimmaFile())}
		         if(tclvalue(mbVal)=="cancel"){
			         Try(tkfocus(.affylmGUIglobals$ttMain))
			         return()
		         }#end of if(tclvalue(mbVal)=="cancel")
		         Try(limmaDataSetNameText <- "Untitled")
	         }#end of if(limmaDataSetNameText!="Untitled")
	         #Try(tkmessageBox(title="Working Directory",message="After clicking OK, please select a working directory.",type="ok"))
	         Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(WD <- SetWD())
           Try(tkfocus(.affylmGUIglobals$ttMain))
	         if(WD=="") return()
	    Try(tkdelete(.affylmGUIglobals$mainTree,"RawAffyData.Status"))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFit.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(tkdelete(.affylmGUIglobals$mainTree,"maSIgProData.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","maSIgProData","maSIgProData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"PLM.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","PLM","PLM.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptDabg.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptDabg","AptDabg.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptMidas.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptMidas","AptMidas.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"spliceIndex.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","spliceIndex","spliceIndex.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.e.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.e.Status" ,text="Not Available at exon level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.g.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.g.Status" ,text="Not Available at gene level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"classification.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","classification","classification.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFitExon.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFitExon","LinearModelFitExon.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      #NGS
      Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(
		    if(NumContrastParameterizations>0){
			    Try(for (i in (1:NumContrastParameterizations))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("ContrastParameterizations.Status.",i,sep="")))
			    )
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"ContrastParameterizations.Status.1"))
		    }
	    )
	    Try(
		    tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)
	    )#end of Try
	    Try(
		    if(NumParameters>0){
			    Try(for (i in (1:NumParameters))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("Parameters.Status.",i,sep="")))
			    )#end of Try-for..
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"Parameters.Status.1"))
		    }
	    )#end of Try-if...
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters","Parameters.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree))
	    if(NumContrastParameterizations>0){
		    for (contrastParameterizationIndex in (1:NumContrastParameterizations)){
			    Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
			    Try(ParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
			    Try(tkdelete(.affylmGUIglobals$ContrastParameterizationTREE,ParameterizationNameNode))
			    Try(assign("ContrastParameterizationList", deleteItemFromList(ContrastParameterizationList,ParameterizationNameNode),affylmGUIenvironment))
		    }#end of for
	    }#end of if
	    Try(initGlobals())
	    Try(LimmaFileName <- get("LimmaFileName",affylmGUIenvironment))
      Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
      Try(if(.Platform$OS.type=="windows")
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",gsub("/","\\\\",LimmaFileName))))
	             else
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",LimmaFileName)))
      )#end of Try
#	    Try(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)		 <- "Please select a Chip Definition (CDF) file.")
#	    Try(tclvalue(.affylmGUIglobals$CDFfileName)				 <- "No filename is selected at the moment.	Press the Select CDF File Button.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle) <- "Please select a tab-delimited file listing the CEL files.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileName)		 <- "No filename is selected at the moment.	Press the Select Targets File Button.")
      Try(OpenBeadStudioFiles())#function to read beadarrays produced from beadstudio 1/2 wrapping .readBead
	    Try(tkfocus(.affylmGUIglobals$ttMain))
       })
#       Try(if(ReturnVal=="AB"){
#           Try(tkmessageBox(title="Selecting the Array Platform",message="AB1700 Not yet implemented", type="ok", icon="info"))  
#           Try(assign("whichArrayPlatform","AB",affylmGUIenvironment))
#           Try(changeMenu())#modify the default manu in aplatform specific menu
#       })
        Try(if(ReturnVal=="EXON"){
          Try(assign("whichArrayPlatform","EXON",affylmGUIenvironment))
##############initialization variables start
                        Try(tt <- "")
                        Try(assign("illuData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("illuData",tt,affylmGUIenvironment))

                        Try(assign("RawAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("NormalizedAffyData.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("unfilteredData.location", tt, affylmGUIenvironment))
                        Try(assign("geoPlatform",  tt, env=affylmGUIenvironment))

                        Try(assign("metaData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("metaData",tt,affylmGUIenvironment))

                        Try(assign("exprConsoleLibs.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exprConsoleLibs", tt ,affylmGUIenvironment))#locate here the library files as a list of data.frames

                        #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(libDirLocation <- myinfo[which(myinfo[,1]=="libDirLocation"),2])
                        Try(if(is.na(libDirLocation)) libDirLocation <- tt)
                        if(libDirLocation != ""){
                          assign("libDirLocation", libDirLocation, affylmGUIenvironment)#directory where affy library files are located
                        } else{  
                                Try(geneExonLibs())
                                Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
                                Try(libDirLocation <- myinfo[which(myinfo[,1]=="libDirLocation"),2])
                                Try(assign("libDirLocation", libDirLocation, affylmGUIenvironment))#directory where affy library files are located
                        }
                        
                        Try(assign("libDir.Available",FALSE,affylmGUIenvironment))
                        Try(assign("libDir", tt ,affylmGUIenvironment))#locate here the library files as a list of data.frames
                        Try(assign("whichLib", tt ,affylmGUIenvironment))#remember the type of exon library loaded
                        Try(aptDir <- myinfo[which(myinfo[,1]=="aptDir"),2])
                        Try(if(is.na(aptDir)) aptDir <- tt)
                        if(aptDir != ""){
                          assign("aptDir.Available",TRUE,affylmGUIenvironment)
                          assign("aptDir", aptDir ,affylmGUIenvironment)
                        } else{  
                                assign("aptDir.Available",FALSE,affylmGUIenvironment)
                                Try(aptFolder())
                                Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
                                Try(aptDir <- myinfo[which(myinfo[,1]=="aptDir"),2])
                                assign("aptDir.Available",TRUE,affylmGUIenvironment)
                                assign("aptDir", aptDir ,affylmGUIenvironment)
                        }

                        Try(meVDirLocation <- myinfo[which(myinfo[,1]=="meVDirLocation"),2])
                        Try(if(is.na(meVDirLocation)) meVDirLocation <- tt)
                        if(meVDirLocation != ""){
                          assign("meVDirLocation", meVDirLocation, affylmGUIenvironment)#directory where meV program is located
                          assign("meVDirLocation.Available",TRUE,affylmGUIenvironment)
                        }
                        
                        Try(assign("exonAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exonAffyData", tt ,affylmGUIenvironment))
                        Try(assign("dabg.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("dabg.p" , tt, affylmGUIenvironment))    
                        Try(assign("midas.p" , tt, affylmGUIenvironment))
                        Try(assign("midas.p.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("spliceIndexData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("spliceIndexData", tt ,affylmGUIenvironment))
                        Try(assign("AltSplRP.e.p" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.e.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("AltSplRP.g" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.g.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("LinearModelFitExon.Available",FALSE,affylmGUIenvironment))
	                      Try(assign("cosie.Available", FALSE ,affylmGUIenvironment))
                        Try(assign("fitExon",tt,affylmGUIenvironment))
                        Try(assign("AltSplLimma" , tt, affylmGUIenvironment))
                        Try(assign("AltSplLimma.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("intronicBg.available", TRUE,affylmGUIenvironment))
                        Try(assign("intronicBg", tt,affylmGUIenvironment))

                        Try(assign("maSigProSigs.Available",FALSE,affylmGUIenvironment))

                        Try(assign("Pset.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("MLdesign.Available",FALSE,affylmGUIenvironment))
                        Try(assign("MLdesign", tt ,affylmGUIenvironment))
                        Try(assign("trainAffyData.available", FALSE, env=affylmGUIenvironment))
                        Try(assign("testAffyData.available", FALSE, env=affylmGUIenvironment))
##############initialization variables end
          Try(tkfocus(.affylmGUIglobals$ttMain))
          Try(whichKindOfArray())
          Try(tkfocus(.affylmGUIglobals$ttMain))
#          if (affylmGUIenvironment$aptDir.Available & affylmGUIenvironment$exprConsoleLibs.Available){
           if (affylmGUIenvironment$exprConsoleLibs.Available){
          #define the right Menu depending on the platform
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(changeMenu())#modify the default manu in aplatform specific menu
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(tkmessageBox(title="Selecting the Array Platform",message="If Affymetrix APT tools are installed, \ngene/exon probe sets summaries can be calculated starting from .CEL, \nelse only tab delimted files exported from  Expression Console are supported.", type="ok", icon="info"))  
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
    	     Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))
	         Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
	         Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
	         if(limmaDataSetNameText!="Untitled"){
		         Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled"){LimmaFileName <- limmaDataSetNameText} )	# Local assignment only
		         Try(mbVal <- tkmessageBox(title="Start New Analysis",
				         											message=paste("Save changes to ",fixSeps(LimmaFileName),"?",sep=""),
						         									icon="question",type="yesnocancel",default="yes"
								         						 )#end of tkmessageBox
		         )#end of Try(mbVal..
		         if(tclvalue(mbVal)=="yes"){Try(SaveLimmaFile())}
		         if(tclvalue(mbVal)=="cancel"){
			         Try(tkfocus(.affylmGUIglobals$ttMain))
			         return()
		         }#end of if(tclvalue(mbVal)=="cancel")
		         Try(limmaDataSetNameText <- "Untitled")
	         }#end of if(limmaDataSetNameText!="Untitled")
	         #Try(tkmessageBox(title="Working Directory",message="After clicking OK, please select a working directory.",type="ok"))
	         Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(WD <- SetWD())
           Try(tkfocus(.affylmGUIglobals$ttMain))
	         if(WD=="") return()
	    Try(tkdelete(.affylmGUIglobals$mainTree,"RawAffyData.Status"))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFit.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(tkdelete(.affylmGUIglobals$mainTree,"maSIgProData.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","maSIgProData","maSIgProData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"PLM.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","PLM","PLM.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptDabg.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptDabg","AptDabg.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptMidas.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptMidas","AptMidas.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"spliceIndex.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","spliceIndex","spliceIndex.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.e.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.e.Status" ,text="Not Available at exon level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.g.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.g.Status" ,text="Not Available at gene level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"classification.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","classification","classification.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
     	Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFitExon.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFitExon","LinearModelFitExon.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      #NGS
      Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(
		    if(NumContrastParameterizations>0){
			    Try(for (i in (1:NumContrastParameterizations))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("ContrastParameterizations.Status.",i,sep="")))
			    )
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"ContrastParameterizations.Status.1"))
		    }
	    )
	    Try(
		    tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)
	    )#end of Try
	    Try(
		    if(NumParameters>0){
			    Try(for (i in (1:NumParameters))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("Parameters.Status.",i,sep="")))
			    )#end of Try-for..
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"Parameters.Status.1"))
		    }
	    )#end of Try-if...
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters","Parameters.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree))
	    if(NumContrastParameterizations>0){
		    for (contrastParameterizationIndex in (1:NumContrastParameterizations)){
			    Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
			    Try(ParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
			    Try(tkdelete(.affylmGUIglobals$ContrastParameterizationTREE,ParameterizationNameNode))
			    Try(assign("ContrastParameterizationList", deleteItemFromList(ContrastParameterizationList,ParameterizationNameNode),affylmGUIenvironment))
		    }#end of for
	    }#end of if
	    Try(initGlobals())
	    Try(LimmaFileName <- get("LimmaFileName",affylmGUIenvironment))
      Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
      Try(if(.Platform$OS.type=="windows")
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",gsub("/","\\\\",LimmaFileName))))
	             else
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",LimmaFileName)))
      )#end of Try
#	    Try(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)		 <- "Please select a Chip Definition (CDF) file.")
#	    Try(tclvalue(.affylmGUIglobals$CDFfileName)				 <- "No filename is selected at the moment.	Press the Select CDF File Button.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle) <- "Please select a tab-delimited file listing the CEL files.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileName)		 <- "No filename is selected at the moment.	Press the Select Targets File Button.")
	    Try(OpenExonandTargetsfiles())
	    Try(tkfocus(.affylmGUIglobals$ttMain))
  }  else {return()}# some parameters were missed therefore gene/exon data cannot be loaded  
       
       })

##########################################################################
        Try(if(ReturnVal=="GENE"){
          Try(assign("whichArrayPlatform","GENE",affylmGUIenvironment))
##############initialization variables start
                        Try(tt <- "")
                        Try(assign("illuData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("illuData",tt,affylmGUIenvironment))

                        Try(assign("RawAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("NormalizedAffyData.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("unfilteredData.location", tt, affylmGUIenvironment))
                        Try(assign("geoPlatform",  tt, env=affylmGUIenvironment))

                        Try(assign("metaData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("metaData",tt,affylmGUIenvironment))

                        Try(assign("exprConsoleLibs.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exprConsoleLibs", tt ,affylmGUIenvironment))#locate here the library files as a list of data.frames

                        #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(libDirLocation <- myinfo[which(myinfo[,1]=="libDirLocation"),2])
                        Try(if(is.na(libDirLocation)) libDirLocation <- tt)
                        if(libDirLocation != ""){
                          assign("libDirLocation", libDirLocation, affylmGUIenvironment)#directory where affy library files are located
                        } else{  
                                Try(geneExonLibs())
                                Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
                                Try(libDirLocation <- myinfo[which(myinfo[,1]=="libDirLocation"),2])
                                Try(assign("libDirLocation", libDirLocation, affylmGUIenvironment))#directory where affy library files are located
                        }
                        
                        Try(assign("libDir.Available",FALSE,affylmGUIenvironment))
                        Try(assign("libDir", tt ,affylmGUIenvironment))#locate here the library files as a list of data.frames
                        Try(assign("whichLib", tt ,affylmGUIenvironment))#remember the type of exon library loaded
                        Try(aptDir <- myinfo[which(myinfo[,1]=="aptDir"),2])
                        Try(if(is.na(aptDir)) aptDir <- tt)
                        if(aptDir != ""){
                          assign("aptDir.Available",TRUE,affylmGUIenvironment)
                          assign("aptDir", aptDir ,affylmGUIenvironment)
                        } else{  
                                assign("aptDir.Available",FALSE,affylmGUIenvironment)
                                Try(aptFolder())
                                Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
                                Try(aptDir <- myinfo[which(myinfo[,1]=="aptDir"),2])
                                assign("aptDir.Available",TRUE,affylmGUIenvironment)
                                assign("aptDir", aptDir ,affylmGUIenvironment)
                        }

                        Try(meVDirLocation <- myinfo[which(myinfo[,1]=="meVDirLocation"),2])
                        Try(if(is.na(meVDirLocation)) meVDirLocation <- tt)
                        if(meVDirLocation != ""){
                          assign("meVDirLocation", meVDirLocation, affylmGUIenvironment)#directory where meV program is located
                          assign("meVDirLocation.Available",TRUE,affylmGUIenvironment)
                        }
                        
                        Try(assign("exonAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exonAffyData", tt ,affylmGUIenvironment))
                        Try(assign("dabg.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("dabg.p" , tt, affylmGUIenvironment))    
                        Try(assign("midas.p" , tt, affylmGUIenvironment))
                        Try(assign("midas.p.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("spliceIndexData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("spliceIndexData", tt ,affylmGUIenvironment))
                        Try(assign("AltSplRP.e.p" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.e.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("AltSplRP.g" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.g.Available" , FALSE, affylmGUIenvironment))
                        
                       	Try(assign("LinearModelFitExon.Available",FALSE,affylmGUIenvironment))
	                      Try(assign("cosie.Available", FALSE ,affylmGUIenvironment))
                        Try(assign("fitExon",tt,affylmGUIenvironment))
                        Try(assign("AltSplLimma" , tt, affylmGUIenvironment))
                        Try(assign("AltSplLimma.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("intronicBg.available", TRUE,affylmGUIenvironment))
                        Try(assign("intronicBg", tt,affylmGUIenvironment))

                        Try(assign("maSigProSigs.Available",FALSE,affylmGUIenvironment))

                        Try(assign("Pset.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("MLdesign.Available",FALSE,affylmGUIenvironment))
                        Try(assign("MLdesign", tt ,affylmGUIenvironment))
                        Try(assign("trainAffyData.available", FALSE, env=affylmGUIenvironment))
                        Try(assign("testAffyData.available", FALSE, env=affylmGUIenvironment))
##############initialization variables end
          Try(tkfocus(.affylmGUIglobals$ttMain))
          Try(whichKindOfArray())
          Try(tkfocus(.affylmGUIglobals$ttMain))
#          if (affylmGUIenvironment$aptDir.Available & affylmGUIenvironment$exprConsoleLibs.Available){
           if (affylmGUIenvironment$exprConsoleLibs.Available){
          #define the right Menu depending on the platform
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(changeMenu())#modify the default manu in aplatform specific menu
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(tkmessageBox(title="Selecting the Array Platform",message="If Affymetrix APT tools are installed, \ngene/exon probe sets summaries can be calculated starting from .CEL, \nelse only tab delimted files exported from  Expression Console are supported.", type="ok", icon="info"))  
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
    	     Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))
	         Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
	         Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
	         if(limmaDataSetNameText!="Untitled"){
		         Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled"){LimmaFileName <- limmaDataSetNameText} )	# Local assignment only
		         Try(mbVal <- tkmessageBox(title="Start New Analysis",
				         											message=paste("Save changes to ",fixSeps(LimmaFileName),"?",sep=""),
						         									icon="question",type="yesnocancel",default="yes"
								         						 )#end of tkmessageBox
		         )#end of Try(mbVal..
		         if(tclvalue(mbVal)=="yes"){Try(SaveLimmaFile())}
		         if(tclvalue(mbVal)=="cancel"){
			         Try(tkfocus(.affylmGUIglobals$ttMain))
			         return()
		         }#end of if(tclvalue(mbVal)=="cancel")
		         Try(limmaDataSetNameText <- "Untitled")
	         }#end of if(limmaDataSetNameText!="Untitled")
	         #Try(tkmessageBox(title="Working Directory",message="After clicking OK, please select a working directory.",type="ok"))
	         tkfocus(.affylmGUIglobals$ttMain)
           Try(WD <- SetWD())
	         if(WD=="") return()
	    Try(tkdelete(.affylmGUIglobals$mainTree,"RawAffyData.Status"))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFit.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(tkdelete(.affylmGUIglobals$mainTree,"maSIgProData.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","maSIgProData","maSIgProData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"PLM.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","PLM","PLM.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptDabg.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptDabg","AptDabg.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptMidas.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptMidas","AptMidas.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"spliceIndex.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","spliceIndex","spliceIndex.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.e.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.e.Status" ,text="Not Available at exon level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.g.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.g.Status" ,text="Not Available at gene level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"classification.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","classification","classification.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFitExon.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFitExon","LinearModelFitExon.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      #NGS
      Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
    
	    Try(
		    if(NumContrastParameterizations>0){
			    Try(for (i in (1:NumContrastParameterizations))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("ContrastParameterizations.Status.",i,sep="")))
			    )
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"ContrastParameterizations.Status.1"))
		    }
	    )
	    Try(
		    tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)
	    )#end of Try
	    Try(
		    if(NumParameters>0){
			    Try(for (i in (1:NumParameters))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("Parameters.Status.",i,sep="")))
			    )#end of Try-for..
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"Parameters.Status.1"))
		    }
	    )#end of Try-if...
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters","Parameters.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree))
	    if(NumContrastParameterizations>0){
		    for (contrastParameterizationIndex in (1:NumContrastParameterizations)){
			    Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
			    Try(ParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
			    Try(tkdelete(.affylmGUIglobals$ContrastParameterizationTREE,ParameterizationNameNode))
			    Try(assign("ContrastParameterizationList", deleteItemFromList(ContrastParameterizationList,ParameterizationNameNode),affylmGUIenvironment))
		    }#end of for
	    }#end of if
	    Try(initGlobals())
	    Try(LimmaFileName <- get("LimmaFileName",affylmGUIenvironment))
      Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
      Try(if(.Platform$OS.type=="windows")
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",gsub("/","\\\\",LimmaFileName))))
	             else
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",LimmaFileName)))
      )#end of Try
#	    Try(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)		 <- "Please select a Chip Definition (CDF) file.")
#	    Try(tclvalue(.affylmGUIglobals$CDFfileName)				 <- "No filename is selected at the moment.	Press the Select CDF File Button.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle) <- "Please select a tab-delimited file listing the CEL files.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileName)		 <- "No filename is selected at the moment.	Press the Select Targets File Button.")
	    Try(OpenExonandTargetsfiles())
	    Try(tkfocus(.affylmGUIglobals$ttMain))
  }  else {return()}# some parameters were missed therefore gene/exon data cannot be loaded  
       
       })

##########################################################################
        Try(if(ReturnVal=="LARGE"){
          Try(assign("whichArrayPlatform","LARGE",affylmGUIenvironment))
##############initialization variables start
                        Try(tt <- "")
                        Try(assign("illuData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("illuData",tt,affylmGUIenvironment))

                        Try(assign("RawAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("NormalizedAffyData.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("unfilteredData.location", tt, affylmGUIenvironment))
                        Try(assign("geoPlatform",  tt, env=affylmGUIenvironment))

                        Try(assign("metaData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("metaData",tt,affylmGUIenvironment))

                        Try(assign("exprConsoleLibs.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exprConsoleLibs", tt ,affylmGUIenvironment))#locate here the library files as a list of data.frames

                        assign("libDir.Available",FALSE,affylmGUIenvironment)
                        assign("libDir", tt ,affylmGUIenvironment)#locate here the library files as a list of data.frames
                        assign("whichLib", tt ,affylmGUIenvironment)#remember the type of exon library loaded

                        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(meVDirLocation <- myinfo[which(myinfo[,1]=="meVDirLocation"),2])
                        Try(if(is.na(meVDirLocation)) meVDirLocation <- tt)
                        if(meVDirLocation != ""){
                          assign("meVDirLocation", meVDirLocation, affylmGUIenvironment)#directory where meV program is located
                          assign("meVDirLocation.Available",TRUE,affylmGUIenvironment)
                        }
                        
                        Try(assign("exonAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exonAffyData", tt ,affylmGUIenvironment))
                        Try(assign("dabg.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("dabg.p" , tt, affylmGUIenvironment))    
                        Try(assign("midas.p" , tt, affylmGUIenvironment))
                        Try(assign("midas.p.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("spliceIndexData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("spliceIndexData", tt ,affylmGUIenvironment))
                        Try(assign("AltSplRP.e.p" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.e.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("AltSplRP.g" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.g.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("LinearModelFitExon.Available",FALSE,affylmGUIenvironment))
	                      Try(assign("cosie.Available", FALSE ,affylmGUIenvironment))
                        Try(assign("fitExon",tt,affylmGUIenvironment))
                        Try(assign("AltSplLimma" , tt, affylmGUIenvironment))
                        Try(assign("AltSplLimma.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("intronicBg.available", TRUE,affylmGUIenvironment))
                        Try(assign("intronicBg", tt,affylmGUIenvironment))

                        Try(assign("maSigProSigs.Available",FALSE,affylmGUIenvironment))

                        Try(assign("Pset.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("MLdesign.Available",FALSE,affylmGUIenvironment))
                        Try(assign("MLdesign", tt ,affylmGUIenvironment))
                        Try(assign("trainAffyData.available", FALSE, env=affylmGUIenvironment))
                        Try(assign("testAffyData.available", FALSE, env=affylmGUIenvironment))
##############initialization variables end

 #         Try(whichKindOfArray())
          #define the right Menu depending on the platform
          Try(tkfocus(.affylmGUIglobals$ttMain))
          Try(changeMenu())#modify the default manu in aplatform specific menu
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(tkmessageBox(title="Selecting the Array Platform",message="Only tab delimited files, with array names in header and 1st column with probe set ids", type="ok", icon="info"))  
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
    	     Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))
	         Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
	         Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
	         if(limmaDataSetNameText!="Untitled"){
		         Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled"){LimmaFileName <- limmaDataSetNameText} )	# Local assignment only
		         Try(mbVal <- tkmessageBox(title="Start New Analysis",
				         											message=paste("Save changes to ",fixSeps(LimmaFileName),"?",sep=""),
						         									icon="question",type="yesnocancel",default="yes"
								         						 )#end of tkmessageBox
		         )#end of Try(mbVal..
		         if(tclvalue(mbVal)=="yes"){Try(SaveLimmaFile())}
		         if(tclvalue(mbVal)=="cancel"){
			         Try(tkfocus(.affylmGUIglobals$ttMain))
			         return()
		         }#end of if(tclvalue(mbVal)=="cancel")
		         Try(limmaDataSetNameText <- "Untitled")
	         }#end of if(limmaDataSetNameText!="Untitled")
	         #Try(tkmessageBox(title="Working Directory",message="After clicking OK, please select a working directory.",type="ok"))
	         tkfocus(.affylmGUIglobals$ttMain)
           Try(WD <- SetWD())
	         if(WD=="") return()
	    Try(tkdelete(.affylmGUIglobals$mainTree,"RawAffyData.Status"))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFit.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(tkdelete(.affylmGUIglobals$mainTree,"maSIgProData.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","maSIgProData","maSIgProData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"PLM.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","PLM","PLM.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptDabg.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptDabg","AptDabg.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptMidas.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptMidas","AptMidas.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"spliceIndex.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","spliceIndex","spliceIndex.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.e.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.e.Status" ,text="Not Available at exon level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.g.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.g.Status" ,text="Not Available at gene level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"classification.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","classification","classification.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFitExon.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFitExon","LinearModelFitExon.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      #NGS
      Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(
		    if(NumContrastParameterizations>0){
			    Try(for (i in (1:NumContrastParameterizations))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("ContrastParameterizations.Status.",i,sep="")))
			    )
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"ContrastParameterizations.Status.1"))
		    }
	    )
	    Try(
		    tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)
	    )#end of Try
	    Try(
		    if(NumParameters>0){
			    Try(for (i in (1:NumParameters))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("Parameters.Status.",i,sep="")))
			    )#end of Try-for..
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"Parameters.Status.1"))
		    }
	    )#end of Try-if...
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters","Parameters.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree))
	    if(NumContrastParameterizations>0){
		    for (contrastParameterizationIndex in (1:NumContrastParameterizations)){
			    Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
			    Try(ParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
			    Try(tkdelete(.affylmGUIglobals$ContrastParameterizationTREE,ParameterizationNameNode))
			    Try(assign("ContrastParameterizationList", deleteItemFromList(ContrastParameterizationList,ParameterizationNameNode),affylmGUIenvironment))
		    }#end of for
	    }#end of if
	    Try(initGlobals())
	    Try(LimmaFileName <- get("LimmaFileName",affylmGUIenvironment))
      Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
      Try(if(.Platform$OS.type=="windows")
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",gsub("/","\\\\",LimmaFileName))))
	             else
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",LimmaFileName)))
      )#end of Try
#	    Try(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)		 <- "Please select a Chip Definition (CDF) file.")
#	    Try(tclvalue(.affylmGUIglobals$CDFfileName)				 <- "No filename is selected at the moment.	Press the Select CDF File Button.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle) <- "Please select a tab-delimited file listing the CEL files.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileName)		 <- "No filename is selected at the moment.	Press the Select Targets File Button.")
	    Try(OpenLargefiles())
	    Try(tkfocus(.affylmGUIglobals$ttMain))

       
       })

        Try(if(ReturnVal=="GEO"){
          Try(assign("whichArrayPlatform","LARGE",affylmGUIenvironment))
##############initialization variables start
                        Try(tt <- "")
                        Try(assign("illuData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("illuData",tt,affylmGUIenvironment))

                        Try(assign("RawAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("NormalizedAffyData.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("unfilteredData.location", tt, affylmGUIenvironment))
                        Try(assign("geoPlatform",  tt, env=affylmGUIenvironment))

                        Try(assign("metaData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("metaData",tt,affylmGUIenvironment))

                        Try(assign("exprConsoleLibs.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exprConsoleLibs", tt ,affylmGUIenvironment))#locate here the library files as a list of data.frames

                        assign("libDir.Available",FALSE,affylmGUIenvironment)
                        assign("libDir", tt ,affylmGUIenvironment)#locate here the library files as a list of data.frames
                        Try(assign("whichLib", tt ,affylmGUIenvironment))#remember the type of exon library loaded

                        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(meVDirLocation <- myinfo[which(myinfo[,1]=="meVDirLocation"),2])
                        Try(if(is.na(meVDirLocation)) meVDirLocation <- tt)
                        if(meVDirLocation != ""){
                          assign("meVDirLocation", meVDirLocation, affylmGUIenvironment)#directory where meV program is located
                          assign("meVDirLocation.Available",TRUE,affylmGUIenvironment)
                        }

                        Try(assign("exonAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exonAffyData", tt ,affylmGUIenvironment))
                        Try(assign("dabg.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("dabg.p" , tt, affylmGUIenvironment))    
                        Try(assign("midas.p" , tt, affylmGUIenvironment))
                        Try(assign("midas.p.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("spliceIndexData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("spliceIndexData", tt ,affylmGUIenvironment))
                        Try(assign("AltSplRP.e.p" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.e.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("AltSplRP.g" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.g.Available" , FALSE, affylmGUIenvironment))
                        
                       	Try(assign("LinearModelFitExon.Available",FALSE,affylmGUIenvironment))
	                      Try(assign("cosie.Available", FALSE ,affylmGUIenvironment))
                        Try(assign("fitExon",tt,affylmGUIenvironment))
                        Try(assign("AltSplLimma" , tt, affylmGUIenvironment))
                        Try(assign("AltSplLimma.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("intronicBg.available", TRUE,affylmGUIenvironment))
                        Try(assign("intronicBg", tt,affylmGUIenvironment))

                        Try(assign("maSigProSigs.Available",FALSE,affylmGUIenvironment))

                        Try(assign("Pset.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("MLdesign.Available",FALSE,affylmGUIenvironment))
                        Try(assign("MLdesign", tt ,affylmGUIenvironment))
                        Try(assign("trainAffyData.available", FALSE, env=affylmGUIenvironment))
                        Try(assign("testAffyData.available", FALSE, env=affylmGUIenvironment))
##############initialization variables end
 #         Try(whichKindOfArray())
          #define the right Menu depending on the platform
          Try(tkfocus(.affylmGUIglobals$ttMain))
          Try(changeMenu())#modify the default manu in aplatform specific menu
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(tkmessageBox(title="Selecting the Array Platform",message="Ony GEO Series Matrix Files could be loaded!", type="ok", icon="info"))  
           Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
    	     Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))
	         Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
	         Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
	         if(limmaDataSetNameText!="Untitled"){
		         Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled"){LimmaFileName <- limmaDataSetNameText} )	# Local assignment only
		         Try(mbVal <- tkmessageBox(title="Start New Analysis",
				         											message=paste("Save changes to ",fixSeps(LimmaFileName),"?",sep=""),
						         									icon="question",type="yesnocancel",default="yes"
								         						 )#end of tkmessageBox
		         )#end of Try(mbVal..
		         if(tclvalue(mbVal)=="yes"){Try(SaveLimmaFile())}
		         if(tclvalue(mbVal)=="cancel"){
			         Try(tkfocus(.affylmGUIglobals$ttMain))
			         return()
		         }#end of if(tclvalue(mbVal)=="cancel")
		         Try(limmaDataSetNameText <- "Untitled")
	         }#end of if(limmaDataSetNameText!="Untitled")
	         #Try(tkmessageBox(title="Working Directory",message="After clicking OK, please select a working directory.",type="ok"))
	         Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(WD <- SetWD())
           Try(tkfocus(.affylmGUIglobals$ttMain))
	         if(WD=="") return()
	    Try(tkdelete(.affylmGUIglobals$mainTree,"RawAffyData.Status"))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFit.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(tkdelete(.affylmGUIglobals$mainTree,"maSIgProData.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","maSIgProData","maSIgProData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"PLM.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","PLM","PLM.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptDabg.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptDabg","AptDabg.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptMidas.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptMidas","AptMidas.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"spliceIndex.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","spliceIndex","spliceIndex.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.e.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.e.Status" ,text="Not Available at exon level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.g.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.g.Status" ,text="Not Available at gene level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"classification.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","classification","classification.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFitExon.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFitExon","LinearModelFitExon.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      #NGS
      Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(
		    if(NumContrastParameterizations>0){
			    Try(for (i in (1:NumContrastParameterizations))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("ContrastParameterizations.Status.",i,sep="")))
			    )
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"ContrastParameterizations.Status.1"))
		    }
	    )
	    Try(
		    tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)
	    )#end of Try
	    Try(
		    if(NumParameters>0){
			    Try(for (i in (1:NumParameters))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("Parameters.Status.",i,sep="")))
			    )#end of Try-for..
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"Parameters.Status.1"))
		    }
	    )#end of Try-if...
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters","Parameters.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree))
	    if(NumContrastParameterizations>0){
		    for (contrastParameterizationIndex in (1:NumContrastParameterizations)){
			    Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
			    Try(ParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
			    Try(tkdelete(.affylmGUIglobals$ContrastParameterizationTREE,ParameterizationNameNode))
			    Try(assign("ContrastParameterizationList", deleteItemFromList(ContrastParameterizationList,ParameterizationNameNode),affylmGUIenvironment))
		    }#end of for
	    }#end of if
	    Try(initGlobals())
	    Try(LimmaFileName <- get("LimmaFileName",affylmGUIenvironment))
      Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
      Try(if(.Platform$OS.type=="windows")
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",gsub("/","\\\\",LimmaFileName))))
	             else
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",LimmaFileName)))
      )#end of Try
#	    Try(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)		 <- "Please select a Chip Definition (CDF) file.")
#	    Try(tclvalue(.affylmGUIglobals$CDFfileName)				 <- "No filename is selected at the moment.	Press the Select CDF File Button.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle) <- "Please select a tab-delimited file listing the CEL files.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileName)		 <- "No filename is selected at the moment.	Press the Select Targets File Button.")
	    Try(OpenGeoFiles())
	    Try(tkfocus(.affylmGUIglobals$ttMain))

       
       })

 } 
 ###############################################################################
 

OpenCDFandTargetsfiles <- function()
{
	require("affy")
	Try(ttCDFandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttCDFandTargets))
	Try(tkgrab.set(ttCDFandTargets))
	Try(tkfocus(ttCDFandTargets))
	Try(tkwm.title(ttCDFandTargets,"Targets file"))
	Try(tkgrid(tklabel(ttCDFandTargets,text="    ")))

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

	OpenCDFFileAndSetCursor <- function()
	{
			Try(tkconfigure(ttCDFandTargets,cursor="watch"))
			Try(tkfocus(ttCDFandTargets))
			Try(OpenCDFFile())
			Try(tkconfigure(ttCDFandTargets,cursor="arrow"))
			Try(tkfocus(ttCDFandTargets))
	}

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

	Try(tclvalue(.affylmGUIglobals$CDFfileName) <- fixSeps(tclvalue(.affylmGUIglobals$CDFfileName)))
	Try(.affylmGUIglobals$CDFfileBoxTitleLabel<-tklabel(ttCDFandTargets,text=as.character(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)),font=.affylmGUIglobals$affylmGUIfont2))
	Try(.affylmGUIglobals$CDFfileNameLabel<-tklabel(ttCDFandTargets,text=as.character(tclvalue(.affylmGUIglobals$CDFfileName)),background="white",font=.affylmGUIglobals$affylmGUIfont2))
	Try(tkconfigure(.affylmGUIglobals$CDFfileBoxTitleLabel, textvariable=.affylmGUIglobals$CDFfileBoxTitle))
	Try(tkconfigure(.affylmGUIglobals$CDFfileNameLabel, textvariable=.affylmGUIglobals$CDFfileName))

#	Try(tkgrid(tklabel(ttCDFandTargets,text="    ")))
#	Try(tkgrid(.affylmGUIglobals$CDFfileBoxTitleLabel,columnspan=4))
#	Try(tkgrid(.affylmGUIglobals$CDFfileNameLabel,columnspan=4))

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

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

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

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

	if(Abort==1)
				return(0)

	#OK
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(Targets <- get("Targets",affylmGUIenvironment))
	Try(slides <- Targets$FileName)
	Try(filesExist <- file.exists(slides))
	Try(filesWhichDontExist <- slides[!filesExist])
	Try(if(length(filesWhichDontExist)>0)
		Try(for (i in (1:length(filesWhichDontExist)))
			Try(tkmessageBox(title="Error opening file",message=paste("Failed to open file: \"",filesWhichDontExist[i],"\"",sep=""),icon="error"))))
	Try(if(length(filesWhichDontExist)>0)
	{
		Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
		return(0)
	})

	Try(RawAffyData <- ReadAffy(filenames=Targets$FileName))
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	Try(assign("RawAffyData",RawAffyData,affylmGUIenvironment))
	Try(assign("RawAffyData.Available",TRUE,affylmGUIenvironment))
	Try(SlideNamesVec <- colnames(exprs(RawAffyData)))
	Try(if("Name" %in% colnames(Targets))
		SlideNamesVec <- Targets$Name)
	Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
	Try(tkdelete(.affylmGUIglobals$mainTree,"RawAffyData.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree))
	Try(ReturnVal <- GetlimmaDataSetName())
	if(ReturnVal==0) return(0)
	return(1)
}
################################################################################

#this function define the organism (hs, mm, rn) of the exon array and the subgroup under analysis (core, extended, full)
#the exon analysis require the library files used by expression console
#in this version of the function user can choose of using tab delimited files calculated by Expression Console or use
#the APT tools to calculate gene/ exon summaries
"whichKindOfArray" <- function(){
Try(tkfocus(.affylmGUIglobals$ttMain))
Try(exonVal <- tkmessageBox(title="Probe sets intensities by Affymetrix APT", message="Do you want to use APT for gene/exon summaries", icon="question",type="yesno",default="yes"))
                    Try(assign("exonVal",exonVal,affylmGUIenvironment)) #the information about the decision of using apt tools for  intenisties calculation
                    Try(whereApt <- get("aptDir",envir=affylmGUIenvironment))
                    Try(if(is.na(whereApt)) whereApt <- "")
                    if(tclvalue(exonVal)=="yes"){
                           #Try(whereApt <- "")
                           #Try(whereApt <- .aptDir())
                           if(whereApt != ""){
                                                   #APT dir
                                                 if(length(grep("apt-probeset-summarize", dir(paste(whereApt, "/bin", sep="")))) == 0){
                                                        Try(tkmessageBox(title="APT tools dir ",message="The main folder where APT tools are located is not correctly defined!",icon="error"))
                                                        assign("aptDir.Available",FALSE,affylmGUIenvironment)
                                                        assign("aptDir", "" ,affylmGUIenvironment)
                                                        Try(aptFolder())
                                                 }  
                                                   Try(assign("aptDir.Available",TRUE,affylmGUIenvironment))
                                                   Try(assign("aptDir", whereApt ,affylmGUIenvironment))

                                                   #select the organism under analysis and the subgroup of the analysis
                                                   Try(ReturnVal <<- "")
                                                   Try(ttIfDialog<-tktoplevel(.affylmGUIglobals$ttMain))
                                                   Try(tkwm.deiconify(ttIfDialog))
                                                   Try(tkgrab.set(ttIfDialog))
                                                   Try(tkfocus(ttIfDialog))
                                                   Try(tkwm.title(ttIfDialog,"Exon/Gene arrays"))
                                                   Try(tkgrid(tklabel(ttIfDialog,text="    ")))
                                                   Try(whichArrayPlatform <- get("whichArrayPlatform",affylmGUIenvironment))
                                                   
                                                   if(whichArrayPlatform == "GENE"){
                                                      Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
                                                      Try(HowManyQuestion1 <- tklabel(frame1,text="Select the organism under analysis",font=.affylmGUIglobals$affylmGUIfont2))
                                                      Try(tkgrid(HowManyQuestion1))
                                                      Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
                                                      Try(thresholdTcl <- tclVar("HuGene"))
                                                      Try(I1.but  <- tkradiobutton(frame1,text="Hs",variable=thresholdTcl,value="HuGene",font=.affylmGUIglobals$affylmGUIfont2))
                                                      Try(I2.but  <- tkradiobutton(frame1,text="Mm",variable=thresholdTcl,value="MoGene",font=.affylmGUIglobals$affylmGUIfont2))
                                                      Try(I3.but  <- tkradiobutton(frame1,text="Rn",variable=thresholdTcl,value="RaGene",font=.affylmGUIglobals$affylmGUIfont2))
													  Try(I4.but  <- tkradiobutton(frame1,text="HTA",variable=thresholdTcl,value="HTA",font=.affylmGUIglobals$affylmGUIfont2))
           
                                                      Try(tkgrid(I1.but,sticky="w"))
                                                      Try(tkgrid(I2.but,sticky="w"))
                                                      Try(tkgrid(I3.but,sticky="w"))
													  Try(tkgrid(I4.but,sticky="w"))
                                                      Try(tkgrid.configure(HowManyQuestion1,I1.but,I2.but,I3.but,I4.but,sticky="w"))

                                                      Try(onOK <- function()
                                                      {
                                                           ReturnVal1 <- as.character(tclvalue(thresholdTcl))
                                                           ReturnVal2 <- "gene" #this is not used in gene 1.0 st arrays
                                                           Try(ReturnVal <<- paste(ReturnVal1, ReturnVal2, sep=";"))
                                                           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(whichArrayPlatform == "EXON"){
                                                      Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
                                                      Try(HowManyQuestion1 <- tklabel(frame1,text="Select the organism under analysis",font=.affylmGUIglobals$affylmGUIfont2))
                                                      Try(tkgrid(HowManyQuestion1))
                                                      Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
                                                      Try(thresholdTcl <- tclVar("HuEx"))
                                                      Try(I1.but  <- tkradiobutton(frame1,text="Hs",variable=thresholdTcl,value="HuEx",font=.affylmGUIglobals$affylmGUIfont2))
                                                      Try(I2.but  <- tkradiobutton(frame1,text="Mm",variable=thresholdTcl,value="MoEx",font=.affylmGUIglobals$affylmGUIfont2))
                                                      Try(I3.but  <- tkradiobutton(frame1,text="Rn",variable=thresholdTcl,value="RaEx",font=.affylmGUIglobals$affylmGUIfont2))
           
                                                      Try(tkgrid(I1.but,sticky="w"))
                                                      Try(tkgrid(I2.but,sticky="w"))
                                                      Try(tkgrid(I3.but,sticky="w"))
                                                      Try(tkgrid.configure(HowManyQuestion1,I1.but,I2.but,I3.but,sticky="w"))

                                                      Try(frame2 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
                                                      Try(fractionLabel <- tklabel(frame2,text="Exon subgroup",font=.affylmGUIglobals$affylmGUIfont2))
                                                      Try(tkgrid(fractionLabel,sticky="w"))
                                                      Try(tkgrid.configure(fractionLabel,sticky="w"))
                                                      Try(fractionTcl <- tclVar("core"))
                                                      Try(F1.but <- tkradiobutton(frame2,text="core",variable=fractionTcl,value="core",font=.affylmGUIglobals$affylmGUIfont2))
                                                      Try(F2.but <- tkradiobutton(frame2,text="extended",variable=fractionTcl,value="extended",font=.affylmGUIglobals$affylmGUIfont2))
                                                      Try(F3.but <- tkradiobutton(frame2,text="full",variable=fractionTcl,value="full",font=.affylmGUIglobals$affylmGUIfont2))

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

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

                                                      Try(onOK <- function()
                                                      {
                                                           ReturnVal1 <- as.character(tclvalue(thresholdTcl))
                                                           ReturnVal2 <- as.character(tclvalue(fractionTcl))
                                                           Try(ReturnVal <<- paste(ReturnVal1, ReturnVal2, sep=";"))
                                                           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,frame2,tklabel(ttIfDialog,text="  ")))
                                                      Try(tkgrid(tklabel(ttIfDialog,text="    ")))
                                                      Try(tkgrid(tklabel(ttIfDialog,text="    "),frame3,tklabel(ttIfDialog,text="  ")))
                                                      Try(tkgrid(tklabel(ttIfDialog,text="    ")))
                                                      Try(tkgrid.configure(frame1,frame3,sticky="w"))

                                                      Try(tkfocus(ttIfDialog))
                                                      Try(tkbind(ttIfDialog, "<Destroy>", function() {Try(tkgrab.release(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
                                                      Try(tkwait.window(ttIfDialog))
                                                  }

                                                  #loading the exon libraries
                                                  if(ReturnVal == ""){
                                                              Try(tkfocus(.affylmGUIglobals$ttMain))
                                                              Try(return())
                                                  }
                                                  Try(tmp<-strsplit(ReturnVal, ";"))
                                                  Try(assign("whichLib", tmp ,affylmGUIenvironment))#saving the type of exon library under use
                                                  #select the directory in which are present the library data for expression console analysis
                                                  Try(libDir <- "")
                                                  Try(libDirLocation <- get("libDirLocation", affylmGUIenvironment))
                                                  #Try(libDir <- libraryFilesDir())
                                                  Try(libDir <- libDirLocation)
                                                  if(libDir != ""){
                                                                           Try(libDir <- paste(libDir, "/", sep=""))
                                                                           Try(content.libDir <- dir(libDir))
                                                                           if(length(grep(tmp[[1]][1],content.libDir)) == 0){
                                                                                  Try(tkmessageBox(title="Gene/Exon libraries Dir",message=paste("The selected folder does not contain ", tmp[[1]][1], " library files!\n Download them using the function provided in the general tools!", sep=""),icon="error"))
                                                                                  Try(return())
                                                                           }
                                                                           assign("libDir.Available",TRUE,affylmGUIenvironment)
                                                                           assign("libDir", libDir ,affylmGUIenvironment)#locate here the library files as a list of data.frames
                                                                           if(whichArrayPlatform == "EXON"){
                                                                               Try(ctrl.name <- paste(libDir, content.libDir[intersect(grep(tmp[[1]][1],content.libDir), grep('controls.ps$',content.libDir))], sep=""))
                                                                               Try(ctrl <- read.table(ctrl.name, sep="\t", header=T, as.is=T))
                                                                               Try(exonlib.name <- paste(libDir, content.libDir[intersect(grep('.mps$',content.libDir), intersect(grep(tmp[[1]][1],content.libDir), grep(tmp[[1]][2],content.libDir)))], sep=""))
                                                                               Try(exonlib <- read.table(exonlib.name, sep="\t", header=T, as.is=T))
                                                                               Try(ctrl.exonlib <- list("controls"=ctrl, "exon.library"=exonlib))
                                                                               Try(assign("exprConsoleLibs.Available",TRUE,affylmGUIenvironment))
                                                                               Try(assign("exprConsoleLibs", ctrl.exonlib ,affylmGUIenvironment))
                                                                               Try(cat(""))
                                                                           }
                                                                           if(whichArrayPlatform == "GENE"){
																	           Try(whichLib <- get("whichLib",envir=affylmGUIenvironment))
																	           #mapping the clf pgf files
																	           Try(content.libDir <- dir(libDir))
																	           
                                                                               #Try(ctrl.name <- paste(libDir, content.libDir[intersect(grep(tmp[[1]][1],content.libDir), grep('controls.ps$',content.libDir))], sep=""))
                                                                               #Try(ctrl <- read.table(ctrl.name, sep="\t", header=T, as.is=T))
                                                                               Try(ctrl <- "")
																			   
                                                                               Try(glibVal <- tkmessageBox(title="Gene library version", message="Are you using genechips version 2.0?\nIf you answer NO version 1.0 of library files will be loaded.",
																							         									icon="question",type="yesnocancel",default="no"
																									         						 )#end of tkmessageBox
																	           )#end of Try(glibVal..
																			       if(tclvalue(glibVal)=="yes"){
																	               Try(libVersion <- paste(whichLib[[1]][1], "-2_0", sep=""))
																	               Try(clf.name <- paste(libDir, content.libDir[intersect(grep(libVersion,content.libDir), grep('.clf$',content.libDir))], sep=""))
																	               Try(pgf.name <- paste(libDir, content.libDir[intersect(grep(libVersion,content.libDir), grep('.pgf$',content.libDir))], sep=""))
																	               #defining the meta gene subset
	                                                                               Try(htaVal <- tkmessageBox(title="HTA", message="You are using HTA 2.0 GeneChips.\nDo you want to run analysis at isoform level?\nIf you answer NO gene-level analysis will be run.",
																								         									icon="question",type="yesnocancel",default="no"
																										         						 )#end of tkmessageBox
																		           )#end of Try(htaVal..
																				   if(tclvalue(htaVal)=="yes"){	   
																	                      Try(exonlib.name <- paste(libDir, content.libDir[intersect(grep('.ps$',content.libDir), grep(libVersion,content.libDir))], sep=""))
																	                      Try(exonlib.name <- exonlib.name[2])
																					   }else{
	 																	                  Try(exonlib.name <- paste(libDir, content.libDir[intersect(grep('.mps$',content.libDir), grep(libVersion,content.libDir))], sep=""))
																					   }
																	          } else if(tclvalue(glibVal)=="no"){
																	               Try(libVersion <- paste(whichLib[[1]][1], "-1_0", sep=""))
																	               Try(clf.name <- paste(libDir, content.libDir[intersect(grep(libVersion,content.libDir), grep('.clf$',content.libDir))], sep=""))
																	               Try(pgf.name <- paste(libDir, content.libDir[intersect(grep(libVersion,content.libDir), grep('.pgf$',content.libDir))], sep=""))
																	               #defining the meta gene subset
																	               Try(exonlib.name <- paste(libDir, content.libDir[intersect(grep('.mps$',content.libDir), grep(libVersion,content.libDir))], sep=""))
																	               #Try(exonlib.name <- exonlib.name[1])
																	           }
																	           Try(geneLibsInfo<-list("clf.name"=clf.name, "pgf.name"=pgf.name, "exonlib.name"=exonlib.name))
																	           Try(assign("geneLibsInfo",  geneLibsInfo,affylmGUIenvironment))
                                                                               Try(exonlib <- read.table(exonlib.name, sep="\t", header=T, as.is=T, fill=T))

                                                                               Try(ctrl.exonlib <- list("controls"=ctrl, "exon.library"=exonlib))
                                                                               Try(assign("exprConsoleLibs.Available",TRUE,affylmGUIenvironment))
                                                                               Try(assign("exprConsoleLibs", ctrl.exonlib ,affylmGUIenvironment))
                                                                               Try(cat(""))
                                                                           }
                                                                           
                                                                     } else {
                                                                           Try(tkmessageBox(title="Gene/exon libraries Dir",message="You have not defined the directory where gene/exon libraries are installed!",icon="error"))
			                                                                     Try(geneExonLibs())
                                                                     }
                                                          Try(cat(""))
                                                   } else {
                                                           Try(aptFolder())
                                                   }
                    } else {
                             Try(ReturnVal <<- "")
                             #summaries uploaded from tab delimited files
                             #select the organism under analysis and the subgroup of the analysis
                             Try(ttIfDialog<-tktoplevel(.affylmGUIglobals$ttMain))
                             Try(tkwm.deiconify(ttIfDialog))
                             Try(tkgrab.set(ttIfDialog))
                             Try(tkfocus(ttIfDialog))
                             Try(tkwm.title(ttIfDialog,"Exon arrays"))
                             Try(tkgrid(tklabel(ttIfDialog,text="    ")))

                             Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
                             Try(HowManyQuestion1 <- tklabel(frame1,text="Select the organism under analysis",font=.affylmGUIglobals$affylmGUIfont2))
                             Try(tkgrid(HowManyQuestion1))
                             Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
                             Try(thresholdTcl <- tclVar("HuEx"))
                             Try(I1.but  <- tkradiobutton(frame1,text="Hs",variable=thresholdTcl,value="HuEx",font=.affylmGUIglobals$affylmGUIfont2))
                             Try(I2.but  <- tkradiobutton(frame1,text="Mm",variable=thresholdTcl,value="MoEx",font=.affylmGUIglobals$affylmGUIfont2))
                             Try(I3.but  <- tkradiobutton(frame1,text="Rn",variable=thresholdTcl,value="RaEx",font=.affylmGUIglobals$affylmGUIfont2))
           
                             Try(tkgrid(I1.but,sticky="w"))
                             Try(tkgrid(I2.but,sticky="w"))
                             Try(tkgrid(I3.but,sticky="w"))
                             Try(tkgrid.configure(HowManyQuestion1,I1.but,I2.but,I3.but,sticky="w"))

                             Try(frame2 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
                             Try(fractionLabel <- tklabel(frame2,text="Exon subgroup",font=.affylmGUIglobals$affylmGUIfont2))
                             Try(tkgrid(fractionLabel,sticky="w"))
                             Try(tkgrid.configure(fractionLabel,sticky="w"))
                             Try(fractionTcl <- tclVar("core"))
                             Try(F1.but <- tkradiobutton(frame2,text="core",variable=fractionTcl,value="core",font=.affylmGUIglobals$affylmGUIfont2))
                             Try(F2.but <- tkradiobutton(frame2,text="extended",variable=fractionTcl,value="extended",font=.affylmGUIglobals$affylmGUIfont2))
                             Try(F3.but <- tkradiobutton(frame2,text="full",variable=fractionTcl,value="full",font=.affylmGUIglobals$affylmGUIfont2))

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

                             Try(tkgrid.configure(fractionLabel,F1.but,F2.but,F3.but,sticky="w"))
                    
                             Try(onOK <- function()
                             {
                                  ReturnVal1 <- as.character(tclvalue(thresholdTcl))
                                  ReturnVal2 <- as.character(tclvalue(fractionTcl))
                                  Try(ReturnVal <<- paste(ReturnVal1, ReturnVal2, sep=";"))
                                  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,frame2,tklabel(ttIfDialog,text="  ")))
                             Try(tkgrid(tklabel(ttIfDialog,text="    ")))
                             Try(tkgrid(tklabel(ttIfDialog,text="    "),frame3,tklabel(ttIfDialog,text="  ")))
                             Try(tkgrid(tklabel(ttIfDialog,text="    ")))
                             Try(tkgrid.configure(frame1,frame3,sticky="w"))

                             Try(tkfocus(ttIfDialog))
                             Try(tkbind(ttIfDialog, "<Destroy>", function() {Try(tkgrab.release(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
                             Try(tkwait.window(ttIfDialog))
                             #loading the exon libraries
                             if(ReturnVal != ""){
                                 Try(tmp<-strsplit(ReturnVal, ";"))
                                 Try(assign("whichLib", tmp ,affylmGUIenvironment))#saving the type of exon library under use
                                 #select the directory in which are present the library data for expression console analysis
                                 Try(libDirLocation <- get("libDirLocation",envir=affylmGUIenvironment))
                                 Try(if(is.na(libDirLocation)) libDirLocation <- "")
                                 #Try(libDir <- "")
                                 #Try(libDir <- libraryFilesDir())
                                 Try(libDir <- libDirLocation)
                                 if(libDir != ""){
                                                     Try(libDir <- paste(libDir, "/", sep=""))
                                                     Try(content.libDir <- dir(libDir))
                                                     if(length(grep(tmp[[1]][1],content.libDir)) == 0){
                                                              Try(tkmessageBox(title="Gene/exon libraries Dir",message=paste("The selected folder does not contain ", tmp[[1]][1], " library files!\n Download them from Affymetrix web site!", sep=""),icon="error"))
                                                              Try(return())
                                                     }
                                                     assign("libDir.Available",TRUE,affylmGUIenvironment)
                                                     assign("libDir", libDir ,affylmGUIenvironment)#locate here the library files as a list of data.frames
                     
                                                     Try(ctrl.name <- paste(libDir, content.libDir[intersect(grep(tmp[[1]][1],content.libDir), grep('controls.ps$',content.libDir))], sep=""))
                                                     Try(ctrl <- read.table(ctrl.name, sep="\t", header=T, as.is=T))
                                                     Try(exonlib.name <- paste(libDir, content.libDir[intersect(grep('.mps$',content.libDir), intersect(grep(tmp[[1]][1],content.libDir), grep(tmp[[1]][2],content.libDir)))], sep=""))
                                                     Try(exonlib <- read.table(exonlib.name, sep="\t", header=T, as.is=T))
                                                     Try(ctrl.exonlib <- list("controls"=ctrl, "exon.library"=exonlib))
                                                     Try(assign("exprConsoleLibs.Available",TRUE,affylmGUIenvironment))
                                                     Try(assign("exprConsoleLibs", ctrl.exonlib ,affylmGUIenvironment))
                                                     Try(cat(""))
                                                  } else {
                                                           Try(tkmessageBox(title="Gene/exon libraries Dir",message="You have not defined the directory where gene/exon libraries are installed!",icon="error"))
			                                                     return()
                                                    }
  
                           } else {
                               Try(tkmessageBox(title="Gene/exon libraries Dir",message="You have not defined the directory where gene/exon libraries are installed!",icon="error"))
                               Try(geneExonLibs())
                            }
                       }
                       Try(tkfocus(.affylmGUIglobals$ttMain))
}

#loading the position of the APT application
".aptDir" <- function (){
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(wd <- tclVar(getwd()))
    Try(if (.Platform$OS.type == "windows") 
        Try(tclvalue(wd) <- gsub("/", "\\\\", tclvalue(wd))))
    Try(ttChooseDir <- tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.title(ttChooseDir, "Please enter the dir in which APT is located"))
    Try(tkwm.deiconify(ttChooseDir))
    Try(tkgrab.set(ttChooseDir))
    Try(tkgrid(tklabel(ttChooseDir, text = "    ")))
    Try(label1 <- tklabel(ttChooseDir, text = "Locate APT dir", 
        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 enter the dir in which APT is located", 
            initialdir = initialdir)))
        Try(if (nchar(dir1) > 0) 
            tclvalue(wd) <- dir1)
        Try(if (.Platform$OS.type == "windows") 
            Try(tclvalue(wd) <- gsub("/", "\\\\", tclvalue(wd))))
    })
    Try(ReturnVal <- "")
    Try(onOK <- function() {
        Try(DirChosen <- tclvalue(wd))
        Try(tkgrab.release(ttChooseDir))
        Try(tkdestroy(ttChooseDir))
        Try(DirChosen <- gsub("\\\\", "/", DirChosen))
        Try(ReturnVal <<- DirChosen)
    })
    Try(onCancel <- function() {
        Try(tkgrab.release(ttChooseDir))
        Try(tkdestroy(ttChooseDir))
        Try(return())
    })
    Try(Browse.but <- tkbutton(ttChooseDir, text = "Browse", 
        command = onBrowse, font = .affylmGUIglobals$affylmGUIfont2))
    Try(OK.but <- tkbutton(ttChooseDir, text = "    OK\t\t", 
        command = onOK, font = .affylmGUIglobals$affylmGUIfont2))
    Try(Cancel.but <- tkbutton(ttChooseDir, text = " Cancel ", 
        command = onCancel, font = .affylmGUIglobals$affylmGUIfont2))
    Try(entry1 <- tkentry(ttChooseDir, textvariable = wd, width = 40, 
        font = .affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(tklabel(ttChooseDir, text = "    "), entry1))
    Try(tkgrid.configure(entry1, columnspan = 3))
    Try(tkgrid(tklabel(ttChooseDir, text = "    "), row = 3, 
        column = 4))
    Try(tkgrid(Browse.but, row = 3, column = 5))
    Try(tkgrid(tklabel(ttChooseDir, text = "    "), row = 3, 
        column = 6))
    Try(tkgrid(tklabel(ttChooseDir, text = "    ")))
    Try(tkgrid(tklabel(ttChooseDir, text = "    "), tklabel(ttChooseDir, 
        text = "    "), OK.but, Cancel.but))
    Try(tkgrid.configure(Cancel.but, sticky = "w"))
    Try(tkgrid(tklabel(ttChooseDir, text = "    ")))
    Try(tkfocus(entry1))
    Try(tkbind(ttChooseDir, "<Destroy>", function() tkgrab.release(ttChooseDir)))
    Try(tkbind(entry1, "<Return>", onOK))
    Try(tkwait.window(ttChooseDir))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(return(ReturnVal))
}
################################################################################

#this function save in int affylmGUIenvironment the directory location of the expression console library files.
#these files are needed for exon level analysis
"libraryFilesDir" <- function()
 {
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(wd <- tclVar(getwd()))
    Try(if (.Platform$OS.type == "windows") 
        Try(tclvalue(wd) <- gsub("/", "\\\\", tclvalue(wd))))
    Try(ttChooseDir <- tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.title(ttChooseDir, "Choose Expression Console library files dir"))
    Try(tkwm.deiconify(ttChooseDir))
    Try(tkgrab.set(ttChooseDir))
    Try(tkgrid(tklabel(ttChooseDir, text = "    ")))
    Try(label1 <- tklabel(ttChooseDir, text = "Choose Expression Console library files dir: ", 
        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 Expression Console library files dir", 
            initialdir = initialdir)))
        Try(if (nchar(dir1) > 0) 
            tclvalue(wd) <- dir1)
        Try(if (.Platform$OS.type == "windows") 
            Try(tclvalue(wd) <- gsub("/", "\\\\", tclvalue(wd))))
    })
    Try(ReturnVal <- "")
    Try(onOK <- function() {
        Try(DirChosen <- tclvalue(wd))
        Try(tkgrab.release(ttChooseDir))
        Try(tkdestroy(ttChooseDir))
        Try(DirChosen <- gsub("\\\\", "/", DirChosen))
        Try(ReturnVal <<- DirChosen)
    })
    Try(onCancel <- function() {
        Try(tkgrab.release(ttChooseDir))
        Try(tkdestroy(ttChooseDir))
        Try(return())
    })
    Try(Browse.but <- tkbutton(ttChooseDir, text = "Browse", 
        command = onBrowse, font = .affylmGUIglobals$affylmGUIfont2))
    Try(OK.but <- tkbutton(ttChooseDir, text = "    OK\t\t", 
        command = onOK, font = .affylmGUIglobals$affylmGUIfont2))
    Try(Cancel.but <- tkbutton(ttChooseDir, text = " Cancel ", 
        command = onCancel, font = .affylmGUIglobals$affylmGUIfont2))
    Try(entry1 <- tkentry(ttChooseDir, textvariable = wd, width = 40, 
        font = .affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(tklabel(ttChooseDir, text = "    "), entry1))
    Try(tkgrid.configure(entry1, columnspan = 3))
    Try(tkgrid(tklabel(ttChooseDir, text = "    "), row = 3, 
        column = 4))
    Try(tkgrid(Browse.but, row = 3, column = 5))
    Try(tkgrid(tklabel(ttChooseDir, text = "    "), row = 3, 
        column = 6))
    Try(tkgrid(tklabel(ttChooseDir, text = "    ")))
    Try(tkgrid(tklabel(ttChooseDir, text = "    "), tklabel(ttChooseDir, 
        text = "    "), OK.but, Cancel.but))
    Try(tkgrid.configure(Cancel.but, sticky = "w"))
    Try(tkgrid(tklabel(ttChooseDir, text = "    ")))
    Try(tkfocus(entry1))
    Try(tkbind(ttChooseDir, "<Destroy>", function() tkgrab.release(ttChooseDir)))
    Try(tkbind(entry1, "<Return>", onOK))
    Try(tkwait.window(ttChooseDir))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(return(ReturnVal))
}
################################################################################

#this function change manu of the affylmGUI depending on the available platform
"changeMenu" <- function(){
          Try(tkfocus(.affylmGUIglobals$ttMain))
          Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
          if(whichArrayPlatform=="AFFY"){
             #changing the menu to be used for exons data
             Try(topMenu <- tkmenu(.affylmGUIglobals$ttMain))
 	       	   Try(tkconfigure(.affylmGUIglobals$ttMain,menu=topMenu))
	       	   Try(Menus <- read.table(file.path(system.file("etc",package="oneChannelGUI"),"affylmGUI-menus.affy.txt"), as.is=TRUE))
	       	   Try(
		       	   for (m in 1:nrow(Menus)){
			       	   Try(if(Menus[m, 1] == "menu"){
					         	assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))
				       	    }else if(Menus[m, 1] == "item"){
					       	  if(Menus[m, 3] == "command")
						       	  tkadd(eval(parse(text=Menus[m, 2])),"command", label=Menus[m, 4], command=eval(parse(text=Menus[m, 5])))
					       	   else if(Menus[m, 3] == "cascade"){
						       	   cascadeMenu <- eval(parse(text=Menus[m, 5]))
						       	   tkadd(eval(parse(text=Menus[m, 2])),"cascade", label=Menus[m, 4], menu=cascadeMenu)
						       	 if(Menus[m, 4]=="File"){
							         	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
							       	  Try(menuNames <- unique(Menus[,2,drop=TRUE]))
							       	  Try(numMenus <- length(menuNames))
							       	  Try(menus <- list())
							       	  Try(for (j in (1:numMenus))
								       	  menus[[j]] <- eval(parse(text=Menus[j,2]))
							       	  )#end of Try
							       	  Try(names(menus) <- menuNames)
							       	  Try(affylmGUIglobals$menus <- menus)
							       	  Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
						       	   }#end of if(Menus[m, 4]=="File")
					       	   }else if(Menus[m, 3] == "separator"){#end of else if(Menus[m, 3] == "cascade")
						       	  if(nrow(Menus)>m && Menus[m+1, 4]=="Exit"){
							       	  recentFilesFileName <- system.file("etc/recent-files.txt",package="oneChannelGUI")
							       	  recentFiles <- readLines(recentFilesFileName)
							       	  recentFiles <- gsub("\\\\","/",recentFiles)
							       	  # Remove any blank lines:
							       	  blanks <- grep("^[ \t\n]*$",recentFiles)
							       	  if(length(blanks)>0)
								       	  recentFiles <- recentFiles[-blanks]
							       	    numRecentFiles <- length(recentFiles)
							       	  if(numRecentFiles>0){
								       	   tkadd(eval(parse(text=Menus[m, 2])),"separator")
								       	   for (i in (1:numRecentFiles)){
									       	   label <- recentFiles[i]
									       	   fileNameOnly <- strsplit(label,"/")[[1]]
								       	     fileNameOnly <- fileNameOnly[length(fileNameOnly)]
									       	   if(nchar(recentFiles[i])>60)
											         	label <- paste(".../",fileNameOnly)
									       	      eval(parse(text=paste("assign(\".OpenALimmaFile_",i,"\",function() OpenALimmaFile(\"",recentFiles[i],"\"),.GlobalEnv)",sep="")))
									       	   Try(
										       	   if(.Platform$OS.type=="windows"){
											       	   tkadd(
												       	   eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",gsub("/","\\\\",label),sep=""),
												       	   command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
											       	   )#end of tkadd
									       	     }else{
											       	    tkadd(
											       	    eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",label,sep=""),
												       	  command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
											       	 )#end of tkadd
										       	 }#end of else/if
							       	     )#end of Try
								       	 }#end of for (i in (1:numRecentFiles))
							       	 }#end of if(numRecentFiles>0)
						       	 }#end of if(nrow(Menus)>m && Menus[m+1, 4]=="Exit")
						       	  tkadd(eval(parse(text=Menus[m, 2])),"separator")
					       	    }else{
						         	  stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
					       	    }#end of else if(Menus[m, 3] == "separator")
				     	      }else{
					         	    stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
			   	      }#end of else/if(Menus[m, 1] == "item")
			       	)#end of Try(if(Menus[m, 1] == "menu") assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))...)
		       	}#end of for (m in 1:nrow(Menus))
	       	)#end of Try(for (m in 1:nrow(Menus))..)

	       	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
	       	Try(affylmGUIglobals$mainMenu <- topMenu)
	       	Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
    }        
###########################################################################################
          if(whichArrayPlatform=="GENE"){
             #changing the menu to be used for exons data
             Try(topMenu <- tkmenu(.affylmGUIglobals$ttMain))
 	       	   Try(tkconfigure(.affylmGUIglobals$ttMain,menu=topMenu))
	       	   Try(Menus <- read.table(file.path(system.file("etc",package="oneChannelGUI"),"affylmGUI-menus.gene.txt"), as.is=TRUE))
	       	   Try(
		       	   for (m in 1:nrow(Menus)){
			       	   Try(if(Menus[m, 1] == "menu"){
					         	assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))
				       	    }else if(Menus[m, 1] == "item"){
					       	  if(Menus[m, 3] == "command")
						       	  tkadd(eval(parse(text=Menus[m, 2])),"command", label=Menus[m, 4], command=eval(parse(text=Menus[m, 5])))
					       	   else if(Menus[m, 3] == "cascade"){
						       	   cascadeMenu <- eval(parse(text=Menus[m, 5]))
						       	   tkadd(eval(parse(text=Menus[m, 2])),"cascade", label=Menus[m, 4], menu=cascadeMenu)
						       	 if(Menus[m, 4]=="File"){
							         	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
							       	  Try(menuNames <- unique(Menus[,2,drop=TRUE]))
							       	  Try(numMenus <- length(menuNames))
							       	  Try(menus <- list())
							       	  Try(for (j in (1:numMenus))
								       	  menus[[j]] <- eval(parse(text=Menus[j,2]))
							       	  )#end of Try
							       	  Try(names(menus) <- menuNames)
							       	  Try(affylmGUIglobals$menus <- menus)
							       	  Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
						       	   }#end of if(Menus[m, 4]=="File")
					       	   }else if(Menus[m, 3] == "separator"){#end of else if(Menus[m, 3] == "cascade")
						       	  if(nrow(Menus)>m && Menus[m+1, 4]=="Exit"){
							       	  recentFilesFileName <- system.file("etc/recent-files.txt",package="oneChannelGUI")
							       	  recentFiles <- readLines(recentFilesFileName)
							       	  recentFiles <- gsub("\\\\","/",recentFiles)
							       	  # Remove any blank lines:
							       	  blanks <- grep("^[ \t\n]*$",recentFiles)
							       	  if(length(blanks)>0)
								       	  recentFiles <- recentFiles[-blanks]
							       	    numRecentFiles <- length(recentFiles)
							       	  if(numRecentFiles>0){
								       	   tkadd(eval(parse(text=Menus[m, 2])),"separator")
								       	   for (i in (1:numRecentFiles)){
									       	   label <- recentFiles[i]
									       	   fileNameOnly <- strsplit(label,"/")[[1]]
								       	     fileNameOnly <- fileNameOnly[length(fileNameOnly)]
									       	   if(nchar(recentFiles[i])>60)
											         	label <- paste(".../",fileNameOnly)
									       	      eval(parse(text=paste("assign(\".OpenALimmaFile_",i,"\",function() OpenALimmaFile(\"",recentFiles[i],"\"),.GlobalEnv)",sep="")))
									       	   Try(
										       	   if(.Platform$OS.type=="windows"){
											       	   tkadd(
												       	   eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",gsub("/","\\\\",label),sep=""),
												       	   command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
											       	   )#end of tkadd
									       	     }else{
											       	    tkadd(
											       	    eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",label,sep=""),
												       	  command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
											       	 )#end of tkadd
										       	 }#end of else/if
							       	     )#end of Try
								       	 }#end of for (i in (1:numRecentFiles))
							       	 }#end of if(numRecentFiles>0)
						       	 }#end of if(nrow(Menus)>m && Menus[m+1, 4]=="Exit")
						       	  tkadd(eval(parse(text=Menus[m, 2])),"separator")
					       	    }else{
						         	  stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
					       	    }#end of else if(Menus[m, 3] == "separator")
				     	      }else{
					         	    stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
			   	      }#end of else/if(Menus[m, 1] == "item")
			       	)#end of Try(if(Menus[m, 1] == "menu") assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))...)
		       	}#end of for (m in 1:nrow(Menus))
	       	)#end of Try(for (m in 1:nrow(Menus))..)

	       	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
	       	Try(affylmGUIglobals$mainMenu <- topMenu)
	       	Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
    }        
###############################################################################
          if(whichArrayPlatform=="EXON"){
             #changing the menu to be used for exons data
             Try(topMenu <- tkmenu(.affylmGUIglobals$ttMain))
 	       	   Try(tkconfigure(.affylmGUIglobals$ttMain,menu=topMenu))
	       	   Try(Menus <- read.table(file.path(system.file("etc",package="oneChannelGUI"),"affylmGUI-menus.exon.txt"), as.is=TRUE))
	       	   Try(
		       	   for (m in 1:nrow(Menus)){
			       	   Try(if(Menus[m, 1] == "menu"){
					         	assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))
				       	    }else if(Menus[m, 1] == "item"){
					       	  if(Menus[m, 3] == "command")
						       	  tkadd(eval(parse(text=Menus[m, 2])),"command", label=Menus[m, 4], command=eval(parse(text=Menus[m, 5])))
					       	   else if(Menus[m, 3] == "cascade"){
						       	   cascadeMenu <- eval(parse(text=Menus[m, 5]))
						       	   tkadd(eval(parse(text=Menus[m, 2])),"cascade", label=Menus[m, 4], menu=cascadeMenu)
						       	 if(Menus[m, 4]=="File"){
							         	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
							       	  Try(menuNames <- unique(Menus[,2,drop=TRUE]))
							       	  Try(numMenus <- length(menuNames))
							       	  Try(menus <- list())
							       	  Try(for (j in (1:numMenus))
								       	  menus[[j]] <- eval(parse(text=Menus[j,2]))
							       	  )#end of Try
							       	  Try(names(menus) <- menuNames)
							       	  Try(affylmGUIglobals$menus <- menus)
							       	  Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
						       	   }#end of if(Menus[m, 4]=="File")
					       	   }else if(Menus[m, 3] == "separator"){#end of else if(Menus[m, 3] == "cascade")
						       	  if(nrow(Menus)>m && Menus[m+1, 4]=="Exit"){
							       	  recentFilesFileName <- system.file("etc/recent-files.txt",package="oneChannelGUI")
							       	  recentFiles <- readLines(recentFilesFileName)
							       	  recentFiles <- gsub("\\\\","/",recentFiles)
							       	  # Remove any blank lines:
							       	  blanks <- grep("^[ \t\n]*$",recentFiles)
							       	  if(length(blanks)>0)
								       	  recentFiles <- recentFiles[-blanks]
							       	    numRecentFiles <- length(recentFiles)
							       	  if(numRecentFiles>0){
								       	   tkadd(eval(parse(text=Menus[m, 2])),"separator")
								       	   for (i in (1:numRecentFiles)){
									       	   label <- recentFiles[i]
									       	   fileNameOnly <- strsplit(label,"/")[[1]]
								       	     fileNameOnly <- fileNameOnly[length(fileNameOnly)]
									       	   if(nchar(recentFiles[i])>60)
											         	label <- paste(".../",fileNameOnly)
									       	      eval(parse(text=paste("assign(\".OpenALimmaFile_",i,"\",function() OpenALimmaFile(\"",recentFiles[i],"\"),.GlobalEnv)",sep="")))
									       	   Try(
										       	   if(.Platform$OS.type=="windows"){
											       	   tkadd(
												       	   eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",gsub("/","\\\\",label),sep=""),
												       	   command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
											       	   )#end of tkadd
									       	     }else{
											       	    tkadd(
											       	    eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",label,sep=""),
												       	  command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
											       	 )#end of tkadd
										       	 }#end of else/if
							       	     )#end of Try
								       	 }#end of for (i in (1:numRecentFiles))
							       	 }#end of if(numRecentFiles>0)
						       	 }#end of if(nrow(Menus)>m && Menus[m+1, 4]=="Exit")
						       	  tkadd(eval(parse(text=Menus[m, 2])),"separator")
					       	    }else{
						         	  stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
					       	    }#end of else if(Menus[m, 3] == "separator")
				     	      }else{
					         	    stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
			   	      }#end of else/if(Menus[m, 1] == "item")
			       	)#end of Try(if(Menus[m, 1] == "menu") assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))...)
		       	}#end of for (m in 1:nrow(Menus))
	       	)#end of Try(for (m in 1:nrow(Menus))..)

	       	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
	       	Try(affylmGUIglobals$mainMenu <- topMenu)
	       	Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
    }        
 ###########################################################################
           if(whichArrayPlatform=="ILLU"){
             #changing the menu to be used for exons data
             Try(topMenu <- tkmenu(.affylmGUIglobals$ttMain))
 	       	   Try(tkconfigure(.affylmGUIglobals$ttMain,menu=topMenu))
	       	   Try(Menus <- read.table(file.path(system.file("etc",package="oneChannelGUI"),"affylmGUI-menus.illumina.txt"), as.is=TRUE))
	       	   Try(
		       	   for (m in 1:nrow(Menus)){
			       	   Try(if(Menus[m, 1] == "menu"){
					         	assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))
				       	    }else if(Menus[m, 1] == "item"){
					       	  if(Menus[m, 3] == "command")
						       	  tkadd(eval(parse(text=Menus[m, 2])),"command", label=Menus[m, 4], command=eval(parse(text=Menus[m, 5])))
					       	   else if(Menus[m, 3] == "cascade"){
						       	   cascadeMenu <- eval(parse(text=Menus[m, 5]))
						       	   tkadd(eval(parse(text=Menus[m, 2])),"cascade", label=Menus[m, 4], menu=cascadeMenu)
						       	 if(Menus[m, 4]=="File"){
							         	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
							       	  Try(menuNames <- unique(Menus[,2,drop=TRUE]))
							       	  Try(numMenus <- length(menuNames))
							       	  Try(menus <- list())
							       	  Try(for (j in (1:numMenus))
								       	  menus[[j]] <- eval(parse(text=Menus[j,2]))
							       	  )#end of Try
							       	  Try(names(menus) <- menuNames)
							       	  Try(affylmGUIglobals$menus <- menus)
							       	  Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
						       	   }#end of if(Menus[m, 4]=="File")
					       	   }else if(Menus[m, 3] == "separator"){#end of else if(Menus[m, 3] == "cascade")
						       	  if(nrow(Menus)>m && Menus[m+1, 4]=="Exit"){
							       	  recentFilesFileName <- system.file("etc/recent-files.txt",package="oneChannelGUI")
							       	  recentFiles <- readLines(recentFilesFileName)
							       	  recentFiles <- gsub("\\\\","/",recentFiles)
							       	  # Remove any blank lines:
							       	  blanks <- grep("^[ \t\n]*$",recentFiles)
							       	  if(length(blanks)>0)
								       	  recentFiles <- recentFiles[-blanks]
							       	    numRecentFiles <- length(recentFiles)
							       	  if(numRecentFiles>0){
								       	   tkadd(eval(parse(text=Menus[m, 2])),"separator")
								       	   for (i in (1:numRecentFiles)){
									       	   label <- recentFiles[i]
									       	   fileNameOnly <- strsplit(label,"/")[[1]]
								       	     fileNameOnly <- fileNameOnly[length(fileNameOnly)]
									       	   if(nchar(recentFiles[i])>60)
											         	label <- paste(".../",fileNameOnly)
									       	      eval(parse(text=paste("assign(\".OpenALimmaFile_",i,"\",function() OpenALimmaFile(\"",recentFiles[i],"\"),.GlobalEnv)",sep="")))
									       	   Try(
										       	   if(.Platform$OS.type=="windows"){
											       	   tkadd(
												       	   eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",gsub("/","\\\\",label),sep=""),
												       	   command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
											       	   )#end of tkadd
									       	     }else{
											       	    tkadd(
											       	    eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",label,sep=""),
												       	  command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
											       	 )#end of tkadd
										       	 }#end of else/if
							       	     )#end of Try
								       	 }#end of for (i in (1:numRecentFiles))
							       	 }#end of if(numRecentFiles>0)
						       	 }#end of if(nrow(Menus)>m && Menus[m+1, 4]=="Exit")
						       	  tkadd(eval(parse(text=Menus[m, 2])),"separator")
					       	    }else{
						         	  stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
					       	    }#end of else if(Menus[m, 3] == "separator")
				     	      }else{
					         	    stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
			   	      }#end of else/if(Menus[m, 1] == "item")
			       	)#end of Try(if(Menus[m, 1] == "menu") assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))...)
		       	}#end of for (m in 1:nrow(Menus))
	       	)#end of Try(for (m in 1:nrow(Menus))..)

	       	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
	       	Try(affylmGUIglobals$mainMenu <- topMenu)
	       	Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
    }
    
 ###########################################################################################
          if(whichArrayPlatform=="LARGE"){
             #changing the menu to be used for exons data
             Try(topMenu <- tkmenu(.affylmGUIglobals$ttMain))
 	       	   Try(tkconfigure(.affylmGUIglobals$ttMain,menu=topMenu))
	       	   Try(Menus <- read.table(file.path(system.file("etc",package="oneChannelGUI"),"affylmGUI-menus.large.datasets.txt"), as.is=TRUE))
	       	   Try(
		       	   for (m in 1:nrow(Menus)){
			       	   Try(if(Menus[m, 1] == "menu"){
					         	assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))
				       	    }else if(Menus[m, 1] == "item"){
					       	  if(Menus[m, 3] == "command")
						       	  tkadd(eval(parse(text=Menus[m, 2])),"command", label=Menus[m, 4], command=eval(parse(text=Menus[m, 5])))
					       	   else if(Menus[m, 3] == "cascade"){
						       	   cascadeMenu <- eval(parse(text=Menus[m, 5]))
						       	   tkadd(eval(parse(text=Menus[m, 2])),"cascade", label=Menus[m, 4], menu=cascadeMenu)
						       	 if(Menus[m, 4]=="File"){
							         	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
							       	  Try(menuNames <- unique(Menus[,2,drop=TRUE]))
							       	  Try(numMenus <- length(menuNames))
							       	  Try(menus <- list())
							       	  Try(for (j in (1:numMenus))
								       	  menus[[j]] <- eval(parse(text=Menus[j,2]))
							       	  )#end of Try
							       	  Try(names(menus) <- menuNames)
							       	  Try(affylmGUIglobals$menus <- menus)
							       	  Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
						       	   }#end of if(Menus[m, 4]=="File")
					       	   }else if(Menus[m, 3] == "separator"){#end of else if(Menus[m, 3] == "cascade")
						       	  if(nrow(Menus)>m && Menus[m+1, 4]=="Exit"){
							       	  recentFilesFileName <- system.file("etc/recent-files.txt",package="oneChannelGUI")
							       	  recentFiles <- readLines(recentFilesFileName)
							       	  recentFiles <- gsub("\\\\","/",recentFiles)
							       	  # Remove any blank lines:
							       	  blanks <- grep("^[ \t\n]*$",recentFiles)
							       	  if(length(blanks)>0)
								       	  recentFiles <- recentFiles[-blanks]
							       	    numRecentFiles <- length(recentFiles)
							       	  if(numRecentFiles>0){
								       	   tkadd(eval(parse(text=Menus[m, 2])),"separator")
								       	   for (i in (1:numRecentFiles)){
									       	   label <- recentFiles[i]
									       	   fileNameOnly <- strsplit(label,"/")[[1]]
								       	     fileNameOnly <- fileNameOnly[length(fileNameOnly)]
									       	   if(nchar(recentFiles[i])>60)
											         	label <- paste(".../",fileNameOnly)
									       	      eval(parse(text=paste("assign(\".OpenALimmaFile_",i,"\",function() OpenALimmaFile(\"",recentFiles[i],"\"),.GlobalEnv)",sep="")))
									       	   Try(
										       	   if(.Platform$OS.type=="windows"){
											       	   tkadd(
												       	   eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",gsub("/","\\\\",label),sep=""),
												       	   command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
											       	   )#end of tkadd
									       	     }else{
											       	    tkadd(
											       	    eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",label,sep=""),
												       	  command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
											       	 )#end of tkadd
										       	 }#end of else/if
							       	     )#end of Try
								       	 }#end of for (i in (1:numRecentFiles))
							       	 }#end of if(numRecentFiles>0)
						       	 }#end of if(nrow(Menus)>m && Menus[m+1, 4]=="Exit")
						       	  tkadd(eval(parse(text=Menus[m, 2])),"separator")
					       	    }else{
						         	  stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
					       	    }#end of else if(Menus[m, 3] == "separator")
				     	      }else{
					         	    stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
			   	      }#end of else/if(Menus[m, 1] == "item")
			       	)#end of Try(if(Menus[m, 1] == "menu") assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))...)
		       	}#end of for (m in 1:nrow(Menus))
	       	)#end of Try(for (m in 1:nrow(Menus))..)

	       	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
	       	Try(affylmGUIglobals$mainMenu <- topMenu)
	       	Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
    }
    ###########################################################################################
          if(whichArrayPlatform=="NGS"){
             #changing the menu to be used for exons data
             Try(topMenu <- tkmenu(.affylmGUIglobals$ttMain))
 	       	   Try(tkconfigure(.affylmGUIglobals$ttMain,menu=topMenu))
	       	   Try(Menus <- read.table(file.path(system.file("etc",package="oneChannelGUI"),"affylmGUI-menus.ngs.datasets.txt"), as.is=TRUE))
	       	   Try(
		       	   for (m in 1:nrow(Menus)){
			       	   Try(if(Menus[m, 1] == "menu"){
					         	assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))
				       	    }else if(Menus[m, 1] == "item"){
					       	  if(Menus[m, 3] == "command")
						       	  tkadd(eval(parse(text=Menus[m, 2])),"command", label=Menus[m, 4], command=eval(parse(text=Menus[m, 5])))
					       	   else if(Menus[m, 3] == "cascade"){
						       	   cascadeMenu <- eval(parse(text=Menus[m, 5]))
						       	   tkadd(eval(parse(text=Menus[m, 2])),"cascade", label=Menus[m, 4], menu=cascadeMenu)
						       	 if(Menus[m, 4]=="File"){
							         	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
							       	  Try(menuNames <- unique(Menus[,2,drop=TRUE]))
							       	  Try(numMenus <- length(menuNames))
							       	  Try(menus <- list())
							       	  Try(for (j in (1:numMenus))
								       	  menus[[j]] <- eval(parse(text=Menus[j,2]))
							       	  )#end of Try
							       	  Try(names(menus) <- menuNames)
							       	  Try(affylmGUIglobals$menus <- menus)
							       	  Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
						       	   }#end of if(Menus[m, 4]=="File")
					       	   }else if(Menus[m, 3] == "separator"){#end of else if(Menus[m, 3] == "cascade")
						       	  if(nrow(Menus)>m && Menus[m+1, 4]=="Exit"){
							       	  recentFilesFileName <- system.file("etc/recent-files.txt",package="oneChannelGUI")
							       	  recentFiles <- readLines(recentFilesFileName)
							       	  recentFiles <- gsub("\\\\","/",recentFiles)
							       	  # Remove any blank lines:
							       	  blanks <- grep("^[ \t\n]*$",recentFiles)
							       	  if(length(blanks)>0)
								       	  recentFiles <- recentFiles[-blanks]
							       	    numRecentFiles <- length(recentFiles)
							       	  if(numRecentFiles>0){
								       	   tkadd(eval(parse(text=Menus[m, 2])),"separator")
								       	   for (i in (1:numRecentFiles)){
									       	   label <- recentFiles[i]
									       	   fileNameOnly <- strsplit(label,"/")[[1]]
								       	     fileNameOnly <- fileNameOnly[length(fileNameOnly)]
									       	   if(nchar(recentFiles[i])>60)
											         	label <- paste(".../",fileNameOnly)
									       	      eval(parse(text=paste("assign(\".OpenALimmaFile_",i,"\",function() OpenALimmaFile(\"",recentFiles[i],"\"),.GlobalEnv)",sep="")))
									       	   Try(
										       	   if(.Platform$OS.type=="windows"){
											       	   tkadd(
												       	   eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",gsub("/","\\\\",label),sep=""),
												       	   command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
											       	   )#end of tkadd
									       	     }else{
											       	    tkadd(
											       	    eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",label,sep=""),
												       	  command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
											       	 )#end of tkadd
										       	 }#end of else/if
							       	     )#end of Try
								       	 }#end of for (i in (1:numRecentFiles))
							       	 }#end of if(numRecentFiles>0)
						       	 }#end of if(nrow(Menus)>m && Menus[m+1, 4]=="Exit")
						       	  tkadd(eval(parse(text=Menus[m, 2])),"separator")
					       	    }else{
						         	  stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
					       	    }#end of else if(Menus[m, 3] == "separator")
				     	      }else{
					         	    stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
			   	      }#end of else/if(Menus[m, 1] == "item")
			       	)#end of Try(if(Menus[m, 1] == "menu") assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))...)
		       	}#end of for (m in 1:nrow(Menus))
	       	)#end of Try(for (m in 1:nrow(Menus))..)

	       	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
	       	Try(affylmGUIglobals$mainMenu <- topMenu)
	       	Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
    }
    Try(tkfocus(.affylmGUIglobals$ttMain))        
}
################################################################################

#modified on 16 12 2006 adding the load of large data set as tab delimited files
"OpenLargefiles" <- function()
{
	Try(tkfocus(.affylmGUIglobals$ttMain))
  require("affy")
	Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttExonandTargets))
	Try(tkgrab.set(ttExonandTargets))
	Try(tkfocus(ttExonandTargets))
	Try(tkwm.title(ttExonandTargets,"Targets file"))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

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

#	OpenExonFileAndSetCursor <- function()
#	{
#			Try(tkconfigure(ttExonandTargets,cursor="watch"))
#			Try(tkfocus(ttExonandTargets))
#			Try(OpenExonFile())
#			Try(tkconfigure(ttExonandTargets,cursor="arrow"))
#			Try(tkfocus(ttExonandTargets))
#	}

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

	#Try(tclvalue(.affylmGUIglobals$CDFfileName) <- fixSeps(tclvalue(.affylmGUIglobals$CDFfileName)))
	#Try(.affylmGUIglobals$CDFfileBoxTitleLabel<-tklabel(ttCDFandTargets,text=as.character(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)),font=.affylmGUIglobals$affylmGUIfont2))
	#Try(.affylmGUIglobals$CDFfileNameLabel<-tklabel(ttCDFandTargets,text=as.character(tclvalue(.affylmGUIglobals$CDFfileName)),background="white",font=.affylmGUIglobals$affylmGUIfont2))
	#Try(tkconfigure(.affylmGUIglobals$CDFfileBoxTitleLabel, textvariable=.affylmGUIglobals$CDFfileBoxTitle))
	#Try(tkconfigure(.affylmGUIglobals$CDFfileNameLabel, textvariable=.affylmGUIglobals$CDFfileName))

#	Try(tkgrid(tklabel(ttCDFandTargets,text="    ")))
#	Try(tkgrid(.affylmGUIglobals$CDFfileBoxTitleLabel,columnspan=4))
#	Try(tkgrid(.affylmGUIglobals$CDFfileNameLabel,columnspan=4))

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

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

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

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

	if(Abort==1)
				return(0)

	#OK
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(Targets <- get("Targets",affylmGUIenvironment))
	Try(slides <- Targets$FileName)
	#################################################
  #not used for exons from expression console
  #Try(filesExist <- file.exists(slides))
	#Try(filesWhichDontExist <- slides[!filesExist])
	#Try(if(length(filesWhichDontExist)>0)
	#	Try(for (i in (1:length(filesWhichDontExist)))
	#		Try(tkmessageBox(title="Error opening file",message=paste("Failed to open file: \"",filesWhichDontExist[i],"\"",sep=""),icon="error"))))
	#Try(if(length(filesWhichDontExist)>0)
	#{
	#	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	#	return(0)
	#})
  #########################################################

  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  Try(target.array.names <- sub(".CEL", "", tmp1.pd$FileName))
  Try(my.exons <- OpenLargeFile())#loading gene level data
  Try(my.exons.array.names <- NULL)
  Try(    for( i in 1:length(target.array.names)){
          if(length(grep(target.array.names[i], names(my.exons))) == 1){
              my.exons.array.names[i] <- grep(target.array.names[i], names(my.exons))
          } else{
               error.message <- paste("\nERROR! Filenames are not unique!\n", target.array.names[i], " is a substring of ", paste(names(my.exons)[grep(target.array.names[i], names(my.exons))],sep=","), "\n", sep="")
               cat("\nERROR! Filenames are not unique!\n")
               cat(error.message)
               cat("\nYou need to modify filenames since the function is unable to correctly associate arrays to target Filenames\n")
               Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
               return()
          }
      })
  Try(my.exons <- my.exons[,my.exons.array.names])
  Try(names(my.exons) <-  tmp1.pd$FileName)

  Try(startFun <- tclvalue(tkmessageBox(title="Log transformation",message="Do you wish to log2 transform your data?",type="yesno",icon="question")))
  Try(if (startFun=="yes"){my.exons <- log2(my.exons)})

  Try(NormalizedAffyData <- new("ExpressionSet", exprs=as.matrix(my.exons), phenoData=tmp1.pd, annotation=""))
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
        Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
	Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
        Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Normalized data from tab delimited file",font=.affylmGUIglobals$affylmGUIfontTree))

	Try(if("Name" %in% colnames(Targets))
	SlideNamesVec <- Targets$Name)
	Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
  Try(tkfocus(.affylmGUIglobals$ttMain))
 	Try(ReturnVal <- GetlimmaDataSetName())
	if(ReturnVal==0) return(0)
	return(1)


}
#loading the tab delimited file
OpenLargeFile <- function(){
          Try(tkmessageBox(title="Large data set analysis",message="Open the file, containing the normalized expression data.
          This file should be tab delimited with identifiers in first 
          row and array names in the header.\n"))  
          my.exons <- OpenAFile()
}


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

#modified on 16 12 2006 adding the load of large data set as tab delimited files
"OpenGeoFiles" <- function()
{
	Try(tkfocus(.affylmGUIglobals$ttMain))
  require("affy")
	Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttExonandTargets))
	Try(tkgrab.set(ttExonandTargets))
	Try(tkfocus(ttExonandTargets))
	Try(tkwm.title(ttExonandTargets,"Targets file"))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

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

#	OpenExonFileAndSetCursor <- function()
#	{
#			Try(tkconfigure(ttExonandTargets,cursor="watch"))
#			Try(tkfocus(ttExonandTargets))
#			Try(OpenExonFile())
#			Try(tkconfigure(ttExonandTargets,cursor="arrow"))
#			Try(tkfocus(ttExonandTargets))
#	}

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

	#Try(tclvalue(.affylmGUIglobals$CDFfileName) <- fixSeps(tclvalue(.affylmGUIglobals$CDFfileName)))
	#Try(.affylmGUIglobals$CDFfileBoxTitleLabel<-tklabel(ttCDFandTargets,text=as.character(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)),font=.affylmGUIglobals$affylmGUIfont2))
	#Try(.affylmGUIglobals$CDFfileNameLabel<-tklabel(ttCDFandTargets,text=as.character(tclvalue(.affylmGUIglobals$CDFfileName)),background="white",font=.affylmGUIglobals$affylmGUIfont2))
	#Try(tkconfigure(.affylmGUIglobals$CDFfileBoxTitleLabel, textvariable=.affylmGUIglobals$CDFfileBoxTitle))
	#Try(tkconfigure(.affylmGUIglobals$CDFfileNameLabel, textvariable=.affylmGUIglobals$CDFfileName))

#	Try(tkgrid(tklabel(ttCDFandTargets,text="    ")))
#	Try(tkgrid(.affylmGUIglobals$CDFfileBoxTitleLabel,columnspan=4))
#	Try(tkgrid(.affylmGUIglobals$CDFfileNameLabel,columnspan=4))

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

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

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

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

	if(Abort==1)
				return(0)

	#OK
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(Targets <- get("Targets",affylmGUIenvironment))
	Try(slides <- Targets$FileName)
	#################################################
  #not used for exons from expression console
  #Try(filesExist <- file.exists(slides))
	#Try(filesWhichDontExist <- slides[!filesExist])
	#Try(if(length(filesWhichDontExist)>0)
	#	Try(for (i in (1:length(filesWhichDontExist)))
	#		Try(tkmessageBox(title="Error opening file",message=paste("Failed to open file: \"",filesWhichDontExist[i],"\"",sep=""),icon="error"))))
	#Try(if(length(filesWhichDontExist)>0)
	#{
	#	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	#	return(0)
	#})
  #########################################################

  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  Try(target.array.names <- sub(".CEL", "", tmp1.pd$FileName))
  Try(my.exons <- OpenGeoFile())#loading gene level data
  Try(my.exons.array.names <- NULL)
  Try(    for( i in 1:length(target.array.names)){
                    if(length(grep(target.array.names[i], names(my.exons))) == 1){
                       my.exons.array.names[i] <- grep(target.array.names[i], names(my.exons))
                       } else{
                              error.message <- paste("\nERROR! Filenames are not unique!\n", target.array.names[i], " is a substring of ", paste(names(my.exons)[grep(target.array.names[i], names(my.exons))],sep=","), "\n", sep="")
                              cat("\nERROR! Filenames are not unique!\n")
                              cat(error.message)
                              cat("\nYou need to modify filenames since the function is unable to correctly associate arrays to target Filenames\n")
                              Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                              return()
                       }
      })
  Try(my.exons <- my.exons[,my.exons.array.names])
  Try(names(my.exons) <-  tmp1.pd$FileName)
  Try(startFun <- tclvalue(tkmessageBox(title="Log transformation",message="Do you wish to log2 transform your data?",type="yesno",icon="question")))
       Try(if (startFun=="yes"){my.exons <- log2(my.exons)})
  ########adding bioc annlib to geo data
  Try(data("geoVSbioc",package="oneChannelGUI"))
  Try(geoPlatform <- get("geoPlatform", env=affylmGUIenvironment))
  
  if(geoPlatform == "") {Try(geoAnn <- "")} else{
         Try(geoAnn.loc <- which(geoVSbioc[,1]==geoPlatform))
         if(length(geoAnn.loc)==1){
                Try(geoAnn <- geoVSbioc[geoAnn.loc,4])
         } else Try(geoAnn <- "")
  }
  ########adding bioc annlib to geo data
  
  Try(NormalizedAffyData <- new("ExpressionSet", exprs=as.matrix(my.exons), phenoData=tmp1.pd, annotation=geoAnn))
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
        Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
	Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
        Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Normalized data from GEO Series Matrix file",font=.affylmGUIglobals$affylmGUIfontTree))

	Try(if("Name" %in% colnames(Targets))
	SlideNamesVec <- Targets$Name)
	Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
  Try(tkfocus(.affylmGUIglobals$ttMain))
 	Try(ReturnVal <- GetlimmaDataSetName())
	if(ReturnVal==0) return(0)
	return(1)


}
#loading the tab delimited file
OpenGeoFile <- function(){
          Try(tkmessageBox(title="Large data set analysis",message="Open the GEO Series Matrix file."))  
          my.exons <- OpenAGeoFile()
}


OpenAGeoFile <- function(FileName)
      {
         Try(tempFileName <- tclvalue(tkgetOpenFile(filetypes="{{Text Files} {.txt}} {{All files} *}")))
               if(!nchar(tempFileName))
               {
                  tkfocus(.affylmGUIglobals$ttMain)
                  return()
               }
           ##start grabbing GEO platform info
           Try(con <- file(tempFileName, "r", blocking = FALSE))
           Try(geoInfo <- readLines(con, n=500))
           Try(close(con))
           Try(geoPlatform <- geoInfo[grep("^!Series_platform_id", geoInfo)])
           Try(geoPlatform <- strsplit(geoPlatform, "\\\""))
           Try(geoPlatform <- unlist(geoPlatform))
           Try(geoPlatform <- geoPlatform[2])
           Try(assign("geoPlatform",  geoPlatform, env=affylmGUIenvironment))
           ##end grabbing GEO platform info
           whereSkip <- grep("^!series_matrix_table_begin", geoInfo)
           mySel<-read.table(tempFileName, sep="\t", header=T, as.is=TRUE, row.names=1, skip=whereSkip, fill=T)
           mySel <- mySel[1:(dim(mySel)[1] - 1),]
           return(mySel)
      }
################################################################################
#NGS
"OpenNgsfiles" <- function()
{
	Try(tkfocus(.affylmGUIglobals$ttMain))
 # require("Biostrings")  || stop("library Biostrings could not be found !")
	Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttExonandTargets))
	Try(tkgrab.set(ttExonandTargets))
	Try(tkfocus(ttExonandTargets))
	Try(tkwm.title(ttExonandTargets,"Targets file"))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

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

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

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

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

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

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

	if(Abort==1)
				return(0)
  
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(Targets <- get("Targets",affylmGUIenvironment))
	Try(slides <- Targets$FileName)
	
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  Try(target.array.names <- sub(".CEL", "", tmp1.pd$FileName))
  Try(target.array.names <- paste(tmp1.pd$FileName, ".bed", sep=""))   #giving the extension filename of counts data produced reformatting the output of shrimp
  #NGS reads number and reformatting Tartget in Targets #######################
  Try(tmpTarget <- Targets$Target)
  Try(tmpTarget <- strsplit(tmpTarget, "_"))
  Try(newTarget <- sapply(tmpTarget, function(x)x[1]))
  Try(Targets$Target <- newTarget)
  Try(rownames(Targets) <- NULL)
  Try(assign("Targets",Targets,envir=affylmGUIenvironment))
  Try(totalReads <- sapply(tmpTarget, function(x)x[2]))
  Try(mappedReads <- sapply(tmpTarget, function(x)x[3]))
  Try(assign("totalReads", as.numeric(totalReads),envir=affylmGUIenvironment))
  Try(assign("mappedReads", as.numeric(mappedReads),envir=affylmGUIenvironment))
  #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(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.5))
	Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.25))
  Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.1))
	Try(tkgrid.configure(rbIQR.5,rbIQR.25,rbIQR.1,columnspan=2,sticky="w"))
	Try(tkgrid(tklabel(ttGetOrganism,text="    "),tklabel(ttGetOrganism,text="    ")))
  Try(ReturnVal <- "")
  Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGetOrganism));Try(tkdestroy(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain))})
  Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGetOrganismTcl));Try(tkgrab.release(ttGetOrganism));Try(tkdestroy(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain))})
  Try(OK.but     <- tkbutton(ttGetOrganism,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <- tkbutton(ttGetOrganism,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

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

  Try(tkbind(ttGetOrganism,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkbind(OK.but, "<Return>",onOK))
  Try(tkbind(Cancel.but, "<Return>",onCancel))      
  Try(tkwait.window(ttGetOrganism))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  
  if(ReturnVal == ""){
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
       Try(return())
  } else if (ReturnVal == "hs"){
       Try(genome <- "Hsapiens")
       Try(genome.version <- "hg19")
       Try(chrs <- seq(1, 25))
       Try(chrs.names <- c(chrs[1:22], "X", "Y", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Hsapiens.UCSC.hg19) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Hsapiens.UCSC.hg19") ; require(BSgenome.Hsapiens.UCSC.hg19)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$hg19)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected H. sapiens genome UCSC release hg19.",type="ok", icon="info"))
  } else if (ReturnVal == "mm"){
       Try(genome <- "Mmusculus")
       Try(genome.version <- "mm9")
       Try(chrs <- seq(1, 22))
       Try(chrs.names <- c(chrs[1:19], "X", "Y", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Mmusculus.UCSC.mm9) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Mmusculus.UCSC.mm9") ; require(BSgenome.Mmusculus.UCSC.mm9)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$mm9)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected M. musculus genome UCSC release mm9.",type="ok", icon="info"))
  
  } else if (ReturnVal == "rn"){
       Try(genome <- "Rnorvegicus")
       Try(genome.version <- "rn4")
       Try(chrs <- seq(1, 21))
       Try(chrs.names <- c(chrs[1:19], "X", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Rnorvegicus.UCSC.rn4) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Rnorvegicus.UCSC.rn4") ; require(BSgenome.Rnorvegicus.UCSC.rn4)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$rn4)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected R. norvegicus genome UCSC release rn4.",type="ok", icon="info"))
  }

  
  ##############################################################################
  #mapping via Genominator
   Try(mGen <- tkmessageBox(title="Mapping non-coding RNA using Genominator",
                message="Do you wish to use Genominator to map RNAseq data?\nGenominator allows to produce quickly a data structure to be used for differential expression\n",
                icon="question",type="yesno",default="yes"))
   
   if(tclvalue(mGen)=="yes") {
           chrsMat <- .mappingWgenominator()
   } else{
        ##############################################################################
        #defining reads extension
          Try(ttGetExtension<-tktoplevel(.affylmGUIglobals$ttMain))
          Try(tkwm.deiconify(ttGetExtension))
          Try(tkgrab.set(ttGetExtension))
          Try(tkfocus(ttGetExtension))
          Try(tkwm.title(ttGetExtension,"Extending reads length"))
          Try(tkgrid(tklabel(ttGetExtension,text="    ")))
          Try(ExtensionText <- "35")
          Try(Local.Extension <- tclVar(init=ExtensionText))
          Try(entry.Extension <-tkentry(ttGetExtension,width="10",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.Extension,bg="white"))
          Try(tkgrid(tklabel(ttGetExtension,text="Please enter the size of read extension.",font=.affylmGUIglobals$affylmGUIfont2)))
          Try(tkgrid(entry.Extension))
          onOK <- function()
          {
              Try(ExtensionText <- tclvalue(Local.Extension))
              if(nchar(ExtensionText)==0)
                ExtensionText <- "Unselected"
                Try(assign("ExtensionText",ExtensionText,affylmGUIenvironment))
                Try(tclvalue(.affylmGUIglobals$ExtensionTcl) <- ExtensionText)
                Try(tkgrab.release(ttGetExtension));Try(tkdestroy(ttGetExtension));Try(tkfocus(.affylmGUIglobals$ttMain))
          }
          Try(OK.but <-tkbutton(ttGetExtension,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
          Try(tkgrid(tklabel(ttGetExtension,text="    ")))
          Try(tkgrid(OK.but))
          Try(tkgrid.configure(OK.but))
          Try(tkgrid(tklabel(ttGetExtension,text="       ")))
          Try(tkfocus(entry.Extension))
          Try(tkbind(entry.Extension, "<Return>",onOK))
          Try(tkbind(ttGetExtension, "<Destroy>", function(){Try(tkgrab.release(ttGetExtension));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
          Try(tkwait.window(ttGetExtension))
          Try(tkfocus(.affylmGUIglobals$ttMain))
          Try(extensionSize <- as.numeric(get("ExtensionText",envir=affylmGUIenvironment)))
          ###########################################
          #defining the threshold for peak definition
          Try(ttGetreadThr<-tktoplevel(.affylmGUIglobals$ttMain))
          Try(tkwm.deiconify(ttGetreadThr))
          Try(tkgrab.set(ttGetreadThr))
          Try(tkfocus(ttGetreadThr))
          Try(tkwm.title(ttGetreadThr,"Minimal number of read in a peak"))
          Try(tkgrid(tklabel(ttGetreadThr,text="    ")))
          Try(readThrText <- "8")
          Try(Local.readThr <- tclVar(init=readThrText))
          Try(entry.readThr <-tkentry(ttGetreadThr,width="4",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.readThr,bg="white"))
          Try(tkgrid(tklabel(ttGetreadThr,text="Please enter the minimal number of reads needed \nto define a peak.",font=.affylmGUIglobals$affylmGUIfont2)))
          Try(tkgrid(entry.readThr))
          onOK <- function()
          {
              Try(readThrText <- tclvalue(Local.readThr))
              if(nchar(readThrText)==0)
                readThrText <- "Unselected"
                Try(assign("readThrText",readThrText,affylmGUIenvironment))
                Try(tclvalue(.affylmGUIglobals$readThrTcl) <- readThrText)
                Try(tkgrab.release(ttGetreadThr));Try(tkdestroy(ttGetreadThr));Try(tkfocus(.affylmGUIglobals$ttMain))
          }
          Try(OK.but <-tkbutton(ttGetreadThr,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
          Try(tkgrid(tklabel(ttGetreadThr,text="    ")))
          Try(tkgrid(OK.but))
          Try(tkgrid.configure(OK.but))
          Try(tkgrid(tklabel(ttGetreadThr,text="       ")))
          Try(tkfocus(entry.readThr))
          Try(tkbind(entry.readThr, "<Return>",onOK))
          Try(tkbind(ttGetreadThr, "<Destroy>", function(){Try(tkgrab.release(ttGetreadThr));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
          Try(tkwait.window(ttGetreadThr))
          Try(tkfocus(.affylmGUIglobals$ttMain))
          Try(readsMinSize <- as.numeric(get("readThrText",envir=affylmGUIenvironment)))
          #########################################
          #loading data
          cat("\nBe patient! Preprocessing mapping data ... \n")
          home <- getwd()
          data.dir <- list() #storing the location of IRanges data  
          for(i in 1:length(target.array.names)){
               #creating a random string of 3 character
               tmpSeed <- ceiling(runif(3,1,25))
               tmpType <- sample(c(rep(0,3),rep(1,3), rep(2,3)),3)
               tmpDir <- rep(0,3)
               tmpDir[which(tmpType == 0)] <- letters[tmpSeed[which(tmpType == 0)]]
               tmpDir[which(tmpType == 1)] <- tmpSeed[which(tmpType == 1)]
               tmpDir[which(tmpType == 2)] <- LETTERS[tmpSeed[which(tmpType == 2)]]
               tmpDir <- paste(target.array.names[i], ".", paste(tmpDir, collapse="", sep=""), collapse = "", sep="")
               data.dir[[target.array.names[i]]] <- tmpDir
               tmpDir <- paste(home, "/",  tmpDir, sep="")
               dir.create(path=tmpDir)
               cat("\nProcessing: ",target.array.names[i])
               mappedReads <- read.table(target.array.names[i], sep="\t", fill = TRUE, colClasses = c("character", "character", "character"))
               mappedReads[,3] <-  as.numeric(mappedReads[,3])
               mappedReads <- mappedReads[which(mappedReads[,1] %in% chrs.names),]
               mappedReads <- mappedReads[which(mappedReads[,2] %in% c("1","-1")),]
               mappedReads <- mappedReads[!is.na(mappedReads[,3]),]
               setwd(tmpDir)
               .preProcessingNGS(mappedReads, chrs.names) #splitting data by chr
               setwd(home)
          }
          cat("\nEnd preprocessing mapping data ... \n")
          Try(assign("NGS.Available",TRUE,affylmGUIenvironment))
          #dir preprocessed data location
	        Try(assign("NGSdata", data.dir ,affylmGUIenvironment))
          cat("\nStarting data reformatting.\n")
          require(chipseq) || stop("\nlibrary chipseq is missing!\n")
          chrsMat <- NULL
          #deciding to use df build from data only or derived from ncRNA ensembl annotation
          Try(dfVal <- tkmessageBox(title="Peaks data",
                  message="Do you want to use as peaks scaffold the ncRNA annotation derived from ENSEMBL? \nIf you answer no the peaks scaffold will be generated using whole genome peaks data.\nIf you answer Yes, remember that the mapped data must be generated using as reference the fasta file ncXx.fa file that can be exported from oneChannelGUI\nusing the export function in the General Tool Menu.\n",
                  icon="question",type="yesno",default="no"))
          Try(if(tclvalue(dfVal)=="yes"){
             nc.scaffold <- "yes"
          } else  nc.scaffold <- "no")

           for(j in 1: length(chrs.names)){
           cat("\nProcessing: chr", chrs.names[j])
          chrMat <- .fromNGStoDf(j ,chrs.names, chrs.length, data.dir, extensionSize, readsMinSize, home, nc.scaffold)
          chrsMat <- rbind(chrsMat, chrMat)
          }
          cat("\nEnding data reformatting.\n")
   } 
  
  #Creating the expression set
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  Try(NormalizedAffyData <- new("ExpressionSet", assayData = assayDataNew(exprs=as.matrix(chrsMat)) , phenoData=tmp1.pd, annotation=genome.version))
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
  Try(assign("NGS.Available",TRUE,affylmGUIenvironment))
	Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="NGS counts",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status" ,text="NGS data",font=.affylmGUIglobals$affylmGUIfontTree))

	Try(if("Name" %in% colnames(Targets))
	SlideNamesVec <- Targets$Name)
	Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
  Try(tkfocus(.affylmGUIglobals$ttMain))
 	Try(ReturnVal <- GetlimmaDataSetName())
	if(ReturnVal==0) return(0)
	return(1)


}
#splitting data by chr 
.preProcessingNGS <- function(mappedReads, chrs.names){
   myrdP <- mappedReads[which(mappedReads[,2] == "1"),]
   myrdM <- mappedReads[which(mappedReads[,2] == "-1"),]
   for(j in chrs.names){
             tmpIR <- myrdP[which(myrdP[,1] == j),3] #column 1 chr, column2 strand, column 3 location
             save(tmpIR, file=paste(j,"p.rda", sep=""))
             tmpIR <- myrdM[which(myrdM[,1] == j),3]
             save(tmpIR, file=paste(j,"m.rda", sep=""))
  }
 return()
} 
#finding overlaps
.myfindOverlaps <- function(x,y) findOverlaps(x, y)       

#bringing NGS to a matrix of counts
  .fromNGStoDf  <- function(j, chrs.names, chrs.length, data.dir, extensionSize, readsMinSize, home, nc.scaffold){
      if(nc.scaffold == "no"){                                                                                          
           dfP <- NULL
           dfM <- NULL
           allIrP <- NULL
           allIrM <- NULL
           myIrP <- list()
           myIrM <- list()
           myP <- paste(chrs.names[j], "p.rda", sep="")
           myM <- paste(chrs.names[j], "m.rda", sep="") 
           #creating a union of all count over the data sets and a list of counts in each dataset
           for (i in 1: length(data.dir)){
              load(paste(home, "/", data.dir[[i]], "/", myP, sep=""))
              allIrP <- c(allIrP, tmpIR)
              myIrP[[i]] <- tmpIR
              load(paste(home, "/", data.dir[[i]], "/", myM, sep=""))
              allIrM <- c(allIrM, tmpIR)
              myIrM[[i]] <- tmpIR
           }
           #creating plus strand df 
           if(length(allIrP) > 0){         
             chrIrP <- IRanges(start= allIrP, width = extensionSize)
             g1 <- coverage(chrIrP, width = chrs.length[j])
             s <- slice(g1, lower = readsMinSize * length(data.dir))
             peaksP <- IRanges(start = start(s), end = end(s))   # peaks to be located in the dfP
             if(length(peaksP) > 0){
               dfP <- matrix(data = rep(0, length(peaksP) * length(data.dir)), ncol = length(data.dir))
               peaksNames <- paste("chr", chrs.names[j], ".", "plus", ".", start(peaksP), "-", end(peaksP), sep="")
               dimnames(dfP) <- list(peaksNames, names(data.dir))
               for (i in 1: length(data.dir)){
                  if(length(myIrP[[i]]) > 0){
                     toBeMapped <- IRanges(start = myIrP[[i]], width =1)
                     readsInPeak <- sapply(peaksP, .myfindOverlaps, y = toBeMapped)
                     peaks.length <- sapply(readsInPeak, length)
                     dfP[,i] <- peaks.length
                  } 
               }
             }
           }  
           #creating minus strand df
           if(length(allIrM) > 0){           
               chrIrM <- IRanges(start= allIrM, width = extensionSize)
               g1 <- coverage(chrIrM, width = chrs.length[j])
               s <- slice(g1, lower = readsMinSize * length(data.dir))
               peaksM <- IRanges(start = start(s), end = end(s))
               if(length(peaksM) > 0){
                   dfM <- matrix(data = rep(0, length(peaksM) * length(data.dir)), ncol = length(data.dir))
                   peaksNames <- paste("chr", chrs.names[j], ".", "minus", ".", start(peaksM), "-", end(peaksM), sep="")
                   dimnames(dfM) <- list(peaksNames, names(data.dir))
                   for (i in 1: length(data.dir)){
                     if(length(myIrM[[i]]) > 0){
                        toBeMapped <- IRanges(start = myIrM[[i]], width =1)
                        readsInPeak <- sapply(peaksM, .myfindOverlaps, y = toBeMapped)
                        peaks.length <- sapply(readsInPeak, length)
                        dfM[,i] <- peaks.length
                    } 
                  }
               }
            }   
           #combining plus and minus strands
           chrMat <- rbind(dfP, dfM)
           return(chrMat)
   } else {
           dfP <- NULL
           dfM <- NULL
           myIrP <- list()
           myIrM <- list()
           myP <- paste(chrs.names[j], "p.rda", sep="")
           myM <- paste(chrs.names[j], "m.rda", sep="") 
           #using a precompiled nc df scaffold to insert the reads counts the scaffold is only made by the names of the peaks chrN.plus.start.end
           if (length(chrs.length) == 25){
               data("ncHs.data" ,package="oneChannelGUI")
               nc.data <- get("ncHs.data",envir=.GlobalEnv)
           } else if (length(chrs.length) == 22){
               data("ncMm.data" ,package="oneChannelGUI")
               nc.data <- get("ncMm.data",envir=.GlobalEnv)

           } else if (length(chrs.length) == 21){
               data("ncRn.data" ,package="oneChannelGUI")
               nc.data <- get("ncRn.data",envir=.GlobalEnv)

           }
           chrsetP <- paste("^chr",chrs.names[j],".plus", sep="") 
           peaksP <- IRanges(start = start(nc.data$peaksP[grep(chrsetP, names(nc.data$peaksP))]), end = end(nc.data$peaksP[grep(chrsetP, names(nc.data$peaksP))]))
           if(length(peaksP) > 0){
             dfP <- matrix(data = rep(0, length(peaksP) * length(data.dir)), ncol = length(data.dir))
             peaksNames <- names(nc.data$peaksP)[grep(chrsetP, names(nc.data$peaksP))]
             dimnames(dfP) <- list(peaksNames, names(data.dir))
             for (i in 1: length(data.dir)){
                 load(paste(home, "/", data.dir[[i]], "/", myP, sep=""))
                 myIrP <- tmpIR
                 if(length(myIrP) > 0){
                    toBeMapped <- IRanges(start = myIrP, width =1)
                    readsInPeak <- sapply(peaksP, .myfindOverlaps, y = toBeMapped)
                    peaks.length <- sapply(readsInPeak, length)
                    dfP[,i] <- peaks.length
                 } 
             }
           }
           #creating minus strand df
            chrsetN <- paste("^chr",chrs.names[j],".plus", sep="")          
            peaksM <- IRanges(start = start(nc.data$peaksN[grep(chrsetN, names(nc.data$peaksN))]), end = end(nc.data$peaksN[grep(chrsetN, names(nc.data$peaksN))]))
            if(length(peaksM) > 0){
               dfM <- matrix(data = rep(0, length(peaksM) * length(data.dir)), ncol = length(data.dir))
               peaksNames <- names(nc.data$peaksN)[grep(chrsetN, names(nc.data$peaksN))]
               dimnames(dfM) <- list(peaksNames, names(data.dir))
               for (i in 1: length(data.dir)){
                  load(paste(home, "/", data.dir[[i]], "/", myM, sep=""))
                  myIrM <- tmpIR
                  if(length(myIrM) > 0){
                      toBeMapped <- IRanges(start = myIrM, width =1)
                      readsInPeak <- sapply(peaksM, .myfindOverlaps, y = toBeMapped)
                      peaks.length <- sapply(readsInPeak, length)
                      dfM[,i] <- peaks.length
                  }
               }   
            }
            #combining plus and minus strands
            chrMat <- rbind(dfP, dfM)
            return(chrMat)
  }
}




################################################################################
".mappingWgenominator" <- function(){
   cat("\nStart of Genominator mapping...")
   require(Genominator) || stop("library Genominator could not be found !")
   NGSprimaryMapping.Available <- get("NGSprimaryMapping.Available", env=affylmGUIenvironment)
   if(NGSprimaryMapping.Available) NGSprimaryMapping <- get("NGSprimaryMapping", env=affylmGUIenvironment)
   if(NGSprimaryMapping == "SHRIMP"){ 
     Targets <- get("Targets",envir=affylmGUIenvironment)
     Try(ldb <- list())  # for bed files
#     Try(ldbl <- list()) #for logos files
     
     #creating a random string of 3 character
     Try(tmpSeed <- ceiling(runif(3,1,25)))
     Try(tmpType <- sample(c(rep(0,3),rep(1,3), rep(2,3)),3))
     Try(tmpDBname <- rep(0,3))
     Try(tmpDBname[which(tmpType == 0)] <- letters[tmpSeed[which(tmpType == 0)]])
     Try(tmpDBname[which(tmpType == 1)] <- tmpSeed[which(tmpType == 1)])
     Try(tmpDBname[which(tmpType == 2)] <- LETTERS[tmpSeed[which(tmpType == 2)]])
     Try(tmpDBname <- paste(tmpDBname, collapse =""))
     Try(assign("Genominator.Available",TRUE,affylmGUIenvironment))
     Try(assign("GenominatorDB",tmpDBname,affylmGUIenvironment))
     chrs.length <- get("chrsLength", affylmGUIenvironment)
#     Try(mbFilter <- tkmessageBox(title="Removing low quality mapping",
#				    											message="Do you wish to remove all low quality mappings? Pressing YES only single SNP will be retained", icon="question",type="yesno",default="yes"
#								    						 )#end of tkmessageBox
#		 )#end of Try(mbFilter..
     
     ####         da ricontrollare il modo con cui gli snp vengono definiti
     for(i in 1:dim(Targets)[1]){
          count.file <- paste(Targets$FileName[i], ".bed", sep="")
          cat("\nImporting ", count.file, "\n")
          dfc <- read.table(count.file, sep="\t", as.is=T)
          names(dfc) <- c("chr", "strand", "location")

 #         logos.file <- paste(Targets$FileName[i], ".logos", sep="")
 #         cat("\nImporting ", logos.file, "\n")
 #         df <- read.table(logos.file, sep="\t", as.is=T)
          #chr is ensembl gene id reformated in a number if nc-subset is uses else is chr
 #         ensemblgid <- gsub("[A-Z]", "", df[,1])
 #         if(is.na(as.numeric(ensemblgid[1]))){
 #                 ensemblgid <- as.numeric(dfc[,1])
 #         } else ensemblgid <- as.numeric(ensemblgid)
 #         df[,1] <- ensemblgid 
          #location is the starting position of the read mapping on the gene
 #         df[,3] <- as.numeric(df[,3])
          #editstring is reformatted in a way to be only numeric
          #Only perfect matches and single SNP are considered
  #        df <- df[setdiff(seq(1,dim(df)[1]), grep("x", df[,2])),]  # sequencing errors
  #        if(tclvalue(mbFilter)=="yes"){
  #             rBfiltering <- dim(dfc)[1]
  #             cat("\nN. reads: ", dim(dfc)[1],", after removing reads with sequencing errors, N. reads: ")
  #             dfc <- dfc[setdiff(seq(1,dim(df)[1]), grep("x", df[,2])),]
  #             rLeft <- 100*dim(dfc)[1]/rBfiltering
  #             cat(dim(dfc)[1], " ",rLeft ,"% of the reads are left\n")
  #        }
  #        df <- df[setdiff(seq(1,dim(df)[1]), grep("-", df[,2])),]  #multiple deletion in thereference: "5----20"
  #        if(tclvalue(mbFilter)=="yes"){
  #             rBfiltering <- dim(dfc)[1]
  #             cat("\nN. reads: ", dim(dfc)[1],", after removing reads with multiple bases deletions, N. reads: ")
  #             dfc <- dfc[setdiff(seq(1,dim(df)[1]), grep("-", df[,2])),]
  #             rLeft <- 100*dim(dfc)[1]/rBfiltering
  #             cat(dim(dfc)[1], " ",rLeft ,"% of the reads are left\n")
  #        } 
  #        df <- df[setdiff(seq(1,dim(df)[1]), grep("\\(", df[,2])),] #multiple base insertion reference: "3(TGCT)20"
  #        if(tclvalue(mbFilter)=="yes"){
  #             rBfiltering <- dim(dfc)[1]
  #             cat("\nN. reads: ", dim(dfc)[1],", after removing reads with multiple bases insertion, N. reads: ")
  #             dfc <- dfc[setdiff(seq(1,dim(df)[1]), grep("\\(", df[,2])),]
  #             rLeft <- 100*dim(dfc)[1]/rBfiltering
  #             cat(dim(dfc)[1], " ",rLeft ,"% of the reads are left\n")
  #        }
          #removing multiple SNPs
  #        editstring <- df[,2]
  #        df[,2] <- as.character(editstring)
  #        tmpes <- strsplit(editstring, "[A,C,G,T]")
  #        l.tmpes <- sapply(tmpes, length)
  #        df <- df[setdiff(seq(1, length(editstring)), which(l.tmpes > 2)),]
  #        if(tclvalue(mbFilter)=="yes"){
  #            rBfiltering <- dim(dfc)[1]
  #            cat("\nN. reads: ", dim(dfc)[1],", after removing reads with multiple SNPs, N. reads: ")
  #            dfc <- dfc[setdiff(seq(1, length(editstring)), which(l.tmpes > 2)),]
  #            rLeft <- 100*dim(dfc)[1]/rBfiltering
  #            cat(dim(dfc)[1], " ",rLeft ,"% of the reads are left\n")
  #        }
          #single SNP are described in three columns perfect matches befor SNP, snptype perfect matched after SNP
  #       snptype <- rep(0, dim(df)[1])
  #        beforeSnp <- rep(0, dim(df)[1])
  #        afterSnp <- rep(0, dim(df)[1])
  #        editstring <- df[,2]
  #        tmpes <- strsplit(editstring, "A")
  #        l.tmpes <- sapply(tmpes, length)
  #        tmpres <- tmpes[which(l.tmpes == 2)]
  #        tmpresB <- sapply(tmpres, function(x) x[1])    #before SNP
  #        tmpresA <- sapply(tmpres, function(x) x[2])    #after SNP
  #        snptype[which(l.tmpes == 2)] <- rep("A",length(which(l.tmpes == 2)))
  #        beforeSnp[which(l.tmpes == 2)] <- tmpresB
  #        afterSnp[which(l.tmpes == 2)] <- tmpresA 
          #replacing C SNP with .2
  #        tmpes <- strsplit(editstring, "C")
  #        l.tmpes <- sapply(tmpes, length)
  #        tmpres <- tmpes[which(l.tmpes == 2)]
  #        tmpresB <- sapply(tmpres, function(x) x[1])    #before SNP
  #        tmpresA <- sapply(tmpres, function(x) x[2])    #after SNP
  #        snptype[which(l.tmpes == 2)] <- rep("C",length(which(l.tmpes == 2)))
  #        beforeSnp[which(l.tmpes == 2)] <- tmpresB
  #        afterSnp[which(l.tmpes == 2)] <- tmpresA 
          #replacing G SNP with .3
  #        tmpes <- strsplit(editstring, "G")
  #        l.tmpes <- sapply(tmpes, length)
  #        tmpres <- tmpes[which(l.tmpes == 2)]
  #        tmpresB <- sapply(tmpres, function(x) x[1])    #before SNP
  #        tmpresA <- sapply(tmpres, function(x) x[2])    #after SNP
  #        snptype[which(l.tmpes == 2)] <- rep("G",length(which(l.tmpes == 2)))
  #        beforeSnp[which(l.tmpes == 2)] <- tmpresB
  #        afterSnp[which(l.tmpes == 2)] <- tmpresA 
          #replacing T SNP with .4
  #        tmpes <- strsplit(editstring, "T")
  #        l.tmpes <- sapply(tmpes, length)
  #        tmpres <- tmpes[which(l.tmpes == 2)]
  #        tmpresB <- sapply(tmpres, function(x) x[1])    #before SNP
  #        tmpresA <- sapply(tmpres, function(x) x[2])    #after SNP
  #        snptype[which(l.tmpes == 2)] <- rep("T",length(which(l.tmpes == 2)))
  #        beforeSnp[which(l.tmpes == 2)] <- tmpresB
  #        afterSnp[which(l.tmpes == 2)] <- tmpresA 
  #        strand <- rep(0, dim(df)[1])
  #        df <- df[,c(1,3)]
  #        df <- cbind(df, strand, as.integer(beforeSnp), snptype, as.integer(afterSnp))
  #        names(df) <- c("chr", "location","strand", "beforeSnp", "snptype", "afterSnp")
  #        logos.name <- paste(Targets$Name[i], "logos", sep="") 
  #        ldbl[[i]] <- importToExpData(df, tmpDBname, tablename = logos.name, overwrite = T)
          ldb[[i]] <- aggregateExpData(importToExpData(dfc, tmpDBname, tablename = Targets$Name[i], overwrite = T))
                 
     }
     Try(getNGSannotation())
     Try(myAnn <- get("tmpNGSannotation", affylmGUIenvironment))
     Try(pm <- as.data.frame(myAnn))
     Try(p <- pm[which(pm$strand == 1),])
     Try(m <- pm[which(pm$strand == -1),])
     Try(pm <- rbind(p,m))
     #clean up on the bases of known chr
     Try(pm <- pm[which(pm$space %in% names(chrs.length)),])
     Try(chr <- as.character(pm$space))
     Try(chr[which(chr == "MT")] <- "77")
     Try(chr[which(chr == "X")] <- "88")
     Try(chr[which(chr == "Y")] <- "89")
     Try(chr <- as.numeric(chr))
     Try(annoData <- data.frame(chr=chr, strand=pm$strand, start=pm$start, end=pm$end, feature=as.character(pm$description)))
     Try(rownames(annoData) <- as.character(pm$names))
     Try(assign("GenominatorAnnoData",annoData,affylmGUIenvironment))
     Try(cdb <- list())
     cat("\nStart aggregating data\n ")
     cat("...")
     for(i in 1:length(ldb)){
          Try(cdb[[i]] <- summarizeByAnnotation(ldb[[i]], annoData,what="counts", fxs="TOTAL", bindAnno = T))       
     }
     Try(df.all <- matrix(rep(NA, length(cdb)*dim(cdb[[1]])[1]), ncol = length(cdb)))
     Try(df.all <- as.data.frame(df.all))
     Try(rownames(df.all) <- rownames(cdb[[i]]))
     Try(names(df.all) <- Targets$FileName)
     for(i in 1:length(cdb)){
          Try(df.all[,i] <- cdb[[i]]$counts)       
     }
     cat("\nEnd aggregating data.\n ")
     return(df.all)
 } else if(NGSprimaryMapping == "MicroRazerS"){ 
     Targets <- get("Targets",envir=affylmGUIenvironment)
     Try(ldb <- list())  # for bed files
     #creating a random string of 3 character
     Try(tmpSeed <- ceiling(runif(3,1,25)))
     Try(tmpType <- sample(c(rep(0,3),rep(1,3), rep(2,3)),3))
     Try(tmpDBname <- rep(0,3))
     Try(tmpDBname[which(tmpType == 0)] <- letters[tmpSeed[which(tmpType == 0)]])
     Try(tmpDBname[which(tmpType == 1)] <- tmpSeed[which(tmpType == 1)])
     Try(tmpDBname[which(tmpType == 2)] <- LETTERS[tmpSeed[which(tmpType == 2)]])
     Try(tmpDBname <- paste(tmpDBname, collapse =""))
     Try(assign("Genominator.Available",TRUE,affylmGUIenvironment))
     Try(assign("GenominatorDB",tmpDBname,affylmGUIenvironment))
     chrs.length <- get("chrsLength", affylmGUIenvironment)
     for(i in 1:dim(Targets)[1]){
          count.file <- paste(Targets$FileName[i], ".bed", sep="")
          cat("\nImporting ", count.file, "\n")
          dfc <- read.table(count.file, sep="\t", as.is=T)
          names(dfc) <- c("chr", "strand", "location")
          ldb[[i]] <- aggregateExpData(importToExpData(dfc, tmpDBname, tablename = Targets$Name[i], overwrite = T))
                 
     }
     Try(getNGSannotation())
     Try(myAnn <- get("tmpNGSannotation", affylmGUIenvironment))
     Try(pm <- as.data.frame(myAnn))
     Try(p <- pm[which(pm$strand == 1),])
     Try(m <- pm[which(pm$strand == -1),])
     Try(pm <- rbind(p,m))
     #clean up on the bases of known chr
     Try(pm <- pm[which(pm$space %in% names(chrs.length)),])
     Try(chr <- as.character(pm$space))
     Try(chr[which(chr == "MT")] <- "77")
     Try(chr[which(chr == "X")] <- "88")
     Try(chr[which(chr == "Y")] <- "89")
     Try(chr <- as.numeric(chr))
     Try(annoData <- data.frame(chr=chr, strand=pm$strand, start=pm$start, end=pm$end, feature=as.character(pm$description)))
     Try(rownames(annoData) <- as.character(pm$names))
     Try(assign("GenominatorAnnoData",annoData,affylmGUIenvironment))
     Try(cdb <- list())
     cat("\nStart aggregating data\n ")
     cat("...")
     for(i in 1:length(ldb)){
          Try(cdb[[i]] <- summarizeByAnnotation(ldb[[i]], annoData,what="counts", fxs="TOTAL", bindAnno = T))       
     }
     Try(df.all <- matrix(rep(NA, length(cdb)*dim(cdb[[1]])[1]), ncol = length(cdb)))
     Try(df.all <- as.data.frame(df.all))
     Try(rownames(df.all) <- rownames(cdb[[i]]))
     Try(names(df.all) <- Targets$FileName)
     for(i in 1:length(cdb)){
          Try(df.all[,i] <- cdb[[i]]$counts)       
     }
     cat("\nEnd aggregating data.\n ")
     return(df.all)
 }
}

################################################################################
"showDataset"<-function(){
    Try(tkfocus(.affylmGUIglobals$ttMain))
    if(affylmGUIenvironment$whichArrayPlatform=="AFFY" || affylmGUIenvironment$whichArrayPlatform=="LARGE" || affylmGUIenvironment$whichArrayPlatform=="ILLU" || affylmGUIenvironment$whichArrayPlatform==""){
                if(affylmGUIenvironment$NormalizedAffyData.Available){
                          Try(NormalizedAffyData     <- get("NormalizedAffyData" , envir=affylmGUIenvironment))
                          Try(info.dataset<-paste("Probe sets = ", dim(exprs(NormalizedAffyData))[1],"\n",
                                             "Samples = ", dim(exprs(NormalizedAffyData))[2],"\n",
                                             "Annotation library = ", .annotation(NormalizedAffyData),"\n", sep=""))
                          Try(tkmessageBox(title="Summary of normalized data set",message=info.dataset))
                          #rm(NormalizedAffyData)
                          #gc()
                          #gc()
                } else if(affylmGUIenvironment$RawAffyData.Available){
                          Try(RawAffyData     <- get("RawAffyData" , envir=affylmGUIenvironment))
                          Try(info.dataset<-paste("Size of arrays= ", nrow(RawAffyData), "x", nrow(RawAffyData),"\n",
                                             "Samples = ", length(sampleNames(RawAffyData)),"\n",
                                             "cdf = ", cdfName(RawAffyData),"\n",
                                             "Annotation library = ", .annotation(RawAffyData),"\n", sep=""))
                          Try(tkmessageBox(title="Summary of raw data set",message=info.dataset)) 
                          #rm(RawAffyData)
                          #gc()
                          #gc()
                } else   Try(tkmessageBox(title="summary Data set",message="No data set has been loaded yet")) 
  }
  if(affylmGUIenvironment$whichArrayPlatform=="EXON"){
             if(affylmGUIenvironment$NormalizedAffyData.Available){
                Try(whichLib <- get("whichLib",envir=affylmGUIenvironment))
                Try(NormalizedAffyData     <- get("NormalizedAffyData" , envir=affylmGUIenvironment))
                Try(exonAffyData     <- get("exonAffyData" , envir=affylmGUIenvironment))
                Try(info.dataset<-paste("Genes= ", dim(exprs(NormalizedAffyData))[1],"\n",
                                         "Exons= ", dim(exprs(exonAffyData))[1],"\n",
                                         "Samples= ", dim(exprs(NormalizedAffyData))[2],"\n",
                                         "Annotation library= ", paste("onChannelGUI embedded", paste(as.character(unlist(whichLib)), collapse=" "), "Affymetrix annotation", collapse=" "),"\n", sep=""))
                Try(tkmessageBox(title="Summary of normalized data set",message=info.dataset))

             }else   Try(tkmessageBox(title="summary Data set",message="No data set has been loaded yet"))
  
  }
  if(affylmGUIenvironment$whichArrayPlatform=="GENE"){
                if(affylmGUIenvironment$NormalizedAffyData.Available){
                          Try(NormalizedAffyData     <- get("NormalizedAffyData" , envir=affylmGUIenvironment))
                          Try(info.dataset<-paste("Probe sets = ", dim(exprs(NormalizedAffyData))[1],"\n",
                                             "Samples = ", dim(exprs(NormalizedAffyData))[2],"\n",
                                             "Annotation library = ", .annotation(NormalizedAffyData),"\n", sep=""))
                          Try(tkmessageBox(title="Summary of normalized data set",message=info.dataset))
                } else   Try(tkmessageBox(title="summary Data set",message="No data set has been loaded yet")) 
  }
  if(affylmGUIenvironment$whichArrayPlatform=="NGS"){
               if(affylmGUIenvironment$NormalizedAffyData.Available){
                          Try(NormalizedAffyData     <- get("NormalizedAffyData" , envir=affylmGUIenvironment))
                          Try(info.dataset<-paste("Chromosomes Peaks = ", dim(exprs(NormalizedAffyData))[1],"\n",
                                             "Samples = ", dim(exprs(NormalizedAffyData))[2],"\n",
                                             "Genome release = ", NormalizedAffyData@annotation, "\n", sep=""))
                          Try(tkmessageBox(title="Summary of reformatted NGS data set",message=info.dataset))
                } else   Try(tkmessageBox(title="summary Data set",message="No data set has been loaded yet"))
  }
  Try(tkfocus(.affylmGUIglobals$ttMain))
}
################################################################################ 

ExportNormalizedExpressionValues1 <- function(){
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(limmaDataSetNameText <- get("limmaDataSetNameText", envir = affylmGUIenvironment))
    Try(ArraysLoaded <- get("ArraysLoaded", envir = affylmGUIenvironment))
    Try(if (ArraysLoaded == FALSE) {
        Try(tkmessageBox(title = "Export Normalized Expression Values", 
            message = "Error: No arrays have been loaded.", icon = "error", 
            default = "ok"))
        return()
    })
    Try(NormalizedAffyData.Available <- get("NormalizedAffyData.Available", 
        envir = affylmGUIenvironment))
    Try(if (NormalizedAffyData.Available == FALSE) {
        NormalizeNow()
    })
    Try(NormalizedAffyData.Available <- get("NormalizedAffyData.Available", 
        envir = affylmGUIenvironment))
    Try(if (NormalizedAffyData.Available == FALSE) {
        tkmessageBox(title = "Export Normalized Expression Values", 
            message = "An error or cancellation occured while trying to normalize the data.")
        return()
    })
    Try(NormalizedAffyData <- get("NormalizedAffyData", envir = affylmGUIenvironment))
    Try(NormalizedAffyData.exprs <- exprs(NormalizedAffyData))
    Try(FileName <- tclvalue(tkgetSaveFile(initialfile = paste(limmaDataSetNameText, 
        "_exprs.xls", sep = ""), filetypes = "{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
    Try(if (!nchar(FileName)) 
        return())
    Try(len <- nchar(FileName))
    if (len <= 4) {
        Try(FileName <- paste(FileName, ".xls", sep = ""))
    }
    else if ((substring(FileName, len - 3, len) != ".txt") && 
        (substring(FileName, len - 3, len) != ".xls")) {
        Try(FileName <- paste(FileName, ".xls", sep = ""))
    }
    Try(write.table(NormalizedAffyData.exprs, file = FileName,  sep = "\t", quote = FALSE, col.names = NA))
    #exporting other data
    Try(whichArrayPlatform <- get("whichArrayPlatform", envir = affylmGUIenvironment))
    if(whichArrayPlatform == "EXON"){
                  Try(exonAffyData <- get("exonAffyData", envir = affylmGUIenvironment))
           		    Try(mbVal <- tkmessageBox(title="Exorting exon data",
				    											message="Do you wish to export exon intensity data?",
						    									icon="question",type="yesnocancel",default="yes"
								    						 )#end of tkmessageBox
		              )#end of Try(mbVal..
                  if(tclvalue(mbVal)=="cancel"){Try(return())} else if(tclvalue(mbVal)=="yes"){
                    Try(FileName <- tclvalue(tkgetSaveFile(initialfile = paste(limmaDataSetNameText, 
                         "_exon_exprs.xls", sep = ""), filetypes = "{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
                    Try(if (!nchar(FileName)) 
                              return())
                    Try(len <- nchar(FileName))
                    if (len <= 4) {
                       Try(FileName <- paste(FileName, ".xls", sep = ""))
                    } else if ((substring(FileName, len - 3, len) != ".txt") && 
                          (substring(FileName, len - 3, len) != ".xls")) {
                                Try(FileName <- paste(FileName, ".xls", sep = ""))
                     }
                   Try(write.table(exprs(exonAffyData), file = FileName,  sep = "\t", quote = FALSE, col.names = NA))
                  }
                  Try(spliceIndexData.Available <- get("spliceIndexData.Available", envir = affylmGUIenvironment))
                  if(spliceIndexData.Available){
                        Try(spliceIndexData <- get("spliceIndexData", envir = affylmGUIenvironment))
           		          Try(mbVal <- tkmessageBox(title="Exorting Splice Index data",
				    						      					message="Do you wish to export Splice Index data?",
						    							      		icon="question",type="yesnocancel",default="yes"
								    				      		 )#end of tkmessageBox
		                    )#end of Try(mbVal..
                        if(tclvalue(mbVal)=="cancel"){Try(return())} else if(tclvalue(mbVal)=="yes"){
                          Try(FileName <- tclvalue(tkgetSaveFile(initialfile = paste(limmaDataSetNameText, 
                               "_SI.xls", sep = ""), filetypes = "{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
                          Try(if (!nchar(FileName)) 
                                    return())
                          Try(len <- nchar(FileName))
                          if (len <= 4) {
                             Try(FileName <- paste(FileName, ".xls", sep = ""))
                          } else if ((substring(FileName, len - 3, len) != ".txt") && 
                                (substring(FileName, len - 3, len) != ".xls")) {
                                      Try(FileName <- paste(FileName, ".xls", sep = ""))
                           }
                         Try(write.table(spliceIndexData, file = FileName,  sep = "\t", quote = FALSE, col.names = NA))
                        }
                  }
                  Try(AltSplRP.Available <- get("AltSplRP.e.Available", envir = affylmGUIenvironment))
                  if(AltSplRP.Available){
                        Try(AltSplRP.e.p <- get("AltSplRP.e.p", envir = affylmGUIenvironment))
           		          Try(mbVal <- tkmessageBox(title="Exorting RP alternative splicing results",
				    						      					message="Do you wish to export RP alternative splicing results?",
						    							      		icon="question",type="yesnocancel",default="yes"
								    				      		 )#end of tkmessageBox
		                    )#end of Try(mbVal..
                        if(tclvalue(mbVal)=="cancel"){Try(return())} else if(tclvalue(mbVal)=="yes"){
                          Try(FileName <- tclvalue(tkgetSaveFile(initialfile = paste(limmaDataSetNameText, 
                               "_RP_alt_spl_eval.xls", sep = ""), filetypes = "{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
                          Try(if (!nchar(FileName)) 
                                    return())
                          Try(len <- nchar(FileName))
                          if (len <= 4) {
                             Try(FileName <- paste(FileName, ".xls", sep = ""))
                          } else if ((substring(FileName, len - 3, len) != ".txt") && 
                                (substring(FileName, len - 3, len) != ".xls")) {
                                      Try(FileName <- paste(FileName, ".xls", sep = ""))
                           }
                         Try(write.table(AltSplRP.e.p, file = FileName,  sep = "\t", quote = FALSE, col.names = NA))
                        }
                  }
                  Try(midas.p.Available <- get("midas.p.Available", envir = affylmGUIenvironment))
                  if(midas.p.Available){
                        Try(midas.p <- get("midas.p", envir = affylmGUIenvironment))
           		          Try(mbVal <- tkmessageBox(title="Exorting MiDAS p-values",
				    						      					message="Do you wish to export MiDAS p-values?",
						    							      		icon="question",type="yesnocancel",default="yes"
								    				      		 )#end of tkmessageBox
		                    )#end of Try(mbVal..
                        if(tclvalue(mbVal)=="cancel"){Try(return())} else if(tclvalue(mbVal)=="yes"){
                          Try(FileName <- tclvalue(tkgetSaveFile(initialfile = paste(limmaDataSetNameText, 
                               "_MiDAS_p.xls", sep = ""), filetypes = "{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
                          Try(if (!nchar(FileName)) 
                                    return())
                          Try(len <- nchar(FileName))
                          if (len <= 4) {
                             Try(FileName <- paste(FileName, ".xls", sep = ""))
                          } else if ((substring(FileName, len - 3, len) != ".txt") && 
                                (substring(FileName, len - 3, len) != ".xls")) {
                                      Try(FileName <- paste(FileName, ".xls", sep = ""))
                           }
                         Try(write.table(midas.p, file = FileName,  sep = "\t", quote = FALSE, col.names = F))
                        }
                  }
                  Try(mapping2ensembl.Available <- get("mapping2ensembl.Available", envir = affylmGUIenvironment))
                  if(mapping2ensembl.Available){
                        Try(mapping2ensembl <- get("mapping2ensembl", envir = affylmGUIenvironment))
           		          Try(mbVal <- tkmessageBox(title="Exorting exon-level probesets statistics and expression data with EG exon association",
				    						      					message="Do you wish to export stat/exprs data mapped to Entrez Gene exons?",
						    							      		icon="question",type="yesnocancel",default="yes"
								    				      		 )#end of tkmessageBox
		                    )#end of Try(mbVal..
                        if(tclvalue(mbVal)=="cancel"){Try(return())} else if(tclvalue(mbVal)=="yes"){
                          Try(FileName <- tclvalue(tkgetSaveFile(initialfile = paste(limmaDataSetNameText, 
                               "_mapping2ensembl.xls", sep = ""), filetypes = "{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
                          Try(if (!nchar(FileName)) 
                                    return())
                          Try(len <- nchar(FileName))
                          if (len <= 4) {
                             Try(FileName <- paste(FileName, ".xls", sep = ""))
                          } else if ((substring(FileName, len - 3, len) != ".txt") && 
                                (substring(FileName, len - 3, len) != ".xls")) {
                                      Try(FileName <- paste(FileName, ".xls", sep = ""))
                           }
                         Try(write.table(mapping2ensembl, file = FileName,  sep = "\t", quote = FALSE, col.names = NA))
                        }
                  }
                  Try(exonsSpecific2as.Available <- get("exonsSpecific2as.Available", envir = affylmGUIenvironment))
                  if(exonsSpecific2as.Available){
                        Try(exonsSpecific <- get("exonsSpecific2as", envir = affylmGUIenvironment))
           		          Try(mbVal <- tkmessageBox(title="Exorting the structure of mRNA isoforms",
				    						      					message="Do you wish to export structure of mRNA isoforms?",
						    							      		icon="question",type="yesnocancel",default="yes"
								    				      		 )#end of tkmessageBox
		                    )#end of Try(mbVal..
                        if(tclvalue(mbVal)=="cancel"){Try(return())} else if(tclvalue(mbVal)=="yes"){
                          Try(FileName <- tclvalue(tkgetSaveFile(initialfile = paste(limmaDataSetNameText, 
                               "_exonsSpecific2as.xls", sep = ""), filetypes = "{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
                          Try(if (!nchar(FileName)) 
                                    return())
                          Try(len <- nchar(FileName))
                          if (len <= 4) {
                             Try(FileName <- paste(FileName, ".xls", sep = ""))
                          } else if ((substring(FileName, len - 3, len) != ".txt") && 
                                (substring(FileName, len - 3, len) != ".xls")) {
                                      Try(FileName <- paste(FileName, ".xls", sep = ""))
                           }
                         for( i in 1: length(exonsSpecific)){  
                                  Try(write.table(exonsSpecific[i], file = FileName,  sep = "\t", quote = FALSE, row.names= T, append=T))
                         }
                        }
                  }

    }
    Try(tkfocus(.affylmGUIglobals$ttMain))
}
################################################################################
"targetWidget" <- function () {
    Try(tkfocus(.affylmGUIglobals$ttMain))
   # require(tkWidgets) || stop("library tkWidgets could not be found !")
    Try(widgetfiles <- fileBrowser(textToShow = "Choose CEL files", 
                         testFun = hasSuffix("[cC][eE][lL]")))
    Try(celfile.path <- getwd())
    Try(if (length(widgetfiles) == 0) 
        stop("No cel filennames specified") else{

        sampleNames <- sub("^/?([^/]*/)*", "", widgetfiles, extended = TRUE)
        myNames <- paste(rep("n", length(sampleNames)),seq(1, length(sampleNames)), sep="")
        pd <- read.phenoData(sampleNames = sampleNames, widget = TRUE)
        pd <- as.data.frame(pData(pd))
        pd <- cbind(rownames(pd), pd)
        
        if(dim(pd)[2]>2){
                targets <- pd[, 2:dim(pd)[2]]
                targets <- apply(targets,1,function(x)paste(x,collapse="_"))
                pd <- as.data.frame(cbind(myNames, rownames(pd), as.character(targets))) 
        } else{
                pd <-as.data.frame(cbind(myNames, pd))
        }
        names(pd) <- c("Name", "FileName", "Target")
        write.table(pd, "target.txt", sep="\t", row.names=F)
        
    })
    Try(tkmessageBox(title="Make an Affy Target file",message=paste("Target file is available in your working directory")))  
    Try(tkfocus(.affylmGUIglobals$ttMain))
 
}
##########################################################################




###########################################################################
 SaveAsLimmaFile <- function()
{
	Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
	Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
	Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
	Try(tempLimmaFileName <- tclvalue(tkgetSaveFile(initialfile=LimmaFileName,filetypes="{{Limma Files} {.lma}} {{All files} *}")))
	if(!nchar(tempLimmaFileName))
	{
		try(tkfocus(.affylmGUIglobals$ttMain),silent=TRUE)
		return()
	}
	len <- nchar(tempLimmaFileName)
	if(len<=4)
			tempLimmaFileName <- paste(tempLimmaFileName,".lma",sep="")
	else if(substring(tempLimmaFileName,len-3,len)!=".lma")
				tempLimmaFileName <- paste(tempLimmaFileName,".lma",sep="")
	Try(LimmaFileName <- tempLimmaFileName)
	Try(assign("LimmaFileName",LimmaFileName,affylmGUIenvironment))

#	Try(recentFilesFileName <- system.file("etc/recent-files.txt",package="oneChannelGUI"))
#	Try(recentFiles <- readLines(recentFilesFileName))

#	Try(recentFiles <- gsub("\\\\","/",recentFiles))

	# Remove any blank lines:
#	Try(blanks <- grep("^[ \t\n]*$",recentFiles))
#	Try(if(length(blanks)>0)
#		recentFiles <- recentFiles[-blanks])
#	Try(numRecentFiles <- length(recentFiles))

#	Try(if(length(grep(LimmaFileName,recentFiles))==0)
#		recentFiles <- c(LimmaFileName,recentFiles))
#	Try(if(length(recentFiles)>4)
#		recentFiles <- recentFiles[1:4])
#	try(writeLines(con=recentFilesFileName,recentFiles),TRUE)
#	Try(numRecentFiles <- length(recentFiles))

#	Try(if(numRecentFiles>0)
#	{
#		Try(fileMenu <- .affylmGUIglobals$menus$fileMenu)
#		Try(workingDirIndex <- as.numeric(tclvalue(tkindex(.affylmGUIglobals$menus$fileMenu,"affylmGUI: Working Directory"))))
#		Try(exitIndex <- as.numeric(tclvalue(tkindex(.affylmGUIglobals$menus$fileMenu,"affylmGUI: Exit"))))
#		Try(if(exitIndex==workingDirIndex+2)
#			Try(numRecentFilesInMenu <- 0)
#		else
#		{
#			Try(numRecentFilesInMenu <- exitIndex - workingDirIndex - 3)
#			Try(for (i in (1:(numRecentFilesInMenu+1)))
#				Try(tkdelete(fileMenu,workingDirIndex+2)))
#		})
#		Try(tkinsert(fileMenu,workingDirIndex+1,"separator"))

#		Try(for (i in (numRecentFiles:1))
#		{
#			Try(label <- recentFiles[i])
#			Try(fileNameOnly <- strsplit(label,"/")[[1]])
#			Try(fileNameOnly <- fileNameOnly[length(fileNameOnly)])
#			Try(if(nchar(recentFiles[i])>60)
#					label <- paste(".../",fileNameOnly))
#			Try(eval(parse(text=paste("assign(\".OpenALimmaFile_",i,"\",function() OpenALimmaFile(\"",recentFiles[i],"\"),.GlobalEnv)",sep=""))))
#			Try(if(.Platform$OS.type=="windows")
#				Try(tkinsert(fileMenu,workingDirIndex+2,"command",label=paste(i,". ",gsub("/","\\\\",label),sep=""),
#					command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))))
#			else
#				Try(tkinsert(fileMenu,workingDirIndex+2,"command",label=paste(i,". ",label,sep=""),
#					command=eval(parse(text=paste(".OpenALimmaFile_",i,sep=""))))))
#
#		})
#	})

	# .affylmGUIglobals$ttMain may have been destroyed
	e <- try(tkfocus(.affylmGUIglobals$ttMain),silent=TRUE)
	if(!inherits(e, "try-error"))
		Try(if(.Platform$OS.type=="windows")
			Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",gsub("/","\\\\",LimmaFileName))))
		else
			Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",LimmaFileName))))

#	try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"),silent=TRUE)
	assign("PsetData.Available",FALSE,affylmGUIenvironment)#Always assign this to FALSE. Will always recalculate it in the Plot menu functions
	Try(save(list = ls(envir=affylmGUIenvironment), file=LimmaFileName, envir=affylmGUIenvironment))
	try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"),silent=TRUE)
	try(tkfocus(.affylmGUIglobals$ttMain),silent=TRUE)
}
################################################################################
#NGS
#this fuction uses the mature data files provided by http://web.bioinformatics.cicbiogune.es/microRNA/miRanalyser.php
"OpenmiRanalyserfiles" <- function()
{
	Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttExonandTargets))
	Try(tkgrab.set(ttExonandTargets))
	Try(tkfocus(ttExonandTargets))
	Try(tkwm.title(ttExonandTargets,"Targets file"))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

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

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

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

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

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

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

	if(Abort==1)
				return(0)
  
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(Targets <- get("Targets",affylmGUIenvironment))
	Try(slides <- Targets$FileName)
	
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  #NGS reads number and reformatting Target in Targets #######################
  Try(tmpTarget <- Targets$Target)
  Try(tmpTarget <- strsplit(tmpTarget, "_"))
  Try(newTarget <- sapply(tmpTarget, function(x)x[1]))
  Try(Targets$Target <- newTarget)
  Try(rownames(Targets) <- NULL)
  Try(assign("Targets",Targets,envir=affylmGUIenvironment))
  Try(totalReads <- sapply(tmpTarget, function(x)x[2]))
  Try(mappedReads <- sapply(tmpTarget, function(x)x[3]))
  Try(assign("totalReads", as.numeric(totalReads),envir=affylmGUIenvironment))
  Try(assign("mappedReads", as.numeric(mappedReads),envir=affylmGUIenvironment))
  
  #Creating the expression set
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  data.list <- list()
  for(i in Targets$FileName){
     tmp <- read.table(i, sep="\t", header=F, as.is=T, skip=14, row.names=1, fill=T)
     miRNA.names <- rownames(tmp)
     miRNA.names <- sub(" ", "",  miRNA.names)
     tmp <- as.numeric(unlist(tmp[,2])) #all counts with and without mismatches
     names(tmp) <- miRNA.names
     data.list[[i]] <- tmp
  }
  #building the data frame
  miRNA.names <- sapply(data.list, function(x) names(x))
  miRNA.unique <- unique(as.character(unlist(miRNA.names)))
  
  #creating matrix to be filled
  mat.miRNA <- matrix(rep(0,length(miRNA.unique) * length(data.list)), nrow=length(miRNA.unique))
  dimnames(mat.miRNA) <- list(miRNA.unique, names(data.list))
  #assigning values
  .fillMat <- function(x, y){
    for(i in 1:dim(x)[1]){
      for(j in 1:length(y)){
        if(length(which(names(y[[j]]) == dimnames(x)[[1]][i]))>0)
             x[i,j]   <- as.numeric(y[[j]][which(names(y[[j]]) == dimnames(x)[[1]][i])])
     }
   }
   return(x)
  }
  
  mat.miRNA <- .fillMat(mat.miRNA, data.list)
  tmp.genome <- NULL
  tmp.genome[1] <- length(grep("hsa", rownames(mat.miRNA)))
  tmp.genome[2] <- length(grep("mmu", rownames(mat.miRNA)))
  tmp.genome[3] <- length(grep("rno", rownames(mat.miRNA)))
  my.genome <- which(tmp.genome == max(tmp.genome)) 
  if(my.genome == 1){
      genome.version = "hg19"
      Try(chrs <- seq(1, 25))
      Try(chrs.names <- c(chrs[1:22], "X", "Y", "MT"))
      Try(names(chrs) <- chrs.names)
      #require(BSgenome.Hsapiens.UCSC.hg19) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Hsapiens.UCSC.hg19") ; require(BSgenome.Hsapiens.UCSC.hg19)}
      Try(data("chrLength",package="oneChannelGUI"))
      Try(chrLength <- get("chrLength",envir=.GlobalEnv))
      Try(chrs.length <- chrLength$hg19)
      Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
  }
  if(my.genome == 2){
       genome.version = "mm8"
       Try(chrs <- seq(1, 22))
       Try(chrs.names <- c(chrs[1:19], "X", "Y", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Mmusculus.UCSC.mm9) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Mmusculus.UCSC.mm9") ; require(BSgenome.Mmusculus.UCSC.mm9)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$mm9)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected M. musculus genome UCSC release mm9.",type="ok", icon="info"))
  }
  if(my.genome == 3){
       genome.version = "rn4"
       Try(chrs <- seq(1, 21))
       Try(chrs.names <- c(chrs[1:19], "X", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Rnorvegicus.UCSC.rn4) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Rnorvegicus.UCSC.rn4") ; require(BSgenome.Rnorvegicus.UCSC.rn4)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$rn4)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected R. norvegicus genome UCSC release rn4.",type="ok", icon="info"))
  }
    
  getNGSannotation()
  chrs.length <- get("chrsLength", affylmGUIenvironment)
  myAnn <- get("tmpNGSannotation", affylmGUIenvironment)
  Try(pm <- as.data.frame(myAnn))
  Try(p <- pm[which(pm$strand == 1),])
  Try(m <- pm[which(pm$strand == -1),])
  Try(pm <- rbind(p,m))
  Try(pm <- pm[which(pm$space %in% names(chrs.length)),])
  Try(chr <- as.character(pm$space))
  Try(annoData <- data.frame(chr=chr, strand=pm$strand, start=pm$start, end=pm$end, feature=as.character(pm$description)))
  Try(rownames(annoData) <- as.character(pm$names))
  description <- as.character(annoData$feature)
  annoData <- annoData[grep("miRBase", description),]
  description <- as.character(annoData$feature)
  description <- strsplit(description, " ")
  description <- sapply(description, function(x) x[1])
  if(my.genome == 1){
#        description <- paste("hsa-miR-", description, sep="")
        annoData$feature <- description
  }
  if(my.genome == 2){
#        description <- paste("mmu-miR-", description, sep="")
        annoData$feature <- description
 }
  if(my.genome == 3){
#        description <- paste("rno-miR-", description, sep="")
        annoData$feature <- description
  }
  #detecting and removing duplicated miRNA
  duplicated <- which(annoData$feature %in% annoData$feature[which(duplicated(annoData$feature))])
  cat("\nThe following miRNAs were removed since present in duplicated positions")
  cat("\n")
  print(annoData[duplicated,])
  cat("\n")
  annoData <- annoData[setdiff(seq(1,dim(annoData)[1]), duplicated),]
  #

  annoData <- annoData[which(annoData$feature %in% dimnames(mat.miRNA)[[1]]),]
  annoData <- annoData[order(annoData$feature),]
  mat.miRNA <- mat.miRNA[which(dimnames(mat.miRNA)[[1]] %in% annoData$feature),]
  mat.miRNA <- mat.miRNA[order(dimnames(mat.miRNA)[[1]]),]
  mat.rnames <- apply(annoData, 1, function(x) paste("chr:",x[1],"strand:",x[2], "start:", x[3], "end:", x[4], "description:", x[5] , sep=" "))
  mat.rnames <- paste(names(mat.rnames), mat.rnames)
  
  if(identical(dimnames(mat.miRNA)[[1]], annoData$feature)){
       dimnames(mat.miRNA)[[1]] <-  mat.rnames
  }else{
     Try(tkmessageBox(title="Internal error",message="Internal error 12345. Please contact oneChannelGUI maintainer",type="ok", icon="error"))
     return()
  }
  
  Try(NormalizedAffyData <- new("ExpressionSet", assayData = assayDataNew(exprs=mat.miRNA) , phenoData=tmp1.pd, annotation=genome.version))
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
  Try(assign("NGS.Available",TRUE,affylmGUIenvironment))
	Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="NGS counts from miRanalyser",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status" ,text="NGS data",font=.affylmGUIglobals$affylmGUIfontTree))

	Try(if("Name" %in% colnames(Targets))
	SlideNamesVec <- Targets$Name)
	Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
  Try(tkfocus(.affylmGUIglobals$ttMain))
 	Try(ReturnVal <- GetlimmaDataSetName())
	if(ReturnVal==0) return(0)
	return(1)
}
################################################################################
#NGS
#this fuction uses the mature data files provided by http://miRExpress.mbc.nctu.edu.tw
"OpenmiRExpress" <- function()
{
	Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttExonandTargets))
	Try(tkgrab.set(ttExonandTargets))
	Try(tkfocus(ttExonandTargets))
	Try(tkwm.title(ttExonandTargets,"Targets file"))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

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

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

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

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

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

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

	if(Abort==1)
				return(0)
  
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(Targets <- get("Targets",affylmGUIenvironment))
	Try(slides <- Targets$FileName)
	
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  #NGS reads number and reformatting Target in Targets #######################
  Try(tmpTarget <- Targets$Target)
  Try(tmpTarget <- strsplit(tmpTarget, "_"))
  Try(newTarget <- sapply(tmpTarget, function(x)x[1]))
  Try(Targets$Target <- newTarget)
  Try(rownames(Targets) <- NULL)
  Try(assign("Targets",Targets,envir=affylmGUIenvironment))
  Try(totalReads <- sapply(tmpTarget, function(x)x[2]))
  Try(mappedReads <- sapply(tmpTarget, function(x)x[3]))
  Try(assign("totalReads", as.numeric(totalReads),envir=affylmGUIenvironment))
  Try(assign("mappedReads", as.numeric(mappedReads),envir=affylmGUIenvironment))
  
  #Creating the expression set
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  data.list <- list()
  for(i in Targets$FileName){
     tmp.genome <- NULL
     tmpf <- read.table(i, sep="\t", header=F, as.is=T)
     tmpf <- as.character(unlist(tmpf))
     
     tmp.genome[1] <- length(grep("hsa", tmpf))
     tmp.genome[2] <- length(grep("mmu", tmpf))
     tmp.genome[3] <- length(grep("rno", tmpf))
     my.genome <- which(tmp.genome == max(tmp.genome))
     if(my.genome == 1) miRNA.pos <- grep("^hsa", tmpf)
     if(my.genome == 2) miRNA.pos <- grep("mmu", tmpf)
     if(my.genome == 3) miRNA.pos <- grep("rno", tmpf)
     tmp <- NULL
     tmp.name <- NULL                                              
     for(j in 1:(length(miRNA.pos) -1)){
        mymir <- NULL
        if(((miRNA.pos[j+1]-1) - (miRNA.pos[j]+3)) > 0){
           mymir <- tmpf[miRNA.pos[j]:(miRNA.pos[j+1]-1)]
           tmp.name[j] <- mymir[1]
           mymir <- strsplit(mymir[4:(length(mymir) - 1)], " ")
           mymir <- sapply(mymir, function(x) x[length(x)])
           mymir <- as.numeric(mymir)
           tmp[j] <- sum(mymir)
        }
     }
     names(tmp) <- tmp.name
     tmp <- tmp[!is.na(tmp)]
     data.list[[i]] <- tmp
  }
  #building the data frame
  miRNA.names <- sapply(data.list, function(x) names(x))
  miRNA.unique <- unique(as.character(unlist(miRNA.names)))
  #creating matrix to be filled
  mat.miRNA <- matrix(rep(0,length(miRNA.unique) * length(data.list)), nrow=length(miRNA.unique))
  dimnames(mat.miRNA) <- list(miRNA.unique, names(data.list))
  #assigning values
  #assigning values
 .fillMat <- function(x, y){
    for(i in 1:dim(x)[1]){
      for(j in 1:length(y)){
        if(length(which(names(y[[j]]) == dimnames(x)[[1]][i]))>0)
             x[i,j]   <- as.numeric(y[[j]][which(names(y[[j]]) == dimnames(x)[[1]][i])])
     }
   }
   return(x)
  }
  
  mat.miRNA <- .fillMat(mat.miRNA, data.list)
  tmp.genome <- NULL
  tmp.genome[1] <- length(grep("hsa", rownames(mat.miRNA)))
  tmp.genome[2] <- length(grep("mmu", rownames(mat.miRNA)))
  tmp.genome[3] <- length(grep("rno", rownames(mat.miRNA)))
  my.genome <- which(tmp.genome == max(tmp.genome)) 
  if(my.genome == 1){
      genome.version = "hg19"
      Try(chrs <- seq(1, 25))
      Try(chrs.names <- c(chrs[1:22], "X", "Y", "MT"))
      Try(names(chrs) <- chrs.names)
      #require(BSgenome.Hsapiens.UCSC.hg19) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Hsapiens.UCSC.hg19") ; require(BSgenome.Hsapiens.UCSC.hg19)}
      Try(data("chrLength",package="oneChannelGUI"))
      Try(chrLength <- get("chrLength",envir=.GlobalEnv))
      Try(chrs.length <- chrLength$hg19)
      Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
  }
  if(my.genome == 2){
       genome.version = "mm8"
       Try(chrs <- seq(1, 22))
       Try(chrs.names <- c(chrs[1:19], "X", "Y", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Mmusculus.UCSC.mm9) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Mmusculus.UCSC.mm9") ; require(BSgenome.Mmusculus.UCSC.mm9)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$mm9)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected M. musculus genome UCSC release mm9.",type="ok", icon="info"))
  }
  if(my.genome == 3){
       genome.version = "rn4"
       Try(chrs <- seq(1, 21))
       Try(chrs.names <- c(chrs[1:19], "X", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Rnorvegicus.UCSC.rn4) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Rnorvegicus.UCSC.rn4") ; require(BSgenome.Rnorvegicus.UCSC.rn4)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$rn4)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected R. norvegicus genome UCSC release rn4.",type="ok", icon="info"))
  }
    
  getNGSannotation()
  chrs.length <- get("chrsLength", affylmGUIenvironment)
  myAnn <- get("tmpNGSannotation", affylmGUIenvironment)
  Try(pm <- as.data.frame(myAnn))
  Try(p <- pm[which(pm$strand == 1),])
  Try(m <- pm[which(pm$strand == -1),])
  Try(pm <- rbind(p,m))
  Try(pm <- pm[which(pm$space %in% names(chrs.length)),])
  Try(chr <- as.character(pm$space))
  Try(annoData <- data.frame(chr=chr, strand=pm$strand, start=pm$start, end=pm$end, feature=as.character(pm$description)))
  Try(rownames(annoData) <- as.character(pm$names))
  description <- as.character(annoData$feature)
  annoData <- annoData[grep("miRBase", description),]
  description <- as.character(annoData$feature)
  description <- strsplit(description, " ")
  description <- sapply(description, function(x) x[1])
  if(my.genome == 1){
#        description <- paste("hsa-miR-", description, sep="")
        annoData$feature <- description
  }
  if(my.genome == 2){
#        description <- paste("mmu-miR-", description, sep="")
        annoData$feature <- description
 }
  if(my.genome == 3){
#        description <- paste("rno-miR-", description, sep="")
        annoData$feature <- description
  }
  #detecting and removing duplicated miRNA
  duplicated <- which(annoData$feature %in% annoData$feature[which(duplicated(annoData$feature))])
  cat("\nThe following miRNAs were removed since present in duplicated positions\n")
  print(annoData[duplicated,])
  cat("\n")
  annoData <- annoData[setdiff(seq(1,dim(annoData)[1]), duplicated),]
  #

  annoData <- annoData[which(annoData$feature %in% dimnames(mat.miRNA)[[1]]),]
  annoData <- annoData[order(annoData$feature),]
  mat.miRNA <- mat.miRNA[which(dimnames(mat.miRNA)[[1]] %in% annoData$feature),]
  mat.miRNA <- mat.miRNA[order(dimnames(mat.miRNA)[[1]]),]
  mat.rnames <- apply(annoData, 1, function(x) paste("chr:",x[1],"strand:",x[2], "start:", x[3], "end:", x[4], "description:", x[5] , sep=" "))
  mat.rnames <- paste(names(mat.rnames), mat.rnames)
  
  if(identical(dimnames(mat.miRNA)[[1]], annoData$feature)){
       dimnames(mat.miRNA)[[1]] <-  mat.rnames
  }else{
     Try(tkmessageBox(title="Internal error",message="Internal error 12345. Please contact oneChannelGUI maintainer",type="ok", icon="error"))
     return()
  }
  
  Try(NormalizedAffyData <- new("ExpressionSet", assayData = assayDataNew(exprs=mat.miRNA) , phenoData=tmp1.pd, annotation=genome.version))
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
  Try(assign("NGS.Available",TRUE,affylmGUIenvironment))
	Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="NGS counts from miRanalyser",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status" ,text="NGS data",font=.affylmGUIglobals$affylmGUIfontTree))

	Try(if("Name" %in% colnames(Targets))
	SlideNamesVec <- Targets$Name)
	Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
  Try(tkfocus(.affylmGUIglobals$ttMain))
 	Try(ReturnVal <- GetlimmaDataSetName())
	if(ReturnVal==0) return(0)
	return(1)
}

################################################################################
#NGS
#this fuction uses the mature data files provided by http://srna-tools.cmp.uea.ac.uk/animal/cgi-bin/srna-tools.cgi
"OpenmiRProfiles" <- function()
{
	Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttExonandTargets))
	Try(tkgrab.set(ttExonandTargets))
	Try(tkfocus(ttExonandTargets))
	Try(tkwm.title(ttExonandTargets,"Targets file"))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

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

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

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

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

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

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

	if(Abort==1)
				return(0)
  
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(Targets <- get("Targets",affylmGUIenvironment))
	Try(slides <- Targets$FileName)
	
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  #NGS reads number and reformatting Target in Targets #######################
  Try(tmpTarget <- Targets$Target)
  Try(tmpTarget <- strsplit(tmpTarget, "_"))
  Try(newTarget <- sapply(tmpTarget, function(x)x[1]))
  Try(Targets$Target <- newTarget)
  Try(rownames(Targets) <- NULL)
  Try(assign("Targets",Targets,envir=affylmGUIenvironment))
  Try(totalReads <- sapply(tmpTarget, function(x)x[2]))
  Try(mappedReads <- sapply(tmpTarget, function(x)x[3]))
  Try(assign("totalReads", as.numeric(totalReads),envir=affylmGUIenvironment))
  Try(assign("mappedReads", as.numeric(mappedReads),envir=affylmGUIenvironment))
  
  #Creating the expression set
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  data.list <- list()
  for(i in Targets$FileName){
    tmp <- read.table(i, sep="\t", header=F, as.is=T, skip=16, fill=T)
    tmp <- as.character(unlist(tmp))
    tmp <- strsplit(tmp, ",")
    tmp.name <- sapply(tmp, function(x) x[1])
    tmp.counts <- sapply(tmp, function(x) x[2])
    tmp.counts <- as.numeric(tmp.counts)
    names(tmp.counts) <- tmp.name
    data.list[[i]] <- tmp.counts
  }
  #building the data frame
  miRNA.names <- sapply(data.list, function(x) names(x))
  miRNA.unique <- unique(as.character(unlist(miRNA.names)))
  
  #creating matrix to be filled
  mat.miRNA <- matrix(rep(0,length(miRNA.unique) * length(data.list)), nrow=length(miRNA.unique))
  dimnames(mat.miRNA) <- list(miRNA.unique, names(data.list))
  #assigning values
  .fillMat <- function(x, y){
    for(i in 1:dim(x)[1]){
      for(j in 1:length(y)){
        if(length(which(names(y[[j]]) == dimnames(x)[[1]][i]))>0)
             x[i,j]   <- as.numeric(y[[j]][which(names(y[[j]]) == dimnames(x)[[1]][i])])
     }
   }
   return(x)
  }
  
  mat.miRNA <- .fillMat(mat.miRNA, data.list)
  #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(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.5))
	Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.25))
  Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.1))
	Try(tkgrid.configure(rbIQR.5,rbIQR.25,rbIQR.1,columnspan=2,sticky="w"))
	Try(tkgrid(tklabel(ttGetOrganism,text="    "),tklabel(ttGetOrganism,text="    ")))
  Try(ReturnVal <- "")
  Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGetOrganism));Try(tkdestroy(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain))})
  Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGetOrganismTcl));Try(tkgrab.release(ttGetOrganism));Try(tkdestroy(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain))})
  Try(OK.but     <- tkbutton(ttGetOrganism,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <- tkbutton(ttGetOrganism,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

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

  Try(tkbind(ttGetOrganism,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkbind(OK.but, "<Return>",onOK))
  Try(tkbind(Cancel.but, "<Return>",onCancel))      
  Try(tkwait.window(ttGetOrganism))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  
  if(ReturnVal == ""){
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
       Try(return())
  } else if (ReturnVal == "hs"){
       Try(genome <- "Hsapiens")
       Try(genome.version <- "hg19")
       Try(chrs <- seq(1, 25))
       Try(chrs.names <- c(chrs[1:22], "X", "Y", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Hsapiens.UCSC.hg19) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Hsapiens.UCSC.hg19") ; require(BSgenome.Hsapiens.UCSC.hg19)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$hg19)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected H. sapiens genome UCSC release hg19.",type="ok", icon="info"))
  } else if (ReturnVal == "mm"){
       Try(genome <- "Mmusculus")
       Try(genome.version <- "mm9")
       Try(chrs <- seq(1, 22))
       Try(chrs.names <- c(chrs[1:19], "X", "Y", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Mmusculus.UCSC.mm9) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Mmusculus.UCSC.mm9") ; require(BSgenome.Mmusculus.UCSC.mm9)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$mm9)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected M. musculus genome UCSC release mm9.",type="ok", icon="info"))
  
  } else if (ReturnVal == "rn"){
       Try(genome <- "Rnorvegicus")
       Try(genome.version <- "rn4")
       Try(chrs <- seq(1, 21))
       Try(chrs.names <- c(chrs[1:19], "X", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Rnorvegicus.UCSC.rn4) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Rnorvegicus.UCSC.rn4") ; require(BSgenome.Rnorvegicus.UCSC.rn4)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$rn4)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected R. norvegicus genome UCSC release rn4.",type="ok", icon="info"))
  }
    
  getNGSannotation()
  chrs.length <- get("chrsLength", affylmGUIenvironment)
  myAnn <- get("tmpNGSannotation", affylmGUIenvironment)
  Try(pm <- as.data.frame(myAnn))
  Try(p <- pm[which(pm$strand == 1),])
  Try(m <- pm[which(pm$strand == -1),])
  Try(pm <- rbind(p,m))
  Try(pm <- pm[which(pm$space %in% names(chrs.length)),])
  Try(chr <- as.character(pm$space))
  Try(annoData <- data.frame(chr=chr, strand=pm$strand, start=pm$start, end=pm$end, feature=as.character(pm$description)))
  Try(rownames(annoData) <- as.character(pm$names))
  description <- as.character(annoData$feature)
  annoData <- annoData[grep("miRBase", description),]
  description <- as.character(annoData$feature)
  description <- strsplit(description, " ")
  description <- sapply(description, function(x) x[1])
  annoData$feature <- description
  #detecting and removing duplicated miRNA
  duplicated <- which(annoData$feature %in% annoData$feature[which(duplicated(annoData$feature))])
  cat("\nThe following miRNAs were removed since present in duplicated positions\n")
  print(annoData[duplicated,])
  cat("\n")
  annoData <- annoData[setdiff(seq(1,dim(annoData)[1]), duplicated),]
  #

  annoData <- annoData[which(annoData$feature %in% dimnames(mat.miRNA)[[1]]),]
  annoData <- annoData[order(annoData$feature),]
  mat.miRNA <- mat.miRNA[which(dimnames(mat.miRNA)[[1]] %in% annoData$feature),]
  mat.miRNA <- mat.miRNA[order(dimnames(mat.miRNA)[[1]]),]
  mat.rnames <- apply(annoData, 1, function(x) paste("chr:",x[1],"strand:",x[2], "start:", x[3], "end:", x[4], "description:", x[5] , sep=" "))
  mat.rnames <- paste(names(mat.rnames), mat.rnames)
  
  if(identical(dimnames(mat.miRNA)[[1]], annoData$feature)){
       dimnames(mat.miRNA)[[1]] <-  mat.rnames
  } else{
     Try(tkmessageBox(title="Internal error",message="Internal error 12345. Please contact oneChannelGUI maintainer",type="ok", icon="error"))
     return()
  }
  Try(NormalizedAffyData <- new("ExpressionSet", assayData = assayDataNew(exprs=mat.miRNA) , phenoData=tmp1.pd, annotation=genome.version))
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
  Try(assign("NGS.Available",TRUE,affylmGUIenvironment))
	Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="NGS counts from miRanalyser",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status" ,text="NGS data",font=.affylmGUIglobals$affylmGUIfontTree))

	Try(if("Name" %in% colnames(Targets))
	SlideNamesVec <- Targets$Name)
	Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
  Try(tkfocus(.affylmGUIglobals$ttMain))
 	Try(ReturnVal <- GetlimmaDataSetName())
	if(ReturnVal==0) return(0)
	return(1)
}
################################################################################
#NGS
#this fuction uses the output file provided by mapping reads over mirBase precursors in fasta format using shrimp
#data are reformatted by  shrimpENSEMBL2genominator.mirbase.pl script
"OpenmiRShrimp" <- function()
{
	Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttExonandTargets))
	Try(tkgrab.set(ttExonandTargets))
	Try(tkfocus(ttExonandTargets))
	Try(tkwm.title(ttExonandTargets,"Targets file"))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

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

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

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

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

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

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

	if(Abort==1)
				return(0)
  
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(Targets <- get("Targets",affylmGUIenvironment))
	Try(slides <- Targets$FileName)
	
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  #NGS reads number and reformatting Target in Targets #######################
  Try(tmpTarget <- Targets$Target)
  Try(tmpTarget <- strsplit(tmpTarget, "_"))
  Try(newTarget <- sapply(tmpTarget, function(x)x[1]))
  Try(Targets$Target <- newTarget)
  Try(rownames(Targets) <- NULL)
  Try(assign("Targets",Targets,envir=affylmGUIenvironment))
  Try(totalReads <- sapply(tmpTarget, function(x)x[2]))
  Try(mappedReads <- sapply(tmpTarget, function(x)x[3]))
  Try(assign("totalReads", as.numeric(totalReads),envir=affylmGUIenvironment))
  Try(assign("mappedReads", as.numeric(mappedReads),envir=affylmGUIenvironment))
 
  #Creating the expression set
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(tmpFileNames <- paste(Targets$FileName, ".shrink", sep=""))
  Try(Targets$FileName <- tmpFileNames)
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))

  data.list <- list()
  .fillVec <- function(x, y){
    for(i in 1:length(x)){
             x[i]   <- length(which(y == names(x)[i]))
    }
    return(x)
  }
 
  for(i in Targets$FileName){
     Try(cat("\nProcessing ",i)) 
     Try(tmp <- read.table(i, sep="\t", header=F, as.is=T))
#     #removing multiple errors x or more than one snp
#     error removals is done at the level of perl preprocessing
#     Try(snps.n <- sapply(tmp[,2], function(x){length(unlist(gregexpr('[A,C,G,T]', x)))})) #multiple snp
#     Try(cat("\n Total reads ", dim(tmp)[1]))
#     Try(tmp <- tmp[which(snps.n <= 2 ),])
#     Try(cat(" left after removal of multiple SNPs ", dim(tmp)[1]))
#     Try(snps.n <- sapply(tmp[,2], function(x){length(unlist(gregexpr('x', x)))})) #error accepted
#     Try(tmp <- tmp[which(snps.n == 1 ),]) 
#     Try(cat(" left after errors removal ", dim(tmp)[1], "\n"))
     Try(miRNA.unique <- unique(as.character(unlist(tmp[,1]))))
     Try(vec.miRNA <- rep(0,length(miRNA.unique)))
     Try(names(vec.miRNA) <- miRNA.unique)
     Try(vec.miRNA <- .fillVec(vec.miRNA, tmp[,1]))
     Try(cat("\nTotal microRNAs detected in ",i, ": ", length(vec.miRNA)))
     Try(data.list[[i]] <- vec.miRNA)
  }
  #building the data frame
  Try(miRNA.names <- sapply(data.list, function(x) names(x)))
  Try(miRNA.unique <- unique(as.character(unlist(miRNA.names))))
  Try(cat("\nDetected ", length(miRNA.unique), "microRNAs\n"))
  #creating matrix to be filled
  Try(mat.miRNA <- matrix(rep(0,length(miRNA.unique) * length(data.list)), nrow=length(miRNA.unique)))
  Try(dimnames(mat.miRNA) <- list(miRNA.unique, names(data.list)))
  #assigning values
  .fillMat <- function(x, y){
    for(i in 1:dim(x)[1]){
      for(j in 1:length(y)){
          if(length(y[[j]][which(names(y[[j]]) == dimnames(x)[[1]][i])]) > 0)
               x[i,j]   <- y[[j]][which(names(y[[j]]) == dimnames(x)[[1]][i])]
      }
    }
    return(x)
  }
  Try(cat("\n"))
  
  Try(mat.miRNA <- .fillMat(mat.miRNA, data.list))
  #saving the data table before annotation addition
  
   .SaveNGSmatrix <- function(mymat)
   {
      Try(FileName <- tclvalue(tkgetSaveFile(initialfile=paste("countMatrix.xls",sep=""),filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
      Try(if(!nchar(FileName))
      return())
      Try(write.table(mymat,file=FileName,quote=FALSE, sep="\t", row.names=T, col.names=NA))
   }
   
  Try(countVal <- tkmessageBox(title="Adding Annotation",
                            message="IMPORTANT: annotation will remove microRNAs characterized by multiple locations in the genome.\n If you answer NO annotation will not be added.",
                            icon="question",type="yesno",default="yes"))
      Try(if(tclvalue(countVal)=="no"){

  Try(tmp.genome <- NULL)
  Try(tmp.genome[1] <- length(grep("hsa", rownames(mat.miRNA))))
  Try(tmp.genome[2] <- length(grep("mmu", rownames(mat.miRNA))))
  Try(tmp.genome[3] <- length(grep("rno", rownames(mat.miRNA))))
  Try(my.genome <- which(tmp.genome == max(tmp.genome))) 
  if(my.genome == 1){
      Try(genome.version <- "hg19")
      Try(chrs <- seq(1, 25))
      Try(chrs.names <- c(chrs[1:22], "X", "Y", "MT"))
      Try(names(chrs) <- chrs.names)
      #require(BSgenome.Hsapiens.UCSC.hg19) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Hsapiens.UCSC.hg19") ; require(BSgenome.Hsapiens.UCSC.hg19)}
      Try(data("chrLength",package="oneChannelGUI"))
      Try(chrLength <- get("chrLength",envir=.GlobalEnv))
      Try(chrs.length <- chrLength$hg19)
      Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
  }
  if(my.genome == 2){
       Try(genome.version <- "mm8")
       Try(chrs <- seq(1, 22))
       Try(chrs.names <- c(chrs[1:19], "X", "Y", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Mmusculus.UCSC.mm9) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Mmusculus.UCSC.mm9") ; require(BSgenome.Mmusculus.UCSC.mm9)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$mm9)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected M. musculus genome UCSC release mm9.",type="ok", icon="info"))
  }
  if(my.genome == 3){
       Try(genome.version <- "rn4")
       Try(chrs <- seq(1, 21))
       Try(chrs.names <- c(chrs[1:19], "X", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Rnorvegicus.UCSC.rn4) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Rnorvegicus.UCSC.rn4") ; require(BSgenome.Rnorvegicus.UCSC.rn4)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$rn4)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected R. norvegicus genome UCSC release rn4.",type="ok", icon="info"))
  }
    Try(NormalizedAffyData <- new("ExpressionSet", assayData = assayDataNew(exprs=mat.miRNA) , phenoData=tmp1.pd, annotation=genome.version))
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
  Try(assign("NGS.Available",TRUE,affylmGUIenvironment))
	Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="NGS counts from miRanalyser",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status" ,text="NGS data",font=.affylmGUIglobals$affylmGUIfontTree))

	Try(if("Name" %in% colnames(Targets))
	SlideNamesVec <- Targets$Name)
	Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))

 	Try(ReturnVal <- GetlimmaDataSetName())
	if(ReturnVal==0) return(0)
	return(1)

  
      } else{
          Try(tkmessageBox(title="Saving miRNA data",message="A data matrix before annotation will be saved.",type="ok", icon="info"))
          Try(.SaveNGSmatrix(mat.miRNA)) 
          Try(tmp.genome <- NULL)
  Try(tmp.genome[1] <- length(grep("hsa", rownames(mat.miRNA))))
  Try(tmp.genome[2] <- length(grep("mmu", rownames(mat.miRNA))))
  Try(tmp.genome[3] <- length(grep("rno", rownames(mat.miRNA))))
  Try(my.genome <- which(tmp.genome == max(tmp.genome))) 
  if(my.genome == 1){
      Try(genome.version <- "hg19")
      Try(chrs <- seq(1, 25))
      Try(chrs.names <- c(chrs[1:22], "X", "Y", "MT"))
      Try(names(chrs) <- chrs.names)
      #require(BSgenome.Hsapiens.UCSC.hg19) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Hsapiens.UCSC.hg19") ; require(BSgenome.Hsapiens.UCSC.hg19)}
      Try(data("chrLength",package="oneChannelGUI"))
      Try(chrLength <- get("chrLength",envir=.GlobalEnv))
      Try(chrs.length <- chrLength$hg19)
      Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
  }
  if(my.genome == 2){
       Try(genome.version <- "mm8")
       Try(chrs <- seq(1, 22))
       Try(chrs.names <- c(chrs[1:19], "X", "Y", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Mmusculus.UCSC.mm9) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Mmusculus.UCSC.mm9") ; require(BSgenome.Mmusculus.UCSC.mm9)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$mm9)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected M. musculus genome UCSC release mm9.",type="ok", icon="info"))
  }
  if(my.genome == 3){
       Try(genome.version <- "rn4")
       Try(chrs <- seq(1, 21))
       Try(chrs.names <- c(chrs[1:19], "X", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Rnorvegicus.UCSC.rn4) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Rnorvegicus.UCSC.rn4") ; require(BSgenome.Rnorvegicus.UCSC.rn4)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$rn4)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected R. norvegicus genome UCSC release rn4.",type="ok", icon="info"))
  }
    Try(getNGSannotation())
  Try(chrs.length <- get("chrsLength", affylmGUIenvironment))
  Try(myAnn <- get("tmpNGSannotation", affylmGUIenvironment))
  Try(pm <- as.data.frame(myAnn))
  Try(p <- pm[which(pm$strand == 1),])
  Try(m <- pm[which(pm$strand == -1),])
  Try(pm <- rbind(p,m))
  Try(pm <- pm[which(pm$space %in% names(chrs.length)),])
  Try(chr <- as.character(pm$space))
  Try(annoData <- data.frame(chr=chr, strand=pm$strand, start=pm$start, end=pm$end, feature=as.character(pm$description)))
  Try(rownames(annoData) <- as.character(pm$names))
  Try(description <- as.character(annoData$feature))
  Try(annoData <- annoData[grep("miRBase", description),])
  Try(description <- as.character(annoData$feature))
  Try(description <- strsplit(description, " "))
  Try(description <- sapply(description, function(x) x[1]))
  if(my.genome == 1){
#        description <- paste("hsa-miR-", description, sep="")
        Try(annoData$feature <- description)
  }
  if(my.genome == 2){
#        description <- paste("mmu-miR-", description, sep="")
        Try(annoData$feature <- description)
 }
  if(my.genome == 3){
#        description <- paste("rno-miR-", description, sep="")
        Try(annoData$feature <- description)
  }
  #detecting and removing duplicated miRNA
  Try(duplicated <- which(annoData$feature %in% annoData$feature[which(duplicated(annoData$feature))]))
  Try(cat("\nThe following miRNAs were removed since present in duplicated positions\n"))
  Try(print(annoData[duplicated,]))
  Try(cat("\n"))
  Try(annoData <- annoData[setdiff(seq(1,dim(annoData)[1]), duplicated),])
  #

  Try(annoData <- annoData[which(annoData$feature %in% dimnames(mat.miRNA)[[1]]),])
  Try(annoData <- annoData[order(annoData$feature),])
  Try(mat.miRNA <- mat.miRNA[which(dimnames(mat.miRNA)[[1]] %in% annoData$feature),])
  Try(mat.miRNA <- mat.miRNA[order(dimnames(mat.miRNA)[[1]]),])
  Try(mat.rnames <- apply(annoData, 1, function(x) paste("chr:",x[1],"strand:",x[2], "start:", x[3], "end:", x[4], "description:", x[5] , sep=" ")))
  Try(mat.rnames <- paste(names(mat.rnames), mat.rnames))
  
  if(identical(dimnames(mat.miRNA)[[1]], annoData$feature)){
       Try(dimnames(mat.miRNA)[[1]] <-  mat.rnames)
  }else{
     Try(tkmessageBox(title="Internal error",message="Internal error 12346. Please contact oneChannelGUI maintainer",type="ok", icon="error"))
     return()
  }
  
  Try(NormalizedAffyData <- new("ExpressionSet", assayData = assayDataNew(exprs=mat.miRNA) , phenoData=tmp1.pd, annotation=genome.version))
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
  Try(assign("NGS.Available",TRUE,affylmGUIenvironment))
	Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="NGS counts from miRanalyser",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status" ,text="NGS data",font=.affylmGUIglobals$affylmGUIfontTree))

	Try(if("Name" %in% colnames(Targets))
	SlideNamesVec <- Targets$Name)
	Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
  Try(tkfocus(.affylmGUIglobals$ttMain))
 	Try(ReturnVal <- GetlimmaDataSetName())
	if(ReturnVal==0) return(0)
	return(1)

  
      }) 
    
}


################################################################################
ExportfeatureNames <- function(){
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(limmaDataSetNameText <- get("limmaDataSetNameText", envir = affylmGUIenvironment))
    Try(ArraysLoaded <- get("ArraysLoaded", envir = affylmGUIenvironment))
    Try(if (ArraysLoaded == FALSE) {
        Try(tkmessageBox(title = "Export gene-level Probe sets ids", 
            message = "Error: No arrays have been loaded.", icon = "error", 
            default = "ok"))
        return()
    })
    Try(NormalizedAffyData.Available <- get("NormalizedAffyData.Available", 
        envir = affylmGUIenvironment))
    Try(if (NormalizedAffyData.Available == FALSE) {
        NormalizeNow()
    })
    Try(NormalizedAffyData.Available <- get("NormalizedAffyData.Available", 
        envir = affylmGUIenvironment))
    Try(if (NormalizedAffyData.Available == FALSE) {
        tkmessageBox(title = "Export gene-level probe sets ids", 
            message = "An error or cancellation occured while trying to normalize the data.")
        return()
    })
    Try(NormalizedAffyData <- get("NormalizedAffyData", envir = affylmGUIenvironment))
    Try(NormalizedAffyData.exprs <- exprs(NormalizedAffyData))
    Try(FileName <- tclvalue(tkgetSaveFile(initialfile = paste(limmaDataSetNameText, 
        "_gene-level_probesetsIDs.txt", sep = ""), filetypes = "{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
    Try(if (!nchar(FileName)) 
        return())
    Try(len <- nchar(FileName))
    if (len <= 4) {
        Try(FileName <- paste(FileName, ".txt", sep = ""))
    }
    else if ((substring(FileName, len - 3, len) != ".txt") && 
        (substring(FileName, len - 3, len) != ".xls")) {
        Try(FileName <- paste(FileName, ".txt", sep = ""))
    }
    #Try(write.table(NormalizedAffyData.exprs, file = FileName,  sep = "\t", quote = FALSE, col.names = NA))
    Try(zz <- file(FileName, "w"))
    Try(writeLines(featureNames(NormalizedAffyData), con = zz, sep = "\n"))
    Try(close(zz))
    Try(tkfocus(.affylmGUIglobals$ttMain))
}


################################################################################
"OpenBeadStudioFiles" <- function(){
            Try(tkfocus(.affylmGUIglobals$ttMain))
          	require("affy")
	        	Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	        	Try(tkwm.deiconify(ttExonandTargets))
	        	Try(tkgrab.set(ttExonandTargets))
	        	Try(tkfocus(ttExonandTargets))
	        	Try(tkwm.title(ttExonandTargets,"Targets file"))
	        	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

	        	OpenTargetsFileAndSetCursor <- function()
	        	{
			        	Try(tkconfigure(ttExonandTargets,cursor="watch"))
			        	Try(tkfocus(ttExonandTargets))
			        	Try(OpenTargetsFile())
			        	Try(tkconfigure(ttExonandTargets,cursor="arrow"))
			        	Try(tkfocus(ttExonandTargets))
	        	}
        		Try(OpenTargetsFile.but <- tkbutton(ttExonandTargets, text="Select Targets File",command=OpenTargetsFile,font=.affylmGUIglobals$affylmGUIfont2))

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

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

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

	        	if(Abort==1)
				        	return(0)
        		Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	        	Try(tkfocus(.affylmGUIglobals$ttMain))
          ####opening bead studio files and selecting Bead studio version
          Try(mbVal <- tkmessageBox(title="Start New Analysis",
				    											message="Please select the expression data file generated by BeadStudio software.",
						    									icon="question",type="yesno",default="yes"
								    						 )#end of tkmessageBox
		    )#end of Try(mbVal..
		    if(tclvalue(mbVal)=="yes"){
            Try(dataFileName <- tclvalue(tkgetOpenFile(filetypes="{{Text Files} {.csv}} {{All files} *}")))
               if(!nchar(dataFileName))
               {
                  tkfocus(.affylmGUIglobals$ttMain)
                  return()
               }
        }
		    if(tclvalue(mbVal)=="no"){
			    Try(tkfocus(.affylmGUIglobals$ttMain))
			    return()
		    }#end of if(tclvalue(mbVal)=="no")
        Try(ttGetVersion <- tktoplevel(.affylmGUIglobals$ttMain))
	      Try(tkwm.deiconify(ttGetVersion))
	      Try(tkgrab.set(ttGetVersion))
	      Try(tkfocus(ttGetVersion))
	      Try(tkwm.title(ttGetVersion,"Selecting BeadStudio Version"))
	      #
	      Try(tkgrid(tklabel(ttGetVersion,text="    ")))
	      Try(VersionTcl <- tclVar("One"))
	      Try(rbONE <- tkradiobutton(ttGetVersion,text="BeadStudio v.1 outuput",variable=VersionTcl,value="One",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(rbTWO <- tkradiobutton(ttGetVersion,text="BeadStudio v.2 outuput",variable=VersionTcl,value="Two",font=.affylmGUIglobals$affylmGUIfont2))
        Try(rbTHREE <- tkradiobutton(ttGetVersion,text="BeadStudio v.3 outuput",variable=VersionTcl,value="Three",font=.affylmGUIglobals$affylmGUIfont2))
        Try(tkgrid(tklabel(ttGetVersion,text="    "),rbONE))
	      Try(tkgrid(tklabel(ttGetVersion,text="    "),rbTWO))
	      Try(tkgrid(tklabel(ttGetVersion,text="    "),rbTHREE))
      	Try(tkgrid.configure(rbONE,rbTWO,rbTHREE, columnspan=2,sticky="w"))
       	Try(tkgrid(tklabel(ttGetVersion,text="    "),tklabel(ttGetVersion,text="    ")))
	      #
	      Try(ReturnVal <- "")
	      Try(
		         onCancel <- function() {
			          Try(ReturnVal <<- "");
			          Try(tkgrab.release(ttGetVersion));
			          Try(tkdestroy(ttGetVersion));
			          Try(tkfocus(.affylmGUIglobals$ttMain))
		        }
	      )
	      Try(
		       onOK <- function() {
			         Try(ReturnVal <<- tclvalue(VersionTcl));
			         Try(tkgrab.release(ttGetVersion));
			         Try(tkdestroy(ttGetVersion));
			         Try(tkfocus(.affylmGUIglobals$ttMain))
		      }
	     )
       #
	     Try(OK.but     <- tkbutton(ttGetVersion,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	     Try(Cancel.but <- tkbutton(ttGetVersion,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
	     #
	     Try(tkgrid(tklabel(ttGetVersion,text="    "),OK.but,Cancel.but,tklabel(ttGetVersion,text="    ")))
	     Try(tkgrid.configure(OK.but,sticky="e"))
	     Try(tkgrid.configure(Cancel.but,sticky="w"))
	     Try(tkgrid(tklabel(ttGetVersion,text="    ")))
	     #
	     Try(tkbind(ttGetVersion,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetVersion));Try(tkfocus(.affylmGUIglobals$ttMain));}))
	     Try(tkbind(OK.but, "<Return>",onOK))
	     Try(tkbind(Cancel.but, "<Return>",onCancel))
	     #
	     Try(tkwait.window(ttGetVersion))
       Try(if(ReturnVal=="") return())

       #defining the annotation under use if v3 beadstudio is used
       Try(ttGetAnn <- tktoplevel(.affylmGUIglobals$ttMain))
	      Try(tkwm.deiconify(ttGetAnn))
	      Try(tkgrab.set(ttGetAnn))
	      Try(tkfocus(ttGetAnn))
	      Try(tkwm.title(ttGetAnn,"Selecting Bioconductor annotation package"))
	      #
	      Try(tkgrid(tklabel(ttGetAnn,text="    ")))
	      Try(AnnTcl <- tclVar("illuminaHumanv1BeadID.db"))
	      Try(rbA <- tkradiobutton(ttGetAnn,text="Illumina HumanWGv1",variable=AnnTcl,value="illuminaHumanv1",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(rbB <- tkradiobutton(ttGetAnn,text="Illumina HumanWGv2",variable=AnnTcl,value="illuminaHumanv2",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(rbC <- tkradiobutton(ttGetAnn,text="Illumina HumanWGv3",variable=AnnTcl,value="illuminaHumanv3",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(rbD <- tkradiobutton(ttGetAnn,text="Illumina HumanWGv4",variable=AnnTcl,value="illuminaHumanv4",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(rbE <- tkradiobutton(ttGetAnn,text="Illumina MouseWGv1",variable=AnnTcl,value="illuminaMousev1",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(rbF <- tkradiobutton(ttGetAnn,text="Illumina MouseWGv2",variable=AnnTcl,value="illuminaMousev2",font=.affylmGUIglobals$affylmGUIfont2))
	    Try(rbG <- tkradiobutton(ttGetAnn,text="Illumina RatWGv1",variable=AnnTcl,value="illuminaRatv1",font=.affylmGUIglobals$affylmGUIfont2))
        Try(rbH <- tkradiobutton(ttGetAnn,text="None",variable=AnnTcl,value="",font=.affylmGUIglobals$affylmGUIfont2))
        
        Try(tkgrid(tklabel(ttGetAnn,text="    "),rbA))
        Try(tkgrid(tklabel(ttGetAnn,text="    "),rbB))
        Try(tkgrid(tklabel(ttGetAnn,text="    "),rbC))
        Try(tkgrid(tklabel(ttGetAnn,text="    "),rbD))
        Try(tkgrid(tklabel(ttGetAnn,text="    "),rbE))
        Try(tkgrid(tklabel(ttGetAnn,text="    "),rbF))
        Try(tkgrid(tklabel(ttGetAnn,text="    "),rbG))
        Try(tkgrid(tklabel(ttGetAnn,text="    "),rbH))
        
      	Try(tkgrid.configure(rbA,rbB,rbC, rbD, rbE, rbF, rbG, rbH, columnspan=2,sticky="w"))
       	Try(tkgrid(tklabel(ttGetAnn,text="    "),tklabel(ttGetAnn,text="    ")))
	      #
	      Try(ReturnAnn <- "")
	      Try(
		         onCancel <- function() {
			          Try(ReturnAnn <<- "");
			          Try(tkgrab.release(ttGetAnn));
			          Try(tkdestroy(ttGetAnn));
			          Try(tkfocus(.affylmGUIglobals$ttMain))
		        }
	      )
	      Try(
		       onOK <- function() {
			         Try(ReturnAnn <<- tclvalue(AnnTcl));
			         Try(tkgrab.release(ttGetAnn));
			         Try(tkdestroy(ttGetAnn));
			         Try(tkfocus(.affylmGUIglobals$ttMain))
		      }
	     )
       #
	     Try(OK.but     <- tkbutton(ttGetAnn,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	     Try(Cancel.but <- tkbutton(ttGetAnn,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
	     #
	     Try(tkgrid(tklabel(ttGetAnn,text="    "),OK.but,Cancel.but,tklabel(ttGetAnn,text="    ")))
	     Try(tkgrid.configure(OK.but,sticky="e"))
	     Try(tkgrid.configure(Cancel.but,sticky="w"))
	     Try(tkgrid(tklabel(ttGetAnn,text="    ")))
	     #
	     Try(tkbind(ttGetAnn,"<Destroy>",function() {ReturnAnn <- "";Try(tkgrab.release(ttGetAnn));Try(tkfocus(.affylmGUIglobals$ttMain));}))
	     Try(tkbind(OK.but, "<Return>",onOK))
	     Try(tkbind(Cancel.but, "<Return>",onCancel))
	     #
	     Try(tkwait.window(ttGetAnn))
       ############################################################
       
       Try(illuData <- .readBead(filenames=dataFileName, version=ReturnVal, annotation = ReturnAnn))
       Try(assign("illuData", illuData, env=affylmGUIenvironment))
       Try(assign("illuData.Available", TRUE, env=affylmGUIenvironment))
       
       Try(Targets <- get("Targets",affylmGUIenvironment))
       Try(rownames(Targets) <- Targets$FileName) 
       Try(var.tmp.pd<-data.frame(names(Targets)))
       Try(names(var.tmp.pd)<-"labelDescription" )
       Try(rownames(var.tmp.pd)<-names(Targets))
       Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
       Try(target.array.names <- sub(".AVG_Signal", "", tmp1.pd$FileName))
       Try(my.exons <- illuData$signal)#loading gene expression data is a matrix
       Try(my.exons.array.names <- NULL)
       Try(    for( i in 1:length(target.array.names)){
                             if(length(grep(target.array.names[i], dimnames(my.exons)[[2]])) == 1){
                                    my.exons.array.names[i] <- grep(target.array.names[i], dimnames(my.exons)[[2]])
                             } else{
                                    error.message <- paste("\nERROR! Filenames are not unique!\n", target.array.names[i], " is a substring of ", paste(names(my.exons)[grep(target.array.names[i], dimnames(my.exons)[[2]])],sep=","), "\n", sep="")
                                    cat("\nERROR! Filenames are not unique!\n")
                                    cat(error.message)
                                    cat("\nYou need to modify filenames since the function is unable to correctly associate arrays to target Filenames\n")
                                    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                                    return()
                             }
       })
       Try(my.exons <- my.exons[,my.exons.array.names])
       Try(dimnames(my.exons)[[2]] <-  tmp1.pd$FileName)
       Try(startFun <- tclvalue(tkmessageBox(title="Log transformation",message="Do you wish to log2 transform your data?",type="yesno",icon="question")))
       Try(if (startFun=="yes"){
            if(length(which(my.exons <= 0)) == 0){
              my.exons <- log2(my.exons)
              #excluding the presence of NA
              Try(my.exons[which(is.na(my.exons))] <- 1)
            } else{
              my.exons[which(my.exons <= 0)] <- 1
              my.exons <- log2(my.exons)
              #excluding the presence of NA
              Try(my.exons[which(is.na(my.exons))] <- 1)
              Try(tkmessageBox(title="Log2 transformation",message="In case of beads with signal values below or equal to 0 those are set to 1 before log2 transformation"))
            }
       })
       
       Try(NormalizedAffyData <- new("ExpressionSet", exprs=my.exons, phenoData=tmp1.pd, annotation=illuData$annotation))
       Try(assign("NormalizedAffyData", NormalizedAffyData, env=affylmGUIenvironment))
       Try(assign("NormalizedAffyData.Available", TRUE, env=affylmGUIenvironment))
     	 Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	     Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Output from BeadStudio",font=.affylmGUIglobals$affylmGUIfontTree))
       	Try(if("Name" %in% colnames(Targets))
	              SlideNamesVec <- Targets$Name)
	      Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	      Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
        Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
        Try(tkfocus(.affylmGUIglobals$ttMain))
 	      Try(ReturnVal <- GetlimmaDataSetName())
	      if(ReturnVal==0) return(0)
	      return(1)
}

################################################################################
#modified by BeadExplorer library
".readBead" <- function (filenames=NULL, annotation="", verbose=TRUE, version="Two"){
      if (length (filenames)==0) stop ("No input file specified")
      if (version=="One"){ 
	        if (verbose) cat (paste ("Read ", filenames[1], "\n", sep=""))
          param<-scan (filenames[1], nlines=5, what=character(0), sep="\n", strip.white=TRUE, quiet=TRUE)
          param<-param2<-gsub ("(Illumina Inc. BeadStudio version |Normalization = |Array Content = |Error Model = | DateTime = |.xml)", "", param)
          param<-gsub(",","",param)
          names(param)<-c("BeadStudioVersion", "Normalization", "ArrayContent", "ErrorModel", "DateTime")
          data<-read.delim (filenames[1], skip=7, sep=",", row.names=1)
      } else if (version=="Two"){
	        if (verbose) cat (paste ("Read ", filenames[1], "\n", sep=""))
          param<-scan (filenames[1], nlines=5, what=character(0), sep="\n", strip.white=TRUE, quiet=TRUE)
          param<-param2<-gsub ("(Illumina Inc. BeadStudio version |Normalization = |Array Content = |Error Model = | DateTime = |.xml)", "", param)
          param<-gsub(",","",param)
          names(param)<-c("BeadStudioVersion", "Normalization", "ArrayContent", "ErrorModel", "DateTime")
          data<-read.delim (filenames[1], skip=7, row.names=1)
      } else if (version=="Three"){
            data<-read.delim (filenames[1], skip=8, row.names=1)
      } else {
           stop ("Cannot identify version number")
      }
      if (version == "One" | version == "Two"){
          names<-colnames (data)
          signal<-grep ("AVG_Signal", names)
          confid<-grep ("Detection", names)
          sd<-grep ("BEAD_STDEV",names)
          colnames (data)<-gsub ("AVG_Signal.", "", names)
          signal<-data[,signal]
          confscores<-data[,confid]
          sdscores<-data[,sd]
          #defining which bioconductor annotation lib should be used
          arrayContent <- as.vector(unlist(param[names(param)=="ArrayContent"]))
          organism <- NULL
          if(length(grep("Human", arrayContent))==1){
                 organism <- "Human"
          } else if(length(grep("Mouse", arrayContent))==1){
                 organism <- "Mouse"
          } else if(length(grep("Rat", arrayContent))==1){
                organism <- "Rat"
          }
          chipVersion <- NULL
          if(length(grep("V1", arrayContent))==1){
              chipVersion <- "v1"
          } else if(length(grep("V2", arrayContent))==1){
              chipVersion <- "v2"
          }  else if(length(grep("V3", arrayContent))==1){
              chipVersion <- "v3"
          }
      
          param[names(param)=="ArrayContent"]
#         illuData <-  list("signal"=as.matrix(signal), "detection"=as.matrix(confscores), "se.exprs"=as.matrix(sdscores), "annotation"=annotation)
          illuData <-  list("signal"=as.matrix(signal), "annotation"=annotation)       
      
      } else{
          names<-colnames (data)
          signal<-grep ("AVG_Signal", names)
          #confid<-grep ("Detection", names)
          #sd<-grep ("Avg_NBEADS",names)  #number of beads is used instead of sd
          colnames (data)<-gsub(".AVG_Signal", "", names)
          signal<-data[,signal]
          #confscores<-data[,confid]
          #sdscores<-data[,sd]
      
#         illuData <-  list("signal"=as.matrix(signal), "detection"=as.matrix(confscores), "se.exprs"=as.matrix(sdscores), "annotation"=annotation)
          illuData <-  list("signal"=as.matrix(signal), "annotation"=annotation)       
      }
    	return(illuData)
}
################################################################################
"createGeoTarget" <- function(){
        Try(tkfocus(.affylmGUIglobals$ttMain))
        #loading the tab delimited file
          Try(tkmessageBox(title="Create a Target File",message="Open the GEO Series Matrix file."))  
          Try(tempFileName <- tclvalue(tkgetOpenFile(filetypes="{{Text Files} {.txt}} {{All files} *}")))
               if(!nchar(tempFileName))
               {
                  tkfocus(.affylmGUIglobals$ttMain)
                  return()
               }
           ##start grabbing GEO platform info
           Try(con <- file(tempFileName, "r", blocking = FALSE))
           Try(geoInfo <- readLines(con, n=600))
           Try(close(con))
           #creating Name 
           Try(geoName <- geoInfo[grep("^!Sample_title",geoInfo)])
           Try(geoName <- strsplit(geoName, "\\\""))
           Try(geoName <- unlist(geoName))
           Try(geoName <- geoName[seq(from = 2, to = length(geoName), by=2)])
           Try(geoName <- sapply(geoName, function(x)gsub(" ", ".", x)))
           Try(geoName <- as.vector(unlist(geoName)))
           #creating FileName
           Try(geoFileNames <- geoInfo[grep("ID_REF",geoInfo)])
           Try(geoFileNames <- strsplit(geoFileNames, "\\\""))
           Try(geoFileNames <- unlist(geoFileNames))
           Try(geoFileNames <- geoFileNames[seq(from = 4, to = length(geoFileNames), by=2)])
           #creating target
           Try(geoTarget <- geoInfo[grep("^!Sample_source_name_ch1",geoInfo)])
           Try(geoTarget <- strsplit(geoTarget, "\\\""))
           Try(geoTarget <- unlist(geoTarget))
           Try(geoTarget <- geoTarget[seq(from = 2, to = length(geoTarget), by=2)])
           Try(geoTarget <- sapply(geoTarget, function(x)gsub(" ", ".", x)))
           Try(geoTarget <- as.vector(unlist(geoTarget)))
           Try(mytarget <- data.frame(geoName, geoFileNames, geoTarget))
           Try(names(mytarget) <- c("Name", "FileName", "Target")) 
           #creating the target file name 
           Try(geoSeriesName <- geoInfo[grep("^!Series_geo_accession",geoInfo)])
           Try(geoSeriesName <- strsplit(geoSeriesName, "\\\""))
           Try(geoSeriesName <- unlist(geoSeriesName))
           Try(geoSeriesName <- geoSeriesName[2])
           Try(geoSeriesName <- paste("target.", geoSeriesName, ".txt", sep=""))
           Try(write.table(mytarget, file= geoSeriesName, sep="\t", row.names=F))
           Try(tkmessageBox(title="Create a Target File",message=paste("The target file is saved in ", getwd(), "\nwith the name ", geoSeriesName, sep="")))
           Try(tkfocus(.affylmGUIglobals$ttMain))
}
#combining GEO matrix series files
"combineGeoMSF"  <- function(){
                Try(tkfocus(.affylmGUIglobals$ttMain))
                #Try(tkmessageBox(title="Combining GEO Series Matrix file",message="How many matrix series files do you want to combine?"))        
                ###########Defining the numbero of  GEO Series Matrix file to be combined
                Try(ttGetGeoN<-tktoplevel(.affylmGUIglobals$ttMain))
                Try(tkwm.deiconify(ttGetGeoN))
                Try(tkgrab.set(ttGetGeoN))
                Try(tkfocus(ttGetGeoN))
                Try(tkwm.title(ttGetGeoN,"N. of GEO Matrix Series Files"))
                Try(tkgrid(tklabel(ttGetGeoN,text="    ")))
                Try(CovarText <- "")
                Try(Local.Covar <- tclVar(init=CovarText))
                Try(entry.Covar <-tkentry(ttGetGeoN,width="3",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.Covar,bg="white"))
                Try(tkgrid(tklabel(ttGetGeoN,text="Please enter the N. of GEO Matrix Series Files to be combined",font=.affylmGUIglobals$affylmGUIfont2)))
                Try(tkgrid(entry.Covar))
                Try( 
   	                onOK <- function() {
			                Try(CovarText <<- tclvalue(Local.Covar))
			                Try(tkgrab.release(ttGetGeoN))
			                Try(tkdestroy(ttGetGeoN))
		 	                Try(tkfocus(.affylmGUIglobals$ttMain))
		               }
	              )
                                                
                Try(OK.but <-tkbutton(ttGetGeoN,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
                Try(tkgrid(tklabel(ttGetGeoN,text="    ")))
                Try(tkgrid(OK.but))
                Try(tkgrid.configure(OK.but))
                Try(tkgrid(tklabel(ttGetGeoN,text="       ")))
                Try(tkfocus(entry.Covar))
                Try(tkbind(entry.Covar, "<Return>",onOK))
                Try(tkbind(ttGetGeoN, "<Destroy>", function(){Try(tkgrab.release(ttGetGeoN));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
                Try(tkwait.window(ttGetGeoN))
                Try(tkfocus(.affylmGUIglobals$ttMain))
                Try(mycovar <- as.numeric(CovarText))
                if(CovarText=="" || nchar(CovarText)==0){
                       Try(tkmessageBox(title="Combining GEO Series Matrix file",message="No GEO Matrix Series Files were selected.\nAborting the analysis!"))
                       Try(return())
                }   else {
                            Try(OpenGeoFiles())
                            Try(NormalizedAffyData1 <- get("NormalizedAffyData", env=affylmGUIenvironment))
                            Try(targets1 <- get("Targets", env=affylmGUIenvironment))
                            for( i in 2:mycovar){
                                     Try(OpenGeoFiles())
                                     Try(NormalizedAffyData <- get("NormalizedAffyData", env=affylmGUIenvironment))
                                     Try(targets <- get("Targets", env=affylmGUIenvironment))
                                     Try(NormalizedAffyData1 <- combine(NormalizedAffyData1, NormalizedAffyData))
                                     Try(targets1 <- rbind(targets1, targets)) 
                            }
                            Try(assign("NormalizedAffyData",NormalizedAffyData1,affylmGUIenvironment))
                            Try(assign("Targets",targets1,affylmGUIenvironment))
                }


               Try(tkfocus(.affylmGUIglobals$ttMain))

}
################################################################################
#modified on 16 12 2006 adding the load of exon expression signal together with gene expression signal
OpenExonandTargetsfiles <- function()
{
	Try(tkfocus(.affylmGUIglobals$ttMain))
  require("affy")
	Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttExonandTargets))
	Try(tkgrab.set(ttExonandTargets))
	Try(tkfocus(ttExonandTargets))
	Try(tkwm.title(ttExonandTargets,"Targets file"))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

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

#	OpenExonFileAndSetCursor <- function()
#	{
#			Try(tkconfigure(ttExonandTargets,cursor="watch"))
#			Try(tkfocus(ttExonandTargets))
#			Try(OpenExonFile())
#			Try(tkconfigure(ttExonandTargets,cursor="arrow"))
#			Try(tkfocus(ttExonandTargets))
#	}

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

	#Try(tclvalue(.affylmGUIglobals$CDFfileName) <- fixSeps(tclvalue(.affylmGUIglobals$CDFfileName)))
	#Try(.affylmGUIglobals$CDFfileBoxTitleLabel<-tklabel(ttCDFandTargets,text=as.character(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)),font=.affylmGUIglobals$affylmGUIfont2))
	#Try(.affylmGUIglobals$CDFfileNameLabel<-tklabel(ttCDFandTargets,text=as.character(tclvalue(.affylmGUIglobals$CDFfileName)),background="white",font=.affylmGUIglobals$affylmGUIfont2))
	#Try(tkconfigure(.affylmGUIglobals$CDFfileBoxTitleLabel, textvariable=.affylmGUIglobals$CDFfileBoxTitle))
	#Try(tkconfigure(.affylmGUIglobals$CDFfileNameLabel, textvariable=.affylmGUIglobals$CDFfileName))

#	Try(tkgrid(tklabel(ttCDFandTargets,text="    ")))
#	Try(tkgrid(.affylmGUIglobals$CDFfileBoxTitleLabel,columnspan=4))
#	Try(tkgrid(.affylmGUIglobals$CDFfileNameLabel,columnspan=4))

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

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

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

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

	if(Abort==1)
				return(0)

	#OK
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(Targets <- get("Targets",affylmGUIenvironment))
	Try(slides <- Targets$FileName)
	#################################################
  #not used for exons from expression console
  #Try(filesExist <- file.exists(slides))
	#Try(filesWhichDontExist <- slides[!filesExist])
	#Try(if(length(filesWhichDontExist)>0)
	#	Try(for (i in (1:length(filesWhichDontExist)))
	#		Try(tkmessageBox(title="Error opening file",message=paste("Failed to open file: \"",filesWhichDontExist[i],"\"",sep=""),icon="error"))))
	#Try(if(length(filesWhichDontExist)>0)
	#{
	#	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	#	return(0)
	#})
  #########################################################
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  
  
  Try(exonVal <- get("exonVal",envir=affylmGUIenvironment)) #recover the information about the decision of using apt tools for  intenisties calculation
  Try(whichArrayPlatform <- get("whichArrayPlatform",affylmGUIenvironment))
  if(affylmGUIenvironment$aptDir.Available & tclvalue(exonVal)=="yes" & whichArrayPlatform=="EXON"){
           Try(aptDir <- get("aptDir",envir=affylmGUIenvironment))
           Try(libDir <- get("libDir",envir=affylmGUIenvironment))
           Try(whichLib <- get("whichLib",envir=affylmGUIenvironment))
           #mapping the clf pgf files
           Try(content.libDir <- dir(libDir))
           Try(clf.name <- paste(libDir, content.libDir[intersect(grep(whichLib[[1]][1],content.libDir), grep('.clf$',content.libDir))], sep=""))
           Try(pgf.name <- paste(libDir, content.libDir[intersect(grep(whichLib[[1]][1],content.libDir), grep('.pgf$',content.libDir))], sep=""))
           #defining the meta gene subset
           Try(exonlib.name <- paste(libDir, content.libDir[intersect(grep('.mps$',content.libDir), intersect(grep(whichLib[[1]][1],content.libDir), grep(whichLib[[1]][2],content.libDir)))], sep=""))
           #defining the temp file containing target info for apt
           Try(tempTarget <- tempfile(pattern = "target", tmpdir = getwd()))
           Try(tempTarget <- sub( "\\\\","/",tempTarget)) #changing double backslach with slash
           Try(write.table(Targets[,2:3], tempTarget, sep="\t", row.names =F, col.names = c("cel_files", "group_id"))) 
           Try(tempOut <- tempfile(pattern = "out", tmpdir = getwd()))#creating a temp outfile
           Try(tempOut <- sub( "\\\\","/",tempOut)) #changing double backslach with slash
   
           #######################################################
           #defining the APT tool gene/exon level calculaiton methods
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(ttIfDialog<-tktoplevel(.affylmGUIglobals$ttMain))
           Try(tkwm.deiconify(ttIfDialog))
           Try(tkgrab.set(ttIfDialog))
           Try(tkfocus(ttIfDialog))
           Try(tkwm.title(ttIfDialog,"APT tools intensity summaries"))
           Try(tkgrid(tklabel(ttIfDialog,text="    ")))
           Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
           Try(HowManyQuestion1 <- tklabel(frame1,text="Gene level methods",font=.affylmGUIglobals$affylmGUIfont2))
           Try(tkgrid(HowManyQuestion1))
           Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
           Try(geneTcl <- tclVar("rma-sketch"))
           Try(I0.but  <- tkradiobutton(frame1,text="rma-sketch",variable=geneTcl,value="rma-sketch",font=.affylmGUIglobals$affylmGUIfont2))
           Try(I1.but  <- tkradiobutton(frame1,text="iter-plier",variable=geneTcl,value="iter-plier",font=.affylmGUIglobals$affylmGUIfont2))
           Try(I2.but <- tkradiobutton(frame1,text="rma quantile norm",variable=geneTcl,value="rma",font=.affylmGUIglobals$affylmGUIfont2))
           Try(I3.but <- tkradiobutton(frame1,text="rma no-norm",variable=geneTcl,value="rma-bg",font=.affylmGUIglobals$affylmGUIfont2))

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

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

           Try(frame2 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
           Try(exonLabel <- tklabel(frame2,text="Exon level methods",font=.affylmGUIglobals$affylmGUIfont2))
           Try(tkgrid(exonLabel,sticky="w"))
           Try(tkgrid.configure(exonLabel,sticky="w"))
           Try(exonTcl <- tclVar("rma-sketch"))
           Try(F0.but <- tkradiobutton(frame2,text="rma sketch quantile norm",variable=exonTcl,value="rma-sketch",font=.affylmGUIglobals$affylmGUIfont2))
           Try(F1.but <- tkradiobutton(frame2,text="plier-gcbg-sketch",variable=exonTcl,value="plier-gcbg-sketch",font=.affylmGUIglobals$affylmGUIfont2))

           Try(tkgrid(F0.but,sticky="w"))
           Try(tkgrid(F1.but,sticky="w"))
           Try(tkgrid.configure(exonLabel,F0.but,F1.but,sticky="w"))
           Try(ReturnValX <<- "")
           Try(onOK <- function()
           {
                ReturnVal1 <- tclvalue(geneTcl)
                ReturnVal2 <- tclvalue(exonTcl)
                Try(ReturnValX <<- paste(ReturnVal1, ReturnVal2, sep=";"))
                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,frame2,tklabel(ttIfDialog,text="  ")))
           Try(tkgrid(tklabel(ttIfDialog,text="    ")))
           Try(tkgrid(tklabel(ttIfDialog,text="    "),frame3,tklabel(ttIfDialog,text="  ")))
           Try(tkgrid(tklabel(ttIfDialog,text="    ")))
           Try(tkgrid.configure(frame1,frame3,sticky="w"))

           Try(tkfocus(ttIfDialog))
           Try(tkbind(ttIfDialog, "<Destroy>", function() {Try(tkgrab.release(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
           Try(tkwait.window(ttIfDialog))

            ##gene/exon routines 
            if(ReturnValX == ""){
                      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                      Try(tkfocus(.affylmGUIglobals$ttMain))
                      Try(return())
            }
           Try(tmpVal<-strsplit(ReturnValX, ";"))
           Try(gene.summary <- tmpVal[[1]][1])
           Try(exon.summary <- tmpVal[[1]][2])

           if(gene.summary == "rma-sketch"){
                    Try(typeOfSummary <-  "rma-sketch")
                    Try(gene.rma.sketch <- paste(aptDir,"/bin/apt-probeset-summarize", " -a ", typeOfSummary," -p ", pgf.name, " -c ", clf.name, " -m ", exonlib.name," -o ", tempOut," --cel-files ", tempTarget, sep=""))
                    Try(cat("\nGene level probe sets summary started\n"))
                    Try(system(gene.rma.sketch, wait = T))#assign to gene summary one of the method implemented for gene summary
                    Try(cat("\nGene level probe sets summary ended\n"))
           }
           if(gene.summary == "rma"){
                    Try(typeOfSummary <-  "rma")
                    Try(gene.rma.sketch <- paste(aptDir,"/bin/apt-probeset-summarize", " -a ", typeOfSummary," -p ", pgf.name, " -c ", clf.name, " -m ", exonlib.name," -o ", tempOut," --cel-files ", tempTarget, sep=""))
                    Try(cat("\nGene level probe sets summary started\n"))
                    Try(system(gene.rma.sketch, wait = T))#assign to gene summary one of the method implemented for gene summary
                    Try(cat("\nGene level probe sets summary ended\n"))
           }
           if(gene.summary == "rma-bg"){
                    Try(typeOfSummary <-  "rma-bg,pm-only,med-polish")
                    Try(gene.rma.sketch <- paste(aptDir,"/bin/apt-probeset-summarize", " -a ", typeOfSummary," -p ", pgf.name, " -c ", clf.name, " -m ", exonlib.name," -o ", tempOut," --cel-files ", tempTarget, sep=""))
                    Try(cat("\nGene level probe sets summary started\n"))
                    Try(system(gene.rma.sketch, wait = T))#assign to gene summary one of the method implemented for gene summary
                    Try(cat("\nGene level probe sets summary ended\n"))
           }
           if(gene.summary == "iter-plier"){
                    Try(typeOfSummary <-  "iter-plier")
                    Try(bgfile.name <- paste(libDir, content.libDir[intersect(grep('[.]antigenomic.bgp$',content.libDir), grep(whichLib[[1]][1],content.libDir))], sep=""))
                    Try(gene.iterplier <- paste(aptDir,"/bin/apt-probeset-summarize", " -a ", "quant-norm.sketch=50000.bioc=false,pm-gcbg,", typeOfSummary," -p ", pgf.name," -b ", bgfile.name," -c ", clf.name, " -m ", exonlib.name," -o ", tempOut," --cel-files ", tempTarget, sep=""))
                    Try(cat("\nGene level probe sets summary started\n"))
                    Try(system(gene.iterplier, wait = T))#assign to gene summary one of the method implemented for gene summary
                    Try(cat("\nGene level probe sets summary ended\n"))
           }

           ##########################################################
           #it is necessary to exchange "-" with "." in the FileNames of Targets 
           #since R will convert "-" into "." for the header of the data file
           #e.g. name in the header of the data file 211_MB-211.rma-gene-core-Signal
           # after reading in R:  211_MB.211.rma.gene.core.Signal
           #therefore the FileName  211_MB-211 should be converted in 211_MB.211
           Try(tmp<- apply(Targets, 1,function(x){sub("-",".",x[2])}))
           Try(Targets[,2] <- tmp )
           ############################################################
  
           Try(rownames(Targets) <- Targets$FileName) 
           Try(var.tmp.pd<-data.frame(names(Targets)))
           Try(names(var.tmp.pd)<-"labelDescription" )
           Try(rownames(var.tmp.pd)<-names(Targets))
           Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
           #Try(target.array.names <- sub(".CEL", "", tmp1.pd$FileName))
           Try(target.array.names <- tmp1.pd$FileName)
           Try(tempOut0 <- paste(typeOfSummary ,".summary.txt",sep=""))
           Try(tempOut0 <- gsub(",", ".", tempOut0))
           Try(content.outDir <- dir(tempOut))
           Try(tempOut1  <- grep(tempOut0, content.outDir))
           Try(my.exons <-read.table(paste(tempOut, "/", content.outDir[tempOut1], sep=""), sep="\t", header=T, as.is=TRUE, row.names=1))#loading gene level data
           Try(my.exons.array.names <- NULL)
           Try(    for( i in 1:length(target.array.names)){
                                    if(length(grep(target.array.names[i], names(my.exons))) == 1){
                                           my.exons.array.names[i] <- grep(target.array.names[i], names(my.exons))
                                    } else{
                                            error.message <- paste("\nERROR! Filenames are not unique!\n", target.array.names[i], " is a substring of ", paste(names(my.exons)[grep(target.array.names[i], names(my.exons))],sep=","), "\n", sep="")
                                            cat("\nERROR! Filenames are not unique!\n")
                                            cat(error.message)
                                            cat("\nYou need to modify filenames since the function is unable to correctly associate arrays to target Filenames\n")
                                            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                                            return()
                                    }
               })
           Try(my.exons <- my.exons[,my.exons.array.names])
           Try(names(my.exons) <-  tmp1.pd$FileName)
           if(gene.summary == "iter-plier"){
                    Try(NormalizedAffyData <- new("ExpressionSet", exprs=log2(as.matrix(my.exons)), phenoData=tmp1.pd, annotation=""))
                    if(!validObject(NormalizedAffyData)){
                           Try(tkmessageBox(title="Gene level APT calculation",message="Check the APT log in the main R window\nNo valid ExpressionSet could be created!",icon="error"))
                				   Try(return())
                    }
           } else {
                    Try(NormalizedAffyData <- new("ExpressionSet", exprs=as.matrix(my.exons), phenoData=tmp1.pd, annotation=""))
                    if(!validObject(NormalizedAffyData)){
                           Try(tkmessageBox(title="Gene level APT calculation",message="Check the APT log in the main R window\nNo valid ExpressionSet could be created!",icon="error"))
                			     Try(return())
                    }

           }
	         Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
	         Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
           Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	         Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Gene level exon data available",font=.affylmGUIglobals$affylmGUIfontTree))
	         Try(if("Name" %in% colnames(Targets))
	         SlideNamesVec <- Targets$Name)
	         Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	         Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
           Try(cat("\nGene level probe sets summary ended\n"))
           ####################
           Try(cat("\nExon level probe sets summary started\n"))
           #defining the exon corrsponding to the meta gene subset
           Try(exonlib1.name <- paste(libDir, content.libDir[intersect(grep('[.]ps$',content.libDir), intersect(grep(whichLib[[1]][1],content.libDir), grep(whichLib[[1]][2],content.libDir)))], sep=""))
           Try(tempOut <- tempfile(pattern = "out", tmpdir = getwd()))#creating a temp outfile
           Try(tempOut <- sub( "\\\\","/",tempOut)) #changing double backslach with slash
           
           if(exon.summary == "rma-sketch"){
                    Try(typeOfSummary <-  "rma-sketch")
                    Try(exon.rma.sketch <- paste(aptDir,"/bin/apt-probeset-summarize", " -a ", typeOfSummary," -p ", pgf.name, " -c ", clf.name, " -s ", exonlib1.name," -o ", tempOut," --cel-files ", tempTarget, sep=""))
                    Try(cat("\nExon level probe sets summary started\n"))
                    Try(system(exon.rma.sketch, wait = T))#assign to exon summary one of the method implemented for gene summary
                    Try(cat("\nExon level probe sets summary ended\n"))
           }
           if(exon.summary == "plier-gcbg-sketch"){
                    Try(typeOfSummary <-  "plier-gcbg-sketch")
                    Try(bgfile.name <- paste(libDir, content.libDir[intersect(grep('[.]antigenomic.bgp$',content.libDir), grep(whichLib[[1]][1],content.libDir))], sep=""))
                    Try(exon.plier <- paste(aptDir,"/bin/apt-probeset-summarize", " -a ", typeOfSummary," -p ", pgf.name, " -c ", clf.name, " -b ", bgfile.name," -s ", exonlib1.name," -o ", tempOut," --cel-files ", tempTarget, sep=""))
                    Try(cat("\nExon level probe sets summary started\n"))
                    Try(system(exon.plier, wait = T))#assign to exon summary one of the method implemented for gene summary
                    Try(cat("\nExon level probe sets summary ended\n"))
           }
           Try(my.exons <-read.table(paste(tempOut, "/", typeOfSummary ,".summary.txt",sep=""), sep="\t", header=T, as.is=TRUE, row.names=1))#loading exon level data
           Try(my.exons.array.names <- NULL)
           Try(    for( i in 1:length(target.array.names)){
                             if(length(grep(target.array.names[i], names(my.exons))) == 1){
                                my.exons.array.names[i] <- grep(target.array.names[i], names(my.exons))
                             } else{
                                    error.message <- paste("\nERROR! Filenames are not unique!\n", target.array.names[i], " is a substring of ", paste(names(my.exons)[grep(target.array.names[i], names(my.exons))],sep=","), "\n", sep="")
                                    cat("\nERROR! Filenames are not unique!\n")
                                    cat(error.message)
                                    cat("\nYou need to modify filenames since the function is unable to correctly associate arrays to target Filenames\n")
                                    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                                    return()
                             }
               })
           Try(my.exons <- my.exons[,my.exons.array.names])
           Try(names(my.exons) <-  tmp1.pd$FileName)
           if(exon.summary == "plier-gcbg-sketch"){
                    Try(ExonAffyData <- new("ExpressionSet", exprs=log2(as.matrix(my.exons)), phenoData=tmp1.pd, annotation=""))
                    if(!validObject(ExonAffyData)){
                           Try(tkmessageBox(title="Exon level APT calculation",message="Check the APT log in the main R window\nNo valid ExpressionSet could be created!",icon="error"))
                			     Try(return())
                    }
           } else {
                    Try(ExonAffyData <- new("ExpressionSet", exprs=as.matrix(my.exons), phenoData=tmp1.pd, annotation=""))
                    if(!validObject(ExonAffyData)){
                           Try(tkmessageBox(title="Exon level APT calculation",message="Check the APT log in the main R window\nNo valid ExpressionSet could be created!",icon="error"))
                			     Try(return())
                    }

           }
	         Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	         Try(tkfocus(.affylmGUIglobals$ttMain))
	         Try(assign("exonAffyData.Available",TRUE,affylmGUIenvironment))
	         Try(assign("exonAffyData",ExonAffyData,affylmGUIenvironment))

	         Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))
	         Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Exon level data available",font=.affylmGUIglobals$affylmGUIfontTree))
           Try(cat("\nExon level probe sets summary ended\n"))
           #############dabg
           Try(mbVal <- tkmessageBox(title="dabg p-values", message="Do you wish to calculate dabg? Dabg is a p-value that the intensities in a probeset \ncould have been observed by chance in a background distribution. \nIt can be used to filter out not expressed probe sets \nbefore alternative splicing analysis.",
						         									icon="question",type="yesnocancel",default="yes"
								         						 )#end of tkmessageBox
		         )#end of Try(mbVal..
		         if(tclvalue(mbVal)=="yes"){
		                Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                    Try(cat("\nDABG calculation started\n"))
                    Try(bgfile.name <- paste(libDir, content.libDir[intersect(grep('[.]antigenomic.bgp$',content.libDir), grep(whichLib[[1]][1],content.libDir))], sep=""))
                    Try(system(paste(aptDir,"/bin/apt-probeset-summarize", " -a ", "dabg"," -b ",bgfile.name, " -p ", pgf.name, " -c ", clf.name, " -m ", exonlib.name," -o ", tempOut," --cel-files ", tempTarget, sep=""), wait = T))
                    #saving dabg in an expression set
                    Try(rownames(Targets) <- Targets$FileName) 
                    Try(var.tmp.pd<-data.frame(names(Targets)))
                    Try(names(var.tmp.pd)<-"labelDescription" )
                    Try(rownames(var.tmp.pd)<-names(Targets))
                    Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
                    #Try(target.array.names <- sub(".CEL", "", tmp1.pd$FileName))
                    Try(target.array.names <- tmp1.pd$FileName)
                    Try(my.exons <-read.table(paste(tempOut, "/", "dabg" ,".summary.txt",sep=""), sep="\t", header=T, as.is=TRUE, row.names=1))#loading gene level data
                    Try(my.exons.array.names <- NULL)
                    Try(    for( i in 1:length(target.array.names)){
                                       if(length(grep(target.array.names[i], names(my.exons))) == 1){
                                            my.exons.array.names[i] <- grep(target.array.names[i], names(my.exons))
                                       } else{
                                               error.message <- paste("\nERROR! Filenames are not unique!\n", target.array.names[i], " is a substring of ", paste(names(my.exons)[grep(target.array.names[i], names(my.exons))],sep=","), "\n", sep="")
                                               cat("\nERROR! Filenames are not unique!\n")
                                               cat(error.message)
                                               cat("\nYou need to modify filenames since the function is unable to correctly associate arrays to target Filenames\n")
                                               Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                                               return()
                                      }
                    })
                    Try(my.exons <- my.exons[,my.exons.array.names])
                    Try(names(my.exons) <-  tmp1.pd$FileName)
                    Try(dabg.p <- new("ExpressionSet", exprs=as.matrix(my.exons), phenoData=tmp1.pd, annotation=""))
                    Try(assign("dabg.p" , dabg.p, affylmGUIenvironment))
                    Try(assign("dabg.Available" , TRUE, affylmGUIenvironment))
                    Try(tkdelete(.affylmGUIglobals$mainTree,"AptDabg.Status"))
                    Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptDabg","AptDabg.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree))
                    Try(cat("\nDABG calculation ended\n"))
                    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
             }
		         if(tclvalue(mbVal)=="cancel"){
			         Try(tkfocus(.affylmGUIglobals$ttMain))
			         return()
			       }  
		        Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
           #################dabg
	         Try(ReturnVal <- GetlimmaDataSetName())
	         if(ReturnVal==0) return(0)
	         return(1)
  } else if(affylmGUIenvironment$aptDir.Available & tclvalue(exonVal)=="yes" & whichArrayPlatform=="GENE"){
           ######gene
           Try(aptDir <- get("aptDir",envir=affylmGUIenvironment))
           Try(libDir <- get("libDir",envir=affylmGUIenvironment))
           Try(whichLib <- get("whichLib",envir=affylmGUIenvironment))
           #mapping the clf pgf files
           Try(content.libDir <- dir(libDir))
           Try(tkfocus(.affylmGUIglobals$ttMain))
#this part is moved at line 1723
#          Try(glibVal <- tkmessageBox(title="Gene library version", message="Are you using genechips version 1.1?\nIf you answer NO version 1.0 of library files will be loaded.",
#						         									icon="question",type="yesnocancel",default="no"
#								         						 )#end of tkmessageBox
#           )#end of Try(glibVal..
#		       if(tclvalue(glibVal)=="yes"){
#               Try(libVersion <- paste(whichLib[[1]][1], "-1_1", sep=""))
#               Try(clf.name <- paste(libDir, content.libDir[intersect(grep(libVersion,content.libDir), grep('.clf$',content.libDir))], sep=""))
#               Try(pgf.name <- paste(libDir, content.libDir[intersect(grep(libVersion,content.libDir), grep('.pgf$',content.libDir))], sep=""))
#               #defining the meta gene subset
#               Try(exonlib.name <- paste(libDir, content.libDir[intersect(grep('.mps$',content.libDir), grep(libVersion,content.libDir))], sep=""))
#           } else if(tclvalue(glibVal)=="no"){
#               Try(libVersion <- paste(whichLib[[1]][1], "-1_0", sep=""))
#               Try(clf.name <- paste(libDir, content.libDir[intersect(grep(libVersion,content.libDir), grep('.clf$',content.libDir))], sep=""))
#               Try(pgf.name <- paste(libDir, content.libDir[intersect(grep(libVersion,content.libDir), grep('.pgf$',content.libDir))], sep=""))
#               #defining the meta gene subset
#               Try(exonlib.name <- paste(libDir, content.libDir[intersect(grep('.mps$',content.libDir), grep(libVersion,content.libDir))], sep=""))
#           }
           Try(geneLibsInfo <- get("geneLibsInfo",envir=affylmGUIenvironment))
           Try(clf.name <- geneLibsInfo$clf.name)
           Try(pgf.name <- geneLibsInfo$pgf.name)
           Try(exonlib.name <- geneLibsInfo$exonlib.name)
           #defining the temp file containing target info for apt
           Try(tempTarget <- tempfile(pattern = "target", tmpdir = getwd()))
           Try(tempTarget <- sub( "\\\\","/",tempTarget)) #changing double backslach with slash
           Try(write.table(Targets[,2:3], tempTarget, sep="\t", row.names =F, col.names = c("cel_files", "group_id"))) 
           Try(tempOut <- tempfile(pattern = "out", tmpdir = getwd()))#creating a temp outfile
           Try(tempOut <- sub( "\\\\","/",tempOut)) #changing double backslach with slash
   
           #######################################################
           #defining the APT tool gene/exon level calculaiton methods
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(ttIfDialog<-tktoplevel(.affylmGUIglobals$ttMain))
           Try(tkwm.deiconify(ttIfDialog))
           Try(tkgrab.set(ttIfDialog))
           Try(tkfocus(ttIfDialog))
           Try(tkwm.title(ttIfDialog,"APT tools intensity summaries"))
           Try(tkgrid(tklabel(ttIfDialog,text="    ")))
           Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
           Try(HowManyQuestion1 <- tklabel(frame1,text="Gene level methods",font=.affylmGUIglobals$affylmGUIfont2))
           Try(tkgrid(HowManyQuestion1))
           Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
           Try(geneTcl <- tclVar("rma-sketch"))
           Try(I0.but  <- tkradiobutton(frame1,text="rma-sketch",variable=geneTcl,value="rma-sketch",font=.affylmGUIglobals$affylmGUIfont2))
           Try(I1.but  <- tkradiobutton(frame1,text="iter-plier",variable=geneTcl,value="iter-plier",font=.affylmGUIglobals$affylmGUIfont2))
           Try(I2.but <- tkradiobutton(frame1,text="rma quantile norm",variable=geneTcl,value="rma",font=.affylmGUIglobals$affylmGUIfont2))
           Try(I3.but <- tkradiobutton(frame1,text="rma no norm",variable=geneTcl,value="rma-bg",font=.affylmGUIglobals$affylmGUIfont2))

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

           #Try(frame2 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
           #Try(exonLabel <- tklabel(frame2,text="Exon level methods",font=.affylmGUIglobals$affylmGUIfont2))
           #Try(tkgrid(exonLabel,sticky="w"))
           #Try(tkgrid.configure(exonLabel,sticky="w"))
           #Try(exonTcl <- tclVar("rma-sketch"))
           #Try(F0.but <- tkradiobutton(frame2,text="rma-sketch",variable=exonTcl,value="rma-sketch",font=.affylmGUIglobals$affylmGUIfont2))
           #Try(F1.but <- tkradiobutton(frame2,text="plier-gcbg-sketch",variable=exonTcl,value="plier-gcbg-sketch",font=.affylmGUIglobals$affylmGUIfont2))

           #Try(tkgrid(F0.but,sticky="w"))
           #Try(tkgrid(F1.but,sticky="w"))
           #Try(tkgrid.configure(exonLabel,F0.but,F1.but,sticky="w"))
           Try(ReturnValX <<- "")
           Try(onOK <- function()
           {
                ReturnVal1 <- tclvalue(geneTcl)
                ReturnVal2 <- "" #not used in gene 1.0 ST
                Try(ReturnValX <<- paste(ReturnVal1, ReturnVal2, sep=";"))
                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))

            ##gene/exon routines 
            if(ReturnValX == ""){
                      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                      Try(tkfocus(.affylmGUIglobals$ttMain))
                      Try(return())
            }
           Try(tmpVal<-strsplit(ReturnValX, ";"))
           Try(gene.summary <- tmpVal[[1]][1])
           #Try(exon.summary <- tmpVal[[1]][2])

           if(gene.summary == "rma-sketch"){
                    Try(typeOfSummary <-  "rma-sketch")
                    Try(gene.rma.sketch <- paste(aptDir,"/bin/apt-probeset-summarize", " -a ", typeOfSummary," -p ", pgf.name, " -c ", clf.name, " -m ", exonlib.name, " -o ", tempOut," --cel-files ", tempTarget, sep=""))
                    Try(cat("\nGene level probe sets summary started\n"))
                    Try(system(gene.rma.sketch, wait = T))#assign to gene summary one of the method implemented for gene summary
                    Try(cat("\nGene level probe sets summary ended\n"))
           }
           if(gene.summary == "rma"){
                    Try(typeOfSummary <-  "rma")
                    Try(gene.rma.sketch <- paste(aptDir,"/bin/apt-probeset-summarize", " -a ", typeOfSummary," -p ", pgf.name, " -c ", clf.name, " -m ", exonlib.name, " -o ", tempOut," --cel-files ", tempTarget, sep=""))
                    Try(cat("\nGene level probe sets summary started\n"))
                    Try(system(gene.rma.sketch, wait = T))#assign to gene summary one of the method implemented for gene summary
                    Try(cat("\nGene level probe sets summary ended\n"))
           }
           if(gene.summary == "rma-bg"){
                    Try(typeOfSummary <-  "rma-bg,pm-only,med-polish")
                    Try(gene.rma.sketch <- paste(aptDir,"/bin/apt-probeset-summarize", " -a ", typeOfSummary," -p ", pgf.name, " -c ", clf.name, " -m ", exonlib.name, " -o ", tempOut," --cel-files ", tempTarget, sep=""))
                    Try(cat("\nGene level probe sets summary started\n"))
                    Try(system(gene.rma.sketch, wait = T))#assign to gene summary one of the method implemented for gene summary
                    Try(cat("\nGene level probe sets summary ended\n"))
           }
           if(gene.summary == "iter-plier"){
                    Try(typeOfSummary <-  "iter-plier")
                    if(tclvalue(glibVal)=="yes"){
                          Try(libVersion <- paste(whichLib[[1]][1], "-1_1", sep=""))
                          Try(bgfile.name <- paste(libDir, content.libDir[intersect(grep('.bgp$',content.libDir), grep(libVersion,content.libDir))], sep=""))
                    }  else if(tclvalue(glibVal)=="no"){
                          Try(libVersion <- paste(whichLib[[1]][1], "-1_0", sep=""))
                          Try(bgfile.name <- paste(libDir, content.libDir[intersect(grep('.bgp$',content.libDir), grep(libVersion,content.libDir))], sep=""))
                    }
                    Try(gene.iterplier <- paste(aptDir,"/bin/apt-probeset-summarize", " -a ", "quant-norm.sketch=50000.bioc=false,pm-gcbg,", typeOfSummary," -p ", pgf.name," -b ", bgfile.name," -c ", clf.name, " -m ", exonlib.name," -o ", tempOut," --cel-files ", tempTarget, sep=""))
                    Try(cat("\nGene level probe sets summary started\n"))
                    Try(system(gene.iterplier, wait = T))#assign to gene summary one of the method implemented for gene summary
                    Try(cat("\nGene level probe sets summary ended\n"))
           }

           ##########################################################
           #it is necessary to exchange "-" with "." in the FileNames of Targets 
           #since R will convert "-" into "." for the header of the data file
           #e.g. name in the header of the data file 211_MB-211.rma-gene-core-Signal
           # after reading in R:  211_MB.211.rma.gene.core.Signal
           #therefore the FileName  211_MB-211 should be converted in 211_MB.211
           Try(tmp<- apply(Targets, 1,function(x){sub("-",".",x[2])}))
           Try(Targets[,2] <- tmp )
           ############################################################
  
           Try(rownames(Targets) <- Targets$FileName) 
           Try(var.tmp.pd<-data.frame(names(Targets)))
           Try(names(var.tmp.pd)<-"labelDescription" )
           Try(rownames(var.tmp.pd)<-names(Targets))
           Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
           #Try(target.array.names <- sub(".CEL", "", tmp1.pd$FileName))
           Try(target.array.names <- tmp1.pd$FileName)
           Try(tempOut0 <- paste(typeOfSummary ,".summary.txt",sep=""))
           Try(tempOut0 <- gsub(",", ".", tempOut0))
           Try(content.outDir <- dir(tempOut))
           Try(tempOut1  <- grep(tempOut0, content.outDir))
           Try(my.exons <-read.table(paste(tempOut, "/", content.outDir[tempOut1], sep=""), sep="\t", header=T, as.is=TRUE, row.names=1))#loading gene level data
           Try(my.exons.array.names <- NULL)
           Try(    for( i in 1:length(target.array.names)){
                             if(length(grep(target.array.names[i], names(my.exons))) == 1){
                                    my.exons.array.names[i] <- grep(target.array.names[i], names(my.exons))
                             } else{
                                    error.message <- paste("\nERROR! Filenames are not unique!\n", target.array.names[i], " is a substring of ", paste(names(my.exons)[grep(target.array.names[i], names(my.exons))],sep=","), "\n", sep="")
                                    cat("\nERROR! Filenames are not unique!\n")
                                    cat(error.message)
                                    cat("\nYou need to modify filenames since the function is unable to correctly associate arrays to target Filenames\n")
                                    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                                    return()
                             }
               })
           Try(my.exons <- my.exons[,my.exons.array.names])
           Try(names(my.exons) <-  tmp1.pd$FileName)
		   Try(annLib <- "")
           if(gene.summary == "iter-plier"){
                    Try(if(whichLib[[1]][1] == "HuGene") annLib <- "hugene10sttranscriptcluster.db")
                    Try(if(whichLib[[1]][1] == "MoGene") annLib <- "mogene10sttranscriptcluster.db")
                    Try(if(whichLib[[1]][1] == "RaGene") annLib <- "ragene10sttranscriptcluster.db")
                    Try(NormalizedAffyData <- new("ExpressionSet", exprs=log2(as.matrix(my.exons)), phenoData=tmp1.pd, annotation=annLib))
                    if(!validObject(NormalizedAffyData)){
                           Try(tkmessageBox(title="Gene 1.0 ST  APT calculation",message="Check the APT log in the main R window\nNo valid ExpressionSet could be created!",icon="error"))
                				   Try(return())
                    }
           } else {
                    Try(if(whichLib[[1]][1] == "HuGene") annLib <- "hugene10sttranscriptcluster.db")
                    Try(if(whichLib[[1]][1] == "MoGene") annLib <- "mogene10sttranscriptcluster.db")
                    Try(if(whichLib[[1]][1] == "RaGene") annLib <- "ragene10sttranscriptcluster.db")
                    Try(NormalizedAffyData <- new("ExpressionSet", exprs=as.matrix(my.exons), phenoData=tmp1.pd, annotation=annLib))
                    if(!validObject(NormalizedAffyData)){
                           Try(tkmessageBox(title="Gene 1.0 ST APT calculation",message="Check the APT log in the main R window\nNo valid ExpressionSet could be created!",icon="error"))
                			     Try(return())
                    }

           }
	         Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
	         Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
           Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	         Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Gene 1.0 ST data available",font=.affylmGUIglobals$affylmGUIfontTree))
	         Try(if("Name" %in% colnames(Targets))
	         SlideNamesVec <- Targets$Name)
	         Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	         Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
           Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
           Try(ReturnVal <- GetlimmaDataSetName())
	         if(ReturnVal==0) return(0)
	         return(1)
           Try(cat("\nGene level probe sets summary ended\n"))
  } else if(tclvalue(exonVal)!="yes" & whichArrayPlatform=="EXON"){
           ##########################################################
           #it is necessary to exchange "-" with "." in the FileNames of Targets 
           #since R will convert "-" into "." for the header of the data file
           #e.g. name in the header of the data file 211_MB-211.rma-gene-core-Signal
           # after reading in R:  211_MB.211.rma.gene.core.Signal
           #therefore the FileName  211_MB-211 should be converted in 211_MB.211
           Try(tkmessageBox(title="Probe sets intensities by Affymetrix Expression Console",message="Loading gene/exon data generated by Expression Console",icon="info"))
                             
           Try(tmp<- apply(Targets, 1,function(x){sub("-",".",x[2])}))
           Try(Targets[,2] <- tmp )
           ############################################################
  
           Try(rownames(Targets) <- Targets$FileName) 
           Try(var.tmp.pd<-data.frame(names(Targets)))
           Try(names(var.tmp.pd)<-"labelDescription" )
           Try(rownames(var.tmp.pd)<-names(Targets))
           Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
           Try(target.array.names <- sub(".CEL", "", tmp1.pd$FileName))
           #Try(target.array.names <- tmp1.pd$FileName)
           Try(my.exons <- OpenExonFile())#loading gene level data
           Try(my.exons.array.names <- NULL)
           Try(    for( i in 1:length(target.array.names)){
                             if(length(grep(target.array.names[i], names(my.exons))) == 1){
                                    my.exons.array.names[i] <- grep(target.array.names[i], names(my.exons))
                             } else{
                                    error.message <- paste("\nERROR! Filenames are not unique!\n", target.array.names[i], " is a substring of ", paste(names(my.exons)[grep(target.array.names[i], names(my.exons))],sep=","), "\n", sep="")
                                    cat("\nERROR! Filenames are not unique!\n")
                                    cat(error.message)
                                    cat("\nYou need to modify filenames since the function is unable to correctly associate arrays to target Filenames\n")
                                    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                                    return()
                             }
               })
           Try(my.exons <- my.exons[,my.exons.array.names])
           Try(names(my.exons) <-  tmp1.pd$FileName)
           Try(NormalizedAffyData <- new("ExpressionSet", exprs=as.matrix(my.exons), phenoData=tmp1.pd, annotation=""))
	         Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
	         Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
           Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	         Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Gene level exon data available",font=.affylmGUIglobals$affylmGUIfontTree))

	         Try(if("Name" %in% colnames(Targets))
	         SlideNamesVec <- Targets$Name)
	         Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	         Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))

           Try(my.exons <- OpenExonProbeFile())#loading exon level data
           Try(my.exons.array.names <- NULL)
           Try(    for( i in 1:length(target.array.names)){
                             if(length(grep(target.array.names[i], names(my.exons))) == 1){
                                    my.exons.array.names[i] <- grep(target.array.names[i], names(my.exons))
                             } else{
                                    error.message <- paste("\nERROR! Filenames are not unique!\n", target.array.names[i], " is a substring of ", paste(names(my.exons)[grep(target.array.names[i], names(my.exons))],sep=","), "\n", sep="")
                                    cat("\nERROR! Filenames are not unique!\n")
                                    cat(error.message)
                                    cat("\nYou need to modify filenames since the function is unable to correctly associate arrays to target Filenames\n")
                                    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                                    return()
                             }
               })
           Try(my.exons <- my.exons[,my.exons.array.names])
           Try(names(my.exons) <-  tmp1.pd$FileName)
           Try(ExonAffyData <- new("ExpressionSet", exprs=as.matrix(my.exons), phenoData=tmp1.pd, annotation=""))
	         Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	         Try(assign("exonAffyData.Available",TRUE,affylmGUIenvironment))
	         Try(assign("exonAffyData",ExonAffyData,affylmGUIenvironment))

	         Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))
	         Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Exon level data available",font=.affylmGUIglobals$affylmGUIfontTree))
           Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	         Try(ReturnVal <- GetlimmaDataSetName())
	         if(ReturnVal==0) return(0)
	         return(1)
     }

}
#loading the tab delimited file
OpenExonFile <- function(){
          Try(tkmessageBox(title="Exon analysis",message="Open the file, containing GENE level summary data, exported from Expression console"))  
          my.exons <- OpenAFile()
}

#loading the tab delimited file
OpenExonProbeFile <- function(){
          Try(tkmessageBox(title="Exon analysis",message="Open the file, containing the EXON level summary data, exported from Expression console"))  
          my.exons <- OpenAFile()
}


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


OpenLimmaFile <- function() OpenALimmaFile()

OpenALimmaFile <- function(FileName)
{
	Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
	Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
	Try(if(missing(FileName))
	{
		Try(tempLimmaFileName <- tclvalue(tkgetOpenFile(filetypes="{{Limma Files} {.lma}} {{All files} *}")))
		if(!nchar(tempLimmaFileName))
		{
			tkfocus(.affylmGUIglobals$ttMain)
			return()
		}
	}
	else
		tempLimmaFileName <- FileName)

	Try(if(!nchar(tempLimmaFileName))
	{
		tkfocus(.affylmGUIglobals$ttMain)
		return()
	})
	Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
	Try(if(limmaDataSetNameText!="Untitled")
	{
			Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled")	LimmaFileName <- limmaDataSetNameText)	# Local assignment only
	#		Try(mbVal <- tkmessageBox(title="Open File",
	#					message=paste("Save changes to ",fixSeps(LimmaFileName),"?",sep=""),
	#					icon="question",type="yesnocancel",default="yes"))
	#		Try(if(tclvalue(mbVal)=="yes")
	#				SaveLimmaFile())
	#		Try(if(tclvalue(mbVal)=="cancel")
	#				return())
	})
	Try(LimmaFileName <- tempLimmaFileName)
	Try(assign("LimmaFileName",LimmaFileName,affylmGUIenvironment))

	#Try(recentFilesFileName <- system.file("etc/recent-files.txt",package="oneChannelGUI"))
	#Try(recentFiles <- readLines(recentFilesFileName))

	#Try(recentFiles <- gsub("\\\\","/",recentFiles))

	# Remove any blank lines:
	#Try(blanks <- grep("^[ \t\n]*$",recentFiles))
	#Try(if(length(blanks)>0)
	#	recentFiles <- recentFiles[-blanks])
	#Try(numRecentFiles <- length(recentFiles))

	#Try(if(length(grep(LimmaFileName,recentFiles))==0)
 #		recentFiles <- c(LimmaFileName,recentFiles))
	#Try(if(length(recentFiles)>4)
	#	recentFiles <- recentFiles[1:4])
	#try(writeLines(con=recentFilesFileName,recentFiles),TRUE)
	#Try(numRecentFiles <- length(recentFiles))

	#Try(if(numRecentFiles>0)
	#{
	#	Try(fileMenu <- .affylmGUIglobals$menus$fileMenu)
	#	Try(workingDirIndex <- as.numeric(tclvalue(tkindex(.affylmGUIglobals$menus$fileMenu,"affylmGUI: Working Directory"))))
	#	Try(exitIndex <- as.numeric(tclvalue(tkindex(.affylmGUIglobals$menus$fileMenu,"affylmGUI: Exit"))))
	#	Try(if(exitIndex==workingDirIndex+2)
	#		Try(numRecentFilesInMenu <- 0)
	#	else
	#	{
	#		Try(numRecentFilesInMenu <- exitIndex - workingDirIndex - 3)
	#		Try(for (i in (1:(numRecentFilesInMenu+1)))
	#			Try(tkdelete(fileMenu,workingDirIndex+2)))
	#	})
	#	Try(tkinsert(fileMenu,workingDirIndex+1,"separator"))

	#	Try(for (i in (numRecentFiles:1))
	#	{
	#		Try(label <- recentFiles[i])
	#		Try(fileNameOnly <- strsplit(label,"/")[[1]])
	#		Try(fileNameOnly <- fileNameOnly[length(fileNameOnly)])
	#		Try(if(nchar(recentFiles[i])>60)
	#				label <- paste(".../",fileNameOnly))
	#		Try(eval(parse(text=paste("assign(\".OpenALimmaFile_",i,"\",function() OpenALimmaFile(\"",recentFiles[i],"\"),.GlobalEnv)",sep=""))))
	#		Try(if(.Platform$OS.type=="windows")
	#			Try(tkinsert(fileMenu,workingDirIndex+2,"command",label=paste(i,". ",gsub("/","\\\\",label),sep=""),
	#				command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))))
	#		else
	#			Try(tkinsert(fileMenu,workingDirIndex+2,"command",label=paste(i,". ",label,sep=""),
	#				command=eval(parse(text=paste(".OpenALimmaFile_",i,sep=""))))))
	#	})
	#})

	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkfocus(.affylmGUIglobals$ttMain))

	Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))
	Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
	Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
	Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))

# Using existing NumContrastParameterizations, NOT the one loaded from the .lma file.
# (We haven't loaded it yet.)
	Try(OldNumParameters <- NumParameters)

	Try(if(NumContrastParameterizations>0)
		Try(for (contrastParameterizationIndex in (1:NumContrastParameterizations))
		{
			Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
			Try(ContrastParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
			Try(tkdelete(.affylmGUIglobals$ContrastParameterizationTREE,ContrastParameterizationNameNode))
			Try(assign("ContrastParameterizationList",deleteItemFromList(ContrastParameterizationList,ContrastParameterizationNameNode),affylmGUIenvironment))
		}))

	# Load the RData File whose name is "LimmaFileName"
	Try(load(LimmaFileName,envir=affylmGUIenvironment))

	# The user may have changed the filename in the operating system since the last save.
	Try(LimmaFileName <- tempLimmaFileName)
	Try(assign("LimmaFileName",LimmaFileName,affylmGUIenvironment))

	Try(limmaDataSetNameText <- get("limmaDataSetNameText" , envir=affylmGUIenvironment))
	Try(ContrastParameterizationNamesVec <- get("ContrastParameterizationNamesVec", envir=affylmGUIenvironment))
	Try(NumContrastParameterizations <- get("NumContrastParameterizations", envir=affylmGUIenvironment))
	Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
	Try(NumParameters <- get("NumParameters" , envir=affylmGUIenvironment))
	Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))

	Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
	Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
	Try(if(.Platform$OS.type=="windows")
		Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",gsub("/","\\\\",LimmaFileName))))
	else
		Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",LimmaFileName))))
	Try(assign("limmaDataSetNameText",limmaDataSetNameText,affylmGUIenvironment))
	Try(tclvalue(.affylmGUIglobals$limmaDataSetNameTcl) <- limmaDataSetNameText)

	Try(tkdelete(.affylmGUIglobals$mainTree,"RawAffyData.Status"))
	Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFit.Status"))
###################new items
  Try(tkdelete(.affylmGUIglobals$mainTree,"maSIgProData.Status"))
	Try(tkdelete(.affylmGUIglobals$mainTree,"PLM.Status"))
	Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))
  Try(tkdelete(.affylmGUIglobals$mainTree,"AptDabg.Status"))
  Try(tkdelete(.affylmGUIglobals$mainTree,"AptMidas.Status"))            
	Try(tkdelete(.affylmGUIglobals$mainTree,"spliceIndex.Status"))
  Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.e.Status"))            
  Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.g.Status"))            
  Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
  Try(tkdelete(.affylmGUIglobals$mainTree,"classification.Status"))          
  #NGS
	Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))            
	

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

	
	Try(if(OldNumParameters>0)
		Try(for (i in (1:OldNumParameters))
			Try(tkdelete(.affylmGUIglobals$mainTree,paste("Parameters.Status.",i,sep=""))))
	else
			Try(tkdelete(.affylmGUIglobals$mainTree,"Parameters.Status.1")))
	Try(if(NumContrastParameterizations>0)
		Try(for (i in (1:NumContrastParameterizations))
			Try(tkdelete(.affylmGUIglobals$mainTree,paste("ContrastParameterizations.Status.",i,sep=""))))
	else
			Try(tkdelete(.affylmGUIglobals$mainTree,"ContrastParameterizations.Status.1")))

	Try(RawAffyData.Available						<- get("RawAffyData.Available" , envir=affylmGUIenvironment))
	Try(NormalizedAffyData.Available		 <- get("NormalizedAffyData.Available" , envir=affylmGUIenvironment))
	Try(LinearModelFit.Available				 <- get("LinearModelFit.Available" , envir=affylmGUIenvironment))
##############################
  Try(maSigProSigs.Available						<- get("maSigProSigs.Available" , envir=affylmGUIenvironment))
	Try(Pset.Available		              <- get("Pset.Available" , envir=affylmGUIenvironment))
	Try(exonAffyData.Available				 <- get("exonAffyData.Available" , envir=affylmGUIenvironment))
	Try(dabg.Available				         <- get("dabg.Available" , envir=affylmGUIenvironment))
	Try(midas.p.Available		     		 <- get("midas.p.Available" , envir=affylmGUIenvironment))
	Try(spliceIndexData.Available				 <- get("spliceIndexData.Available" , envir=affylmGUIenvironment))
	Try(AltSplRP.e.Available				 <- get("AltSplRP.e.Available" , envir=affylmGUIenvironment))
	Try(AltSplRP.g.Available				 <- get("AltSplRP.g.Available" , envir=affylmGUIenvironment))
	Try(MLdesign.Available				 <- get("MLdesign.Available" , envir=affylmGUIenvironment))
	Try(metaData.Available				 <- get("metaData.Available" , envir=affylmGUIenvironment))
	#NGS
	Try(NGS.Available				 <- get("NGS.Available" , envir=affylmGUIenvironment))
##############################

	Try(if(RawAffyData.Available)
		Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree))
	else
		Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))		)
	Try(if(exists("NormMethod",envir=affylmGUIenvironment))
		Try(NormMethod <- get("NormMethod",envir=affylmGUIenvironment))
	else
		Try(NormMethod <- "RMA"))
	Try(if(NormalizedAffyData.Available)
		Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text=paste("Available (",NormMethod,")",sep=""),font=.affylmGUIglobals$affylmGUIfontTree))
	else
		Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))		)
	Try(if(LinearModelFit.Available)
		Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status",text="Available",font=.affylmGUIglobals$affylmGUIfontTree))
	else
		Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree)))

###########################################
	Try(if(maSigProSigs.Available){
		     tkinsert(.affylmGUIglobals$mainTree,"end","maSIgProData","maSIgProData.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree)
	       require(maSigPro) || stop("library maSigPro could not be found !")
      }
      else
		     tkinsert(.affylmGUIglobals$mainTree,"end","maSIgProData","maSIgProData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree)
 )
	Try(if(exonAffyData.Available)
		      tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree)
	  else
		      tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree)
	)

	Try(if(dabg.Available)
          tkinsert(.affylmGUIglobals$mainTree,"end","AptDabg","AptDabg.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree)
	  else
		      tkinsert(.affylmGUIglobals$mainTree,"end","AptDabg","AptDabg.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree)
	)

	Try(if(midas.p.Available)
          tkinsert(.affylmGUIglobals$mainTree,"end","AptMidas","AptMidas.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree)
	  else
		      tkinsert(.affylmGUIglobals$mainTree,"end","AptMidas","AptMidas.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree)
	)

  Try(if(spliceIndexData.Available)
          tkinsert(.affylmGUIglobals$mainTree,"end","spliceIndex","spliceIndex.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree)
      else
		      tkinsert(.affylmGUIglobals$mainTree,"end","spliceIndex","spliceIndex.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree)
  )
  
  Try(if(AltSplRP.e.Available)
          tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.e.Status" ,text="Available at exon level",font=.affylmGUIglobals$affylmGUIfontTree)
      else
          tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.e.Status" ,text="Not Available at exon level",font=.affylmGUIglobals$affylmGUIfontTree)
  )
  
  Try(if(AltSplRP.g.Available)
          tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.g.Status" ,text="Available at gene level",font=.affylmGUIglobals$affylmGUIfontTree)
      else
          tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.g.Status" ,text="Not Available at gene level",font=.affylmGUIglobals$affylmGUIfontTree)
  )
  
  Try(if(MLdesign.Available)
          tkinsert(.affylmGUIglobals$mainTree,"end","classification","classification.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree)
      else
          tkinsert(.affylmGUIglobals$mainTree,"end","classification","classification.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree)
  )
  
  Try(if(metaData.Available)
          tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree)
      else
          tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree)
  )
    


  
  Try(if(Pset.Available){
		      tkinsert(.affylmGUIglobals$mainTree,"end","PLM","PLM.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree)
          require(affyPLM) || stop("library affyPLM could not be found !")
      }
	    else
		      tkinsert(.affylmGUIglobals$mainTree,"end","PLM","PLM.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree)
)

Try(if(NGS.Available){
		      tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree)
        #  require(Biostrings) || stop("library Biostrings could not be found !")
      }
	    else
		      tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree)
)
##########################################

	Try(if(LinearModelFit.Available)
	{
		Try(design <- get("design",affylmGUIenvironment))
		Try(if(NumParameters>0)
		{
			for (i in (1:NumParameters))
				Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters",
					paste("Parameters.Status.",i,sep=""),text=colnames(design)[i],font=.affylmGUIglobals$affylmGUIfontTree))
		}
		else
			Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters","Parameters.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)))
	}
	else
	{
		Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters","Parameters.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree))
	})

	Try(if(NumContrastParameterizations>0)
	{
		for (contrastParameterizationIndex in (1:NumContrastParameterizations))
		{
			Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
			Try(ContrastParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
			Try(ContrastParameterizationsStatusNameNode <- paste("ContrastParameterizations.Status.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
			Try(tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations",ContrastParameterizationsStatusNameNode ,text=ContrastParameterizationNamesVec[contrastParameterizationIndex],font=.affylmGUIglobals$affylmGUIfontTree))
			Try(contrastsMatrix <- ContrastParameterizationList[[1]]$contrastsMatrixInList$contrasts)
			Try(ContrastsNames <- colnames(contrastsMatrix))
			Try(ContrastParameterizationNameText <- ContrastParameterizationList[[1]]$ContrastParameterizationNameText)
			Try(tkinsert(.affylmGUIglobals$ContrastParameterizationTREE,"end","root",ContrastParameterizationNameNode,text=ContrastParameterizationNameText,font=.affylmGUIglobals$affylmGUIfontTree))
			Try(ContrastsNode <- paste("ContrastsNode.",.affylmGUIglobals$ContrastParameterizationTREEIndex))

			Try(tkinsert(.affylmGUIglobals$ContrastParameterizationTREE,"end",ContrastParameterizationNameNode,ContrastsNode,text="Contrasts",font=.affylmGUIglobals$affylmGUIfontTree))

			Try(NumContrastsInContrastParameterization <- length(ContrastsNames))
			Try(for (j in (1:NumContrastsInContrastParameterization))
				Try(tkinsert(.affylmGUIglobals$ContrastParameterizationTREE,"end",ContrastsNode,paste("Contrasts.",.affylmGUIglobals$ContrastParameterizationTREEIndex,".",j,sep=""),text=ContrastsNames[j],font=.affylmGUIglobals$affylmGUIfontTree)))

			Try(LinearModelFitNode			 <- paste("LinearModelFitNode.",.affylmGUIglobals$ContrastParameterizationTREEIndex))
			Try(LinearModelFitStatusNode <- paste("LinearModelFitStatusNode.",.affylmGUIglobals$ContrastParameterizationTREEIndex))
			Try(tkinsert(.affylmGUIglobals$ContrastParameterizationTREE,"end",ContrastParameterizationNameNode,LinearModelFitNode,text="Linear Model Fit",font=.affylmGUIglobals$affylmGUIfontTree))
			Try(tkinsert(.affylmGUIglobals$ContrastParameterizationTREE,"end",LinearModelFitNode,LinearModelFitStatusNode,text="Available",font=.affylmGUIglobals$affylmGUIfontTree))

			Try(if(("eb" %in% names(ContrastParameterizationList[[contrastParameterizationIndex]]))&&
												length(ContrastParameterizationList[[contrastParameterizationIndex]]$eb)>0)
				Try(ebayesAvailable <- TRUE)
			else
				Try(ebayesAvailable <- FALSE))

			Try(EmpiricalBayesNode			 <- paste("EmpiricalBayesNode.",.affylmGUIglobals$ContrastParameterizationTREEIndex))
			Try(EmpiricalBayesStatusNode <- paste("EmpiricalBayesStatusNode.",.affylmGUIglobals$ContrastParameterizationTREEIndex))
			Try(tkinsert(.affylmGUIglobals$ContrastParameterizationTREE,"end",ContrastParameterizationNameNode,EmpiricalBayesNode,text="Empirical Bayes Statistics",font=.affylmGUIglobals$affylmGUIfontTree))
			Try(if(ebayesAvailable==TRUE)
				Try(tkinsert(.affylmGUIglobals$ContrastParameterizationTREE,"end",EmpiricalBayesNode,EmpiricalBayesStatusNode,text="Available",font=.affylmGUIglobals$affylmGUIfontTree))
			else
				Try(tkinsert(.affylmGUIglobals$ContrastParameterizationTREE,"end",EmpiricalBayesNode,EmpiricalBayesStatusNode,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree)))

		}
	}
	else
		Try(tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)))
  #####################################################################
  #updating the localData info after opening a new .lma This is useful 
  #if the same .lma is opened on a new comuter with a different localization of apt and libs files
  Try(localdata  <- paste(path.package("oneChannelGUI", quiet = FALSE), "/etc/localData.txt", sep=""))
  Try(libDirLocation <- paste(path.package("oneChannelGUI", quiet = FALSE), "/affylibs/", sep = ""))
  Try(myinfo <- read.table(localdata, sep="\t", header=F, as.is=T))
  Try(aptDir <- myinfo[which(myinfo[,1]=="aptDir"),2])
  Try(assign("libDirLocation", libDirLocation, affylmGUIenvironment))
  Try(assign("libDir", libDirLocation, affylmGUIenvironment))
  Try(assign("aptDir", aptDir ,affylmGUIenvironment))
  ####################################################################

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

  Try(changeMenu())#place the right menu depending on the kind of platform array under analysis
}
################################################################################

#if annotation lib is not present in the data set , like in the case of loading the data as tab delimted file
#annotation library can be added to the annotation field of ExpressionSet object
"addAnnLib" <- function(){
   NormalizedAffyData.Available     <- get("NormalizedAffyData.Available" , envir=affylmGUIenvironment)
   if(NormalizedAffyData.Available){
         Try(x <- get("NormalizedAffyData",envir=affylmGUIenvironment))

         Try(ttAnnLibName<-tktoplevel(.affylmGUIglobals$ttMain))
         Try(tkwm.deiconify(ttAnnLibName))
         Try(tkgrab.set(ttAnnLibName))
         Try(tkfocus(ttAnnLibName))
         Try(tkwm.title(ttAnnLibName,"Bioconductor Annotation library"))
         Try(tkgrid(tklabel(ttAnnLibName,text="    ")))
         Try(AnnLibNameText <- "")
         Try(Local.AnnLibName <- tclVar(init=AnnLibNameText))
         Try(entry.AnnLibName <-tkentry(ttAnnLibName,width="20",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.AnnLibName,bg="white"))
         Try(tkgrid(tklabel(ttAnnLibName,text="Please enter the code of the Bioconductor\nAnnotation Library.",font=.affylmGUIglobals$affylmGUIfont2)))
         Try(tkgrid(entry.AnnLibName))
         onOK <- function()
         {
               Try(AnnLibNameText <- tclvalue(Local.AnnLibName))
               
               if(nchar(AnnLibNameText)==0)
                  AnnLibNameText <- ""
               Try(x@annotation <- AnnLibNameText)
               Try(assign("NormalizedAffyData",x,affylmGUIenvironment))
               Try(tkgrab.release(ttAnnLibName));Try(tkdestroy(ttAnnLibName));Try(tkfocus(.affylmGUIglobals$ttMain))
         }
         Try(OK.but <-tkbutton(ttAnnLibName,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
         Try(tkgrid(tklabel(ttAnnLibName,text="    ")))
         Try(tkgrid(OK.but))
         Try(tkgrid.configure(OK.but))
         Try(tkgrid(tklabel(ttAnnLibName,text="       ")))
         Try(tkfocus(entry.AnnLibName))
         Try(tkbind(entry.AnnLibName, "<Return>",onOK))
         Try(tkbind(ttAnnLibName, "<Destroy>", function(){Try(tkgrab.release(ttAnnLibName));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
         Try(tkwait.window(ttAnnLibName))
         Try(tkfocus(.affylmGUIglobals$ttMain))
   } else {
            Try(tkmessageBox(title="Bioconductor annotation library",message="Normalized data are not loaded!\n Annotation  Library info cannot be attached.",icon="error",type="ok"))
   }



}
################################################################################
NewLimmaFileNGS <- function(){
	####################################################
	Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(ttGetArray <- tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttGetArray))
	Try(tkgrab.set(ttGetArray))
	Try(tkfocus(ttGetArray))
	Try(tkwm.title(ttGetArray,"Selecting the NGS analysis"))
	#
	Try(tkgrid(tklabel(ttGetArray,text="    ")))
	Try(ArrayTcl <- tclVar("NGS"))
	Try(rbmiRNA <- tkradiobutton(ttGetArray,text="miRNA-seq primary mapping with Bowtie/Picard",variable=ArrayTcl,value="miRNA",font=.affylmGUIglobals$affylmGUIfont2))
	Try(rbmRNA <- tkradiobutton(ttGetArray,text="RNA-seq primary mapping with Bowtie/Picard",variable=ArrayTcl,value="mRNA",font=.affylmGUIglobals$affylmGUIfont2))
	Try(rbREFORMAT <- tkradiobutton(ttGetArray,text="Reformating primary miRNA-seq data generated with SHRIMP, MicroRazerS, miRanalyzer mapping tools",variable=ArrayTcl,value="REFORMAT",font=.affylmGUIglobals$affylmGUIfont2))
	Try(rbNGS <- tkradiobutton(ttGetArray,text="Importing primary mapping data in oneChannelGUI.\nAccepted formats:\n\tmiRNA or mRNA BAM files generated by oneChannelGUI,\n\toneChannelGUI reformatted SHRIMP data, \n\tmature miRNAs from miRanalyser, \n\toneChannelGUI reformatted MicroRazerS data, \n\tmature miRNAs from miRProf, \n\tmature miRNAs from miRExpress, \n\tSHRIMP 2.1 data generated using miRBase as reference.",variable=ArrayTcl,value="NGS",font=.affylmGUIglobals$affylmGUIfont2))
	
  Try(tkgrid(tklabel(ttGetArray,text="    "),rbmiRNA))
  Try(tkgrid(tklabel(ttGetArray,text="    "),rbmRNA))
	Try(tkgrid(tklabel(ttGetArray,text="    "),rbREFORMAT))
	Try(tkgrid(tklabel(ttGetArray,text="    "),rbNGS))
	Try(tkgrid.configure(rbmiRNA, rbmRNA,rbREFORMAT,rbNGS,columnspan=2,sticky="w"))
	Try(tkgrid(tklabel(ttGetArray,text="    "),tklabel(ttGetArray,text="    ")))
	#
	Try(ReturnVal <- "")
	Try(
		onCancel <- function() {
			Try(ReturnVal <<- "");
			Try(tkgrab.release(ttGetArray));
			Try(tkdestroy(ttGetArray));
			Try(tkfocus(.affylmGUIglobals$ttMain))
			Try(return())
		}
	)
	Try(
		onOK <- function() {
			Try(ReturnVal <<- tclvalue(ArrayTcl));
			Try(tkgrab.release(ttGetArray));
			Try(tkdestroy(ttGetArray));
			Try(tkfocus(.affylmGUIglobals$ttMain))
		}
	)
	#
	Try(OK.but     <- tkbutton(ttGetArray,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	Try(Cancel.but <- tkbutton(ttGetArray,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
	#
	Try(tkgrid(tklabel(ttGetArray,text="    "),OK.but,Cancel.but,tklabel(ttGetArray,text="    ")))
	Try(tkgrid.configure(OK.but,sticky="e"))
	Try(tkgrid.configure(Cancel.but,sticky="w"))
	Try(tkgrid(tklabel(ttGetArray,text="    ")))
	#
	Try(tkbind(ttGetArray,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetArray));Try(tkfocus(.affylmGUIglobals$ttMain));}))
	Try(tkbind(OK.but, "<Return>",onOK))
	Try(tkbind(Cancel.but, "<Return>",onCancel))
	#
	Try(tkwait.window(ttGetArray))
	Try(tkfocus(.affylmGUIglobals$ttMain))
#selecting the array type
  Try(
    if(ReturnVal=="miRNA"){
                     Try(assign("whichArrayPlatform","NGS",affylmGUIenvironment))
##############initialization variables start
                        Try(tt <- "")
                        Try(assign("illuData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("illuData",tt,affylmGUIenvironment))

                        Try(assign("RawAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("NormalizedAffyData.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("unfilteredData.location", tt, affylmGUIenvironment))
                        Try(assign("geoPlatform",  tt, env=affylmGUIenvironment))

                        Try(assign("metaData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("metaData",tt,affylmGUIenvironment))

                        Try(assign("exprConsoleLibs.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exprConsoleLibs", tt ,affylmGUIenvironment))#locate here the library files as a list of data.frames

                        assign("libDir.Available",FALSE,affylmGUIenvironment)
                        assign("libDir", tt ,affylmGUIenvironment)#locate here the library files as a list of data.frames
                        Try(assign("whichLib", tt ,affylmGUIenvironment))#remember the type of exon library loaded

                        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(meVDirLocation <- myinfo[which(myinfo[,1]=="meVDirLocation"),2])
                        Try(if(is.na(meVDirLocation)) meVDirLocation <- tt)
                        if(meVDirLocation != ""){
                          assign("meVDirLocation", meVDirLocation, affylmGUIenvironment)#directory where meV program is located
                          assign("meVDirLocation.Available",TRUE,affylmGUIenvironment)
                        }
                  #      Try(perlDirLocation <- myinfo[which(myinfo[,1]=="perlDirLocation"),2])
                  #      Try(if(is.na(perlDirLocation)) perlDirLocation <- tt)
                  #      if(perlDirLocation != ""){
                  #        assign("perlDirLocation", perlDirLocation, affylmGUIenvironment)#directory where ngs perl scripts are located
                  #        assign("perlDirLocation.Available",TRUE,affylmGUIenvironment)
                  #      }else{
                  #                  Try(ngsperlDownload())
                  #      }

                        Try(assign("exonAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exonAffyData", tt ,affylmGUIenvironment))
                        Try(assign("dabg.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("dabg.p" , tt, affylmGUIenvironment))    
                        Try(assign("midas.p" , tt, affylmGUIenvironment))
                        Try(assign("midas.p.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("spliceIndexData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("spliceIndexData", tt ,affylmGUIenvironment))
                        Try(assign("AltSplRP.e.p" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.e.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("AltSplRP.g" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.g.Available" , FALSE, affylmGUIenvironment))
                        
                       	Try(assign("LinearModelFitExon.Available",FALSE,affylmGUIenvironment))
	                      Try(assign("cosie.Available", FALSE ,affylmGUIenvironment))
                        Try(assign("fitExon",tt,affylmGUIenvironment))
                        Try(assign("AltSplLimma" , tt, affylmGUIenvironment))
                        Try(assign("AltSplLimma.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("intronicBg.available", TRUE,affylmGUIenvironment))
                        Try(assign("intronicBg", tt,affylmGUIenvironment))

                        Try(assign("maSigProSigs.Available",FALSE,affylmGUIenvironment))

                        Try(assign("Pset.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("MLdesign.Available",FALSE,affylmGUIenvironment))
                        Try(assign("MLdesign", tt ,affylmGUIenvironment))
                        Try(assign("trainAffyData.available", FALSE, env=affylmGUIenvironment))
                        Try(assign("testAffyData.available", FALSE, env=affylmGUIenvironment))
                        #NGS data
                        assign("NGS", tt ,affylmGUIenvironment)
                        assign("NGS.Available", FALSE, env=affylmGUIenvironment)
                        assign("NGSconversion.available", FALSE,  env=affylmGUIenvironment)
##############initialization variables end
 #         Try(whichKindOfArray())
          #define the right Menu depending on the platform
          Try(tkfocus(.affylmGUIglobals$ttMain))
          Try(changeMenu())#modify the default manu in aplatform specific menu
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
    	     Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))
	         Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
	         Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
	         if(limmaDataSetNameText!="Untitled"){
		         Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled"){LimmaFileName <- limmaDataSetNameText} )	# Local assignment only
		         Try(mbVal <- tkmessageBox(title="Start New Analysis",
				         											message=paste("Save changes to ",fixSeps(LimmaFileName),"?",sep=""),
						         									icon="question",type="yesnocancel",default="yes"
								         						 )#end of tkmessageBox
		         )#end of Try(mbVal..
		         if(tclvalue(mbVal)=="yes"){Try(SaveLimmaFile())}
		         if(tclvalue(mbVal)=="cancel"){
			         Try(tkfocus(.affylmGUIglobals$ttMain))
			         return()
		         }#end of if(tclvalue(mbVal)=="cancel")
		         Try(limmaDataSetNameText <- "Untitled")
	         }#end of if(limmaDataSetNameText!="Untitled")
	         #Try(tkmessageBox(title="Working Directory",message="After clicking OK, please select a working directory.",type="ok"))
	         Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(WD <- SetWD())
           Try(tkfocus(.affylmGUIglobals$ttMain))
	         if(WD=="") return()
	    Try(tkdelete(.affylmGUIglobals$mainTree,"RawAffyData.Status"))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFit.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(tkdelete(.affylmGUIglobals$mainTree,"maSIgProData.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","maSIgProData","maSIgProData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"PLM.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","PLM","PLM.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptDabg.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptDabg","AptDabg.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptMidas.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptMidas","AptMidas.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"spliceIndex.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","spliceIndex","spliceIndex.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.e.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.e.Status" ,text="Not Available at exon level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.g.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.g.Status" ,text="Not Available at gene level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"classification.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","classification","classification.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFitExon.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFitExon","LinearModelFitExon.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      #NGS
      Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(
		    if(NumContrastParameterizations>0){
			    Try(for (i in (1:NumContrastParameterizations))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("ContrastParameterizations.Status.",i,sep="")))
			    )
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"ContrastParameterizations.Status.1"))
		    }
	    )
	    Try(
		    tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)
	    )#end of Try
	    Try(
		    if(NumParameters>0){
			    Try(for (i in (1:NumParameters))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("Parameters.Status.",i,sep="")))
			    )#end of Try-for..
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"Parameters.Status.1"))
		    }
	    )#end of Try-if...
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters","Parameters.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree))
	    if(NumContrastParameterizations>0){
		    for (contrastParameterizationIndex in (1:NumContrastParameterizations)){
			    Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
			    Try(ParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
			    Try(tkdelete(.affylmGUIglobals$ContrastParameterizationTREE,ParameterizationNameNode))
			    Try(assign("ContrastParameterizationList", deleteItemFromList(ContrastParameterizationList,ParameterizationNameNode),affylmGUIenvironment))
		    }#end of for
	    }#end of if
	    Try(initGlobals())
	    Try(LimmaFileName <- get("LimmaFileName",affylmGUIenvironment))
      Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
      Try(if(.Platform$OS.type=="windows")
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",gsub("/","\\\\",LimmaFileName))))
	             else
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",LimmaFileName)))
      )#end of Try
#	    Try(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)		 <- "Please select a Chip Definition (CDF) file.")
#	    Try(tclvalue(.affylmGUIglobals$CDFfileName)				 <- "No filename is selected at the moment.	Press the Select CDF File Button.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle) <- "Please select a tab-delimited file listing the NGS files.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileName)		 <- "No filename is selected at the moment.	Press the Select Targets File Button.")

      Try(miRNAbowtieRun())
	    Try(tkfocus(.affylmGUIglobals$ttMain))
    })
  Try(
    if(ReturnVal=="mRNA"){
                     Try(assign("whichArrayPlatform","NGS",affylmGUIenvironment))
##############initialization variables start
                        Try(tt <- "")
                        Try(assign("illuData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("illuData",tt,affylmGUIenvironment))

                        Try(assign("RawAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("NormalizedAffyData.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("unfilteredData.location", tt, affylmGUIenvironment))
                        Try(assign("geoPlatform",  tt, env=affylmGUIenvironment))

                        Try(assign("metaData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("metaData",tt,affylmGUIenvironment))

                        Try(assign("exprConsoleLibs.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exprConsoleLibs", tt ,affylmGUIenvironment))#locate here the library files as a list of data.frames

                        assign("libDir.Available",FALSE,affylmGUIenvironment)
                        assign("libDir", tt ,affylmGUIenvironment)#locate here the library files as a list of data.frames
                        Try(assign("whichLib", tt ,affylmGUIenvironment))#remember the type of exon library loaded

                        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(meVDirLocation <- myinfo[which(myinfo[,1]=="meVDirLocation"),2])
                        Try(if(is.na(meVDirLocation)) meVDirLocation <- tt)
                        if(meVDirLocation != ""){
                          assign("meVDirLocation", meVDirLocation, affylmGUIenvironment)#directory where meV program is located
                          assign("meVDirLocation.Available",TRUE,affylmGUIenvironment)
                        }
             #           Try(perlDirLocation <- myinfo[which(myinfo[,1]=="perlDirLocation"),2])
             #           Try(if(is.na(perlDirLocation)) perlDirLocation <- tt)
             #           if(perlDirLocation != ""){
             #             assign("perlDirLocation", perlDirLocation, affylmGUIenvironment)#directory where ngs perl scripts are located
             #             assign("perlDirLocation.Available",TRUE,affylmGUIenvironment)
             #           }else{
             #                       Try(ngsperlDownload())
             #           }

                        Try(assign("exonAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exonAffyData", tt ,affylmGUIenvironment))
                        Try(assign("dabg.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("dabg.p" , tt, affylmGUIenvironment))    
                        Try(assign("midas.p" , tt, affylmGUIenvironment))
                        Try(assign("midas.p.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("spliceIndexData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("spliceIndexData", tt ,affylmGUIenvironment))
                        Try(assign("AltSplRP.e.p" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.e.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("AltSplRP.g" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.g.Available" , FALSE, affylmGUIenvironment))
                        
                       	Try(assign("LinearModelFitExon.Available",FALSE,affylmGUIenvironment))
	                      Try(assign("cosie.Available", FALSE ,affylmGUIenvironment))
                        Try(assign("fitExon",tt,affylmGUIenvironment))
                        Try(assign("AltSplLimma" , tt, affylmGUIenvironment))
                        Try(assign("AltSplLimma.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("intronicBg.available", TRUE,affylmGUIenvironment))
                        Try(assign("intronicBg", tt,affylmGUIenvironment))

                        Try(assign("maSigProSigs.Available",FALSE,affylmGUIenvironment))

                        Try(assign("Pset.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("MLdesign.Available",FALSE,affylmGUIenvironment))
                        Try(assign("MLdesign", tt ,affylmGUIenvironment))
                        Try(assign("trainAffyData.available", FALSE, env=affylmGUIenvironment))
                        Try(assign("testAffyData.available", FALSE, env=affylmGUIenvironment))
                        #NGS data
                        assign("NGS", tt ,affylmGUIenvironment)
                        assign("NGS.Available", FALSE, env=affylmGUIenvironment)
                        assign("NGSconversion.available", FALSE,  env=affylmGUIenvironment)
##############initialization variables end
 #         Try(whichKindOfArray())
          #define the right Menu depending on the platform
          Try(tkfocus(.affylmGUIglobals$ttMain))
          Try(changeMenu())#modify the default manu in aplatform specific menu
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
    	     Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))
	         Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
	         Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
	         if(limmaDataSetNameText!="Untitled"){
		         Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled"){LimmaFileName <- limmaDataSetNameText} )	# Local assignment only
		         Try(mbVal <- tkmessageBox(title="Start New Analysis",
				         											message=paste("Save changes to ",fixSeps(LimmaFileName),"?",sep=""),
						         									icon="question",type="yesnocancel",default="yes"
								         						 )#end of tkmessageBox
		         )#end of Try(mbVal..
		         if(tclvalue(mbVal)=="yes"){Try(SaveLimmaFile())}
		         if(tclvalue(mbVal)=="cancel"){
			         Try(tkfocus(.affylmGUIglobals$ttMain))
			         return()
		         }#end of if(tclvalue(mbVal)=="cancel")
		         Try(limmaDataSetNameText <- "Untitled")
	         }#end of if(limmaDataSetNameText!="Untitled")
	         #Try(tkmessageBox(title="Working Directory",message="After clicking OK, please select a working directory.",type="ok"))
	         Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(WD <- SetWD())
           Try(tkfocus(.affylmGUIglobals$ttMain))
	         if(WD=="") return()
	    Try(tkdelete(.affylmGUIglobals$mainTree,"RawAffyData.Status"))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFit.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(tkdelete(.affylmGUIglobals$mainTree,"maSIgProData.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","maSIgProData","maSIgProData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"PLM.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","PLM","PLM.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptDabg.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptDabg","AptDabg.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptMidas.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptMidas","AptMidas.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"spliceIndex.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","spliceIndex","spliceIndex.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.e.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.e.Status" ,text="Not Available at exon level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.g.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.g.Status" ,text="Not Available at gene level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"classification.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","classification","classification.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFitExon.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFitExon","LinearModelFitExon.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      #NGS
      Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(
		    if(NumContrastParameterizations>0){
			    Try(for (i in (1:NumContrastParameterizations))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("ContrastParameterizations.Status.",i,sep="")))
			    )
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"ContrastParameterizations.Status.1"))
		    }
	    )
	    Try(
		    tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)
	    )#end of Try
	    Try(
		    if(NumParameters>0){
			    Try(for (i in (1:NumParameters))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("Parameters.Status.",i,sep="")))
			    )#end of Try-for..
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"Parameters.Status.1"))
		    }
	    )#end of Try-if...
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters","Parameters.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree))
	    if(NumContrastParameterizations>0){
		    for (contrastParameterizationIndex in (1:NumContrastParameterizations)){
			    Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
			    Try(ParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
			    Try(tkdelete(.affylmGUIglobals$ContrastParameterizationTREE,ParameterizationNameNode))
			    Try(assign("ContrastParameterizationList", deleteItemFromList(ContrastParameterizationList,ParameterizationNameNode),affylmGUIenvironment))
		    }#end of for
	    }#end of if
	    Try(initGlobals())
	    Try(LimmaFileName <- get("LimmaFileName",affylmGUIenvironment))
      Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
      Try(if(.Platform$OS.type=="windows")
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",gsub("/","\\\\",LimmaFileName))))
	             else
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",LimmaFileName)))
      )#end of Try
#	    Try(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)		 <- "Please select a Chip Definition (CDF) file.")
#	    Try(tclvalue(.affylmGUIglobals$CDFfileName)				 <- "No filename is selected at the moment.	Press the Select CDF File Button.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle) <- "Please select a tab-delimited file listing the NGS files.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileName)		 <- "No filename is selected at the moment.	Press the Select Targets File Button.")

      Try(mRNAbowtieRun())
	    Try(tkfocus(.affylmGUIglobals$ttMain))
    })



    Try(if(ReturnVal=="REFORMAT"){
                    Try(assign("whichArrayPlatform","NGS",affylmGUIenvironment))
##############initialization variables start
                        Try(tt <- "")
                        Try(assign("illuData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("illuData",tt,affylmGUIenvironment))

                        Try(assign("RawAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("NormalizedAffyData.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("unfilteredData.location", tt, affylmGUIenvironment))
                        Try(assign("geoPlatform",  tt, env=affylmGUIenvironment))

                        Try(assign("metaData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("metaData",tt,affylmGUIenvironment))

                        Try(assign("exprConsoleLibs.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exprConsoleLibs", tt ,affylmGUIenvironment))#locate here the library files as a list of data.frames

                        assign("libDir.Available",FALSE,affylmGUIenvironment)
                        assign("libDir", tt ,affylmGUIenvironment)#locate here the library files as a list of data.frames
                        Try(assign("whichLib", tt ,affylmGUIenvironment))#remember the type of exon library loaded

                        Try(assign("exonAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exonAffyData", tt ,affylmGUIenvironment))
                        Try(assign("dabg.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("dabg.p" , tt, affylmGUIenvironment))    
                        Try(assign("midas.p" , tt, affylmGUIenvironment))
                        Try(assign("midas.p.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("spliceIndexData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("spliceIndexData", tt ,affylmGUIenvironment))
                        Try(assign("AltSplRP.e.p" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.e.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("AltSplRP.g" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.g.Available" , FALSE, affylmGUIenvironment))
                        
                       	Try(assign("LinearModelFitExon.Available",FALSE,affylmGUIenvironment))
	                      Try(assign("cosie.Available", FALSE ,affylmGUIenvironment))
                        Try(assign("fitExon",tt,affylmGUIenvironment))
                        Try(assign("AltSplLimma" , tt, affylmGUIenvironment))
                        Try(assign("AltSplLimma.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("intronicBg.available", TRUE,affylmGUIenvironment))
                        Try(assign("intronicBg", tt,affylmGUIenvironment))

                        Try(assign("maSigProSigs.Available",FALSE,affylmGUIenvironment))

                        Try(assign("Pset.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("MLdesign.Available",FALSE,affylmGUIenvironment))
                        Try(assign("MLdesign", tt ,affylmGUIenvironment))
                        Try(assign("trainAffyData.available", FALSE, env=affylmGUIenvironment))
                        Try(assign("testAffyData.available", FALSE, env=affylmGUIenvironment))
                        #NGS data
                        assign("NGS", tt ,affylmGUIenvironment)
                        assign("NGS.Available", FALSE, env=affylmGUIenvironment)
                        assign("NGSconversion.available", FALSE,  env=affylmGUIenvironment)
##############initialization variables end
 #         Try(whichKindOfArray())
          #define the right Menu depending on the platform
          Try(tkfocus(.affylmGUIglobals$ttMain))
          Try(changeMenu())#modify the default manu in aplatform specific menu
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
    	     Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))
	         Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
	         Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
	         if(limmaDataSetNameText!="Untitled"){
		         Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled"){LimmaFileName <- limmaDataSetNameText} )	# Local assignment only
		         Try(mbVal <- tkmessageBox(title="Start New Analysis",
				         											message=paste("Save changes to ",fixSeps(LimmaFileName),"?",sep=""),
						         									icon="question",type="yesnocancel",default="yes"
								         						 )#end of tkmessageBox
		         )#end of Try(mbVal..
		         if(tclvalue(mbVal)=="yes"){Try(SaveLimmaFile())}
		         if(tclvalue(mbVal)=="cancel"){
			         Try(tkfocus(.affylmGUIglobals$ttMain))
			         return()
		         }#end of if(tclvalue(mbVal)=="cancel")
		         Try(limmaDataSetNameText <- "Untitled")
	         }#end of if(limmaDataSetNameText!="Untitled")
	         #Try(tkmessageBox(title="Working Directory",message="After clicking OK, please select a working directory.",type="ok"))
	         Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(WD <- SetWD())
           Try(tkfocus(.affylmGUIglobals$ttMain))
	         if(WD=="") return()
	    Try(tkdelete(.affylmGUIglobals$mainTree,"RawAffyData.Status"))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFit.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(tkdelete(.affylmGUIglobals$mainTree,"maSIgProData.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","maSIgProData","maSIgProData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"PLM.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","PLM","PLM.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptDabg.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptDabg","AptDabg.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptMidas.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptMidas","AptMidas.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"spliceIndex.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","spliceIndex","spliceIndex.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.e.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.e.Status" ,text="Not Available at exon level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.g.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.g.Status" ,text="Not Available at gene level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"classification.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","classification","classification.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFitExon.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFitExon","LinearModelFitExon.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      #NGS
      Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(
		    if(NumContrastParameterizations>0){
			    Try(for (i in (1:NumContrastParameterizations))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("ContrastParameterizations.Status.",i,sep="")))
			    )
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"ContrastParameterizations.Status.1"))
		    }
	    )
	    Try(
		    tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)
	    )#end of Try
	    Try(
		    if(NumParameters>0){
			    Try(for (i in (1:NumParameters))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("Parameters.Status.",i,sep="")))
			    )#end of Try-for..
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"Parameters.Status.1"))
		    }
	    )#end of Try-if...
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters","Parameters.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree))
	    if(NumContrastParameterizations>0){
		    for (contrastParameterizationIndex in (1:NumContrastParameterizations)){
			    Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
			    Try(ParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
			    Try(tkdelete(.affylmGUIglobals$ContrastParameterizationTREE,ParameterizationNameNode))
			    Try(assign("ContrastParameterizationList", deleteItemFromList(ContrastParameterizationList,ParameterizationNameNode),affylmGUIenvironment))
		    }#end of for
	    }#end of if
	    Try(initGlobals())
	    Try(LimmaFileName <- get("LimmaFileName",affylmGUIenvironment))
      Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
      Try(if(.Platform$OS.type=="windows")
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",gsub("/","\\\\",LimmaFileName))))
	             else
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",LimmaFileName)))
      )#end of Try
#	    Try(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)		 <- "Please select a Chip Definition (CDF) file.")
#	    Try(tclvalue(.affylmGUIglobals$CDFfileName)				 <- "No filename is selected at the moment.	Press the Select CDF File Button.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle) <- "Please select a tab-delimited file listing the NGS files.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileName)		 <- "No filename is selected at the moment.	Press the Select Targets File Button.")

          Try(NGSreformat())
       
    })
    Try(if(ReturnVal=="NGS"){
          Try(assign("whichArrayPlatform","NGS",affylmGUIenvironment))
##############initialization variables start
                        Try(tt <- "")
                        Try(assign("illuData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("illuData",tt,affylmGUIenvironment))

                        Try(assign("RawAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("NormalizedAffyData.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("unfilteredData.location", tt, affylmGUIenvironment))
                        Try(assign("geoPlatform",  tt, env=affylmGUIenvironment))

                        Try(assign("metaData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("metaData",tt,affylmGUIenvironment))

                        Try(assign("exprConsoleLibs.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exprConsoleLibs", tt ,affylmGUIenvironment))#locate here the library files as a list of data.frames

                        assign("libDir.Available",FALSE,affylmGUIenvironment)
                        assign("libDir", tt ,affylmGUIenvironment)#locate here the library files as a list of data.frames
                        Try(assign("whichLib", tt ,affylmGUIenvironment))#remember the type of exon library loaded

                        Try(assign("exonAffyData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("exonAffyData", tt ,affylmGUIenvironment))
                        Try(assign("dabg.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("dabg.p" , tt, affylmGUIenvironment))    
                        Try(assign("midas.p" , tt, affylmGUIenvironment))
                        Try(assign("midas.p.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("spliceIndexData.Available",FALSE,affylmGUIenvironment))
                        Try(assign("spliceIndexData", tt ,affylmGUIenvironment))
                        Try(assign("AltSplRP.e.p" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.e.Available" , FALSE, affylmGUIenvironment))
                        Try(assign("AltSplRP.g" , tt, affylmGUIenvironment))
                        Try(assign("AltSplRP.g.Available" , FALSE, affylmGUIenvironment))
                        
                       	Try(assign("LinearModelFitExon.Available",FALSE,affylmGUIenvironment))
	                      Try(assign("cosie.Available", FALSE ,affylmGUIenvironment))
                        Try(assign("fitExon",tt,affylmGUIenvironment))
                        Try(assign("AltSplLimma" , tt, affylmGUIenvironment))
                        Try(assign("AltSplLimma.Available" , FALSE, affylmGUIenvironment))
                        
                        Try(assign("intronicBg.available", TRUE,affylmGUIenvironment))
                        Try(assign("intronicBg", tt,affylmGUIenvironment))

                        Try(assign("maSigProSigs.Available",FALSE,affylmGUIenvironment))

                        Try(assign("Pset.Available",FALSE,affylmGUIenvironment))
                        
                        Try(assign("MLdesign.Available",FALSE,affylmGUIenvironment))
                        Try(assign("MLdesign", tt ,affylmGUIenvironment))
                        Try(assign("trainAffyData.available", FALSE, env=affylmGUIenvironment))
                        Try(assign("testAffyData.available", FALSE, env=affylmGUIenvironment))
                        #NGS data
                        assign("NGS", tt ,affylmGUIenvironment)
                        assign("NGS.Available", FALSE, env=affylmGUIenvironment)
                        assign("NGSconversion.available", FALSE,  env=affylmGUIenvironment)
##############initialization variables end
 #         Try(whichKindOfArray())
          #define the right Menu depending on the platform
          Try(tkfocus(.affylmGUIglobals$ttMain))
          Try(changeMenu())#modify the default manu in aplatform specific menu
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
    	     Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))
	         Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
	         Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
	         Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
	         if(limmaDataSetNameText!="Untitled"){
		         Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled"){LimmaFileName <- limmaDataSetNameText} )	# Local assignment only
		         Try(mbVal <- tkmessageBox(title="Start New Analysis",
				         											message=paste("Save changes to ",fixSeps(LimmaFileName),"?",sep=""),
						         									icon="question",type="yesnocancel",default="yes"
								         						 )#end of tkmessageBox
		         )#end of Try(mbVal..
		         if(tclvalue(mbVal)=="yes"){Try(SaveLimmaFile())}
		         if(tclvalue(mbVal)=="cancel"){
			         Try(tkfocus(.affylmGUIglobals$ttMain))
			         return()
		         }#end of if(tclvalue(mbVal)=="cancel")
		         Try(limmaDataSetNameText <- "Untitled")
	         }#end of if(limmaDataSetNameText!="Untitled")
	         #Try(tkmessageBox(title="Working Directory",message="After clicking OK, please select a working directory.",type="ok"))
	         Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(WD <- SetWD())
           Try(tkfocus(.affylmGUIglobals$ttMain))
	         if(WD=="") return()
	    Try(tkdelete(.affylmGUIglobals$mainTree,"RawAffyData.Status"))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFit.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(tkdelete(.affylmGUIglobals$mainTree,"maSIgProData.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","maSIgProData","maSIgProData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"PLM.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","PLM","PLM.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptDabg.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptDabg","AptDabg.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AptMidas.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AptMidas","AptMidas.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"spliceIndex.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","spliceIndex","spliceIndex.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.e.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.e.Status" ,text="Not Available at exon level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"AltSplRP.g.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","AltSplRP","AltSplRP.g.Status" ,text="Not Available at gene level",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      Try(tkdelete(.affylmGUIglobals$mainTree,"classification.Status"))            
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","classification","classification.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
	    Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFitExon.Status"))
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFitExon","LinearModelFitExon.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
      #NGS
      Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
      Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status",text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))

	    Try(
		    if(NumContrastParameterizations>0){
			    Try(for (i in (1:NumContrastParameterizations))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("ContrastParameterizations.Status.",i,sep="")))
			    )
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"ContrastParameterizations.Status.1"))
		    }
	    )
	    Try(
		    tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)
	    )#end of Try
	    Try(
		    if(NumParameters>0){
			    Try(for (i in (1:NumParameters))
				    Try(tkdelete(.affylmGUIglobals$mainTree,paste("Parameters.Status.",i,sep="")))
			    )#end of Try-for..
		    }else{
			    Try(tkdelete(.affylmGUIglobals$mainTree,"Parameters.Status.1"))
		    }
	    )#end of Try-if...
	    Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters","Parameters.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree))
	    if(NumContrastParameterizations>0){
		    for (contrastParameterizationIndex in (1:NumContrastParameterizations)){
			    Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
			    Try(ParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
			    Try(tkdelete(.affylmGUIglobals$ContrastParameterizationTREE,ParameterizationNameNode))
			    Try(assign("ContrastParameterizationList", deleteItemFromList(ContrastParameterizationList,ParameterizationNameNode),affylmGUIenvironment))
		    }#end of for
	    }#end of if
	    Try(initGlobals())
	    Try(LimmaFileName <- get("LimmaFileName",affylmGUIenvironment))
      Try(if(LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
      Try(if(.Platform$OS.type=="windows")
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",gsub("/","\\\\",LimmaFileName))))
	             else
		             Try(tkwm.title(.affylmGUIglobals$ttMain,paste("You are now using oneChannelGUI. A add-on package extending the capabilities of affylmGUI -",LimmaFileName)))
      )#end of Try
#	    Try(tclvalue(.affylmGUIglobals$CDFfileBoxTitle)		 <- "Please select a Chip Definition (CDF) file.")
#	    Try(tclvalue(.affylmGUIglobals$CDFfileName)				 <- "No filename is selected at the moment.	Press the Select CDF File Button.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle) <- "Please select a tab-delimited file listing the NGS files.")
	    Try(tclvalue(.affylmGUIglobals$TargetsfileName)		 <- "No filename is selected at the moment.	Press the Select Targets File Button.")
      #defining the the type of input of mapped NGS data
       Try(ttGetNGSinput <- tktoplevel(.affylmGUIglobals$ttMain))
	      Try(tkwm.deiconify(ttGetNGSinput))
	      Try(tkgrab.set(ttGetNGSinput))
	      Try(tkfocus(ttGetNGSinput))
	      Try(tkwm.title(ttGetNGSinput,"Selecting Type of NGS input data"))
	      #
	      Try(tkgrid(tklabel(ttGetNGSinput,text="    ")))
	      Try(NGSinputTcl <- tclVar("SHRIMP reformatted"))
	      Try(rbA <- tkradiobutton(ttGetNGSinput,text="Loading SHRIMP reformatted output data",variable=NGSinputTcl,value="SHRIMP",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(rbB <- tkradiobutton(ttGetNGSinput,text="Loading mature miRNAs from miRanalyser",variable=NGSinputTcl,value="miRanalyser",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(rbC <- tkradiobutton(ttGetNGSinput,text="Loading MicroRazerS reformatted output data",variable=NGSinputTcl,value="MicroRazerS",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(rbD <- tkradiobutton(ttGetNGSinput,text="Loading mature miRNAs from miRProf",variable=NGSinputTcl,value="miRProf",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(rbE <- tkradiobutton(ttGetNGSinput,text="Loading mature miRNAs from miRExpress",variable=NGSinputTcl,value="miRExpress",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(rbF <- tkradiobutton(ttGetNGSinput,text="Loading SHRIMP data generated using miRBase as reference",variable=NGSinputTcl,value="miRShrimp",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(rbG <- tkradiobutton(ttGetNGSinput,text="Loading BAM files generated using oneChannelGUI primary mapping of miRNAs fastq\non miRBase precursors",variable=NGSinputTcl,value="miRBam",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(rbH <- tkradiobutton(ttGetNGSinput,text="Loading BAM files generated using oneChannelGUI primary mapping of mRNAs-seq",variable=NGSinputTcl,value="mRNAbam",font=.affylmGUIglobals$affylmGUIfont2))
        
        Try(tkgrid(tklabel(ttGetNGSinput,text="    "),rbA))
        Try(tkgrid(tklabel(ttGetNGSinput,text="    "),rbB))
        Try(tkgrid(tklabel(ttGetNGSinput,text="    "),rbC))
        Try(tkgrid(tklabel(ttGetNGSinput,text="    "),rbD))
        Try(tkgrid(tklabel(ttGetNGSinput,text="    "),rbE)) 
        Try(tkgrid(tklabel(ttGetNGSinput,text="    "),rbF)) 
        Try(tkgrid(tklabel(ttGetNGSinput,text="    "),rbG)) 
        Try(tkgrid(tklabel(ttGetNGSinput,text="    "),rbH)) 
             
      	Try(tkgrid.configure(rbA,rbB, rbC, rbD, rbE, rbF, rbG, rbH, columnspan=2,sticky="w"))
       	Try(tkgrid(tklabel(ttGetNGSinput,text="    "),tklabel(ttGetNGSinput,text="    ")))
	      #
	      Try(ReturnNGSinput <- "")
	      Try(
		         onCancel <- function() {
			          Try(ReturnNGSinput <<- "");
			          Try(tkgrab.release(ttGetNGSinput));
			          Try(tkdestroy(ttGetNGSinput));
			          Try(tkfocus(.affylmGUIglobals$ttMain))
		        }
	      )
	      Try(
		       onOK <- function() {
			         Try(ReturnNGSinput <<- tclvalue(NGSinputTcl));
			         Try(tkgrab.release(ttGetNGSinput));
			         Try(tkdestroy(ttGetNGSinput));
			         Try(tkfocus(.affylmGUIglobals$ttMain))
		      }
	     )
       #
	     Try(OK.but     <- tkbutton(ttGetNGSinput,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	     Try(Cancel.but <- tkbutton(ttGetNGSinput,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
	     #
	     Try(tkgrid(tklabel(ttGetNGSinput,text="    "),OK.but,Cancel.but,tklabel(ttGetNGSinput,text="    ")))
	     Try(tkgrid.configure(OK.but,sticky="e"))
	     Try(tkgrid.configure(Cancel.but,sticky="w"))
	     Try(tkgrid(tklabel(ttGetNGSinput,text="    ")))
	     #
	     Try(tkbind(ttGetNGSinput,"<Destroy>",function() {ReturnNGSinput <- "";Try(tkgrab.release(ttGetNGSinput));Try(tkfocus(.affylmGUIglobals$ttMain));}))
	     Try(tkbind(OK.but, "<Return>",onOK))
	     Try(tkbind(Cancel.but, "<Return>",onCancel))
	     #
	     Try(tkwait.window(ttGetNGSinput))
     
      if(ReturnNGSinput == "SHRIMP"){
          Try(tkmessageBox(title="NGS data input",message="Loading SHRIMP reformatted using the reformat function provided in oneChannelGUI File menu", type="ok", icon="info"))  
          Try(assign("NGSprimaryMapping", "SHRIMP" ,affylmGUIenvironment))
          Try(assign("NGSprimaryMapping.Available", TRUE, env=affylmGUIenvironment))

          Try(OpenNgsfiles())
      }
      if(ReturnNGSinput == "MicroRazerS"){
          Try(tkmessageBox(title="NGS data input",message="Loading MicroRazerS reformatted using the reformat function provided in oneChannelGUI File menu", type="ok", icon="info"))  
          Try(assign("NGSprimaryMapping", "MicroRazerS" ,affylmGUIenvironment))
          Try(assign("NGSprimaryMapping.Available", TRUE, env=affylmGUIenvironment))

          Try(OpenNgsfiles())
      }
      if(ReturnNGSinput == "miRanalyser") {
          Try(tkmessageBox(title="NGS data input",message="Loading Tab delimited file for mature miRNAs provided by miRanalyser web site.", type="ok", icon="info"))  
          Try(assign("NGSprimaryMapping", "miRanalyser" ,affylmGUIenvironment))
          Try(assign("NGSprimaryMapping.Available", TRUE, env=affylmGUIenvironment))
          Try(OpenmiRanalyserfiles())
      }
      if(ReturnNGSinput == "miRExpress") {
          Try(tkmessageBox(title="NGS data input",message="Loading Tab delimited file for mature miRNAs provided by miRExpress tool.", type="ok", icon="info"))  
          Try(assign("NGSprimaryMapping", "miRExpress" ,affylmGUIenvironment))
          Try(assign("NGSprimaryMapping.Available", TRUE, env=affylmGUIenvironment))
          Try(OpenmiRExpress())
      }

      if(ReturnNGSinput == "miRProf") {
          Try(tkmessageBox(title="NGS data input",message="Loading Tab delimited file for mature miRNAs provided by miRProf web site.", type="ok", icon="info"))  
          Try(assign("NGSprimaryMapping", "miRProf" ,affylmGUIenvironment))
          Try(assign("NGSprimaryMapping.Available", TRUE, env=affylmGUIenvironment))
          Try(OpenmiRProfiles())
      }
      
      if(ReturnNGSinput == "miRShrimp") {
          Try(tkmessageBox(title="NGS data input",message="Loading reformatted files generated mapping reads over oneChannelGUI-mirbase precursors in fasta format using SHRIMP.\nThe oneChannelGUI reformatted files have extension shrink.", type="ok", icon="info"))  
          Try(assign("NGSprimaryMapping", "miRShrimp" ,affylmGUIenvironment))
          Try(assign("NGSprimaryMapping.Available", TRUE, env=affylmGUIenvironment))
          Try(OpenmiRShrimp())
      }

      if(ReturnNGSinput == "miRBam"){
          Try(tkmessageBox(title="NGS data input",message="Loading BAM files generated by miRNA oneChannelGUI primary mapping", type="ok", icon="info"))  
          Try(assign("NGSprimaryMapping", "miRBam" ,affylmGUIenvironment))
          Try(assign("NGSprimaryMapping.Available", TRUE, env=affylmGUIenvironment))
          Try(OpenmiRBam())
      }
      
      if(ReturnNGSinput == "mRNAbam"){
          Try(tkmessageBox(title="NGS data input",message="Loading BAM files generated by mRNA oneChannelGUI primary mapping", type="ok", icon="info"))  
          Try(assign("NGSprimaryMapping", "mRNABam" ,affylmGUIenvironment))
          Try(assign("NGSprimaryMapping.Available", TRUE, env=affylmGUIenvironment))
          Try(OpenmRNABam())
      }


	    Try(tkfocus(.affylmGUIglobals$ttMain))

       
       })

 } 
##################################################################################################################
#NGS
#this fuction uses the output file provided by mapping reads over mirBase precursors in fasta format using shrimp
#data are reformatted by  shrimpENSEMBL2genominator.mirbase.pl script
"OpenmiRBam" <- function()
{
#	Try(require(Rsamtools)||stop("\nMissingRsamtools library!"))
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttExonandTargets))
	Try(tkgrab.set(ttExonandTargets))
	Try(tkfocus(ttExonandTargets))
	Try(tkwm.title(ttExonandTargets,"Targets file"))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

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

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

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

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

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

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

	if(Abort==1)
				return(0)
  
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(Targets <- get("Targets",affylmGUIenvironment))
	Try(slides <- Targets$FileName)
	
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  #NGS reads number and reformatting Target in Targets #######################
  Try(tmpTarget <- Targets$Target)
  Try(tmpTarget <- strsplit(tmpTarget, "_"))
  Try(newTarget <- sapply(tmpTarget, function(x)x[1]))
  Try(Targets$Target <- newTarget)
  Try(rownames(Targets) <- NULL)
  Try(assign("Targets",Targets,envir=affylmGUIenvironment))
  Try(totalReads <- sapply(tmpTarget, function(x)x[2]))
  Try(mappedReads <- sapply(tmpTarget, function(x)x[3]))
  Try(assign("totalReads", as.numeric(totalReads),envir=affylmGUIenvironment))
  Try(assign("mappedReads", as.numeric(mappedReads),envir=affylmGUIenvironment))
 
  #Creating the expression set
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))

  Try(data.list <- list())
  .fillVec <- function(x, y){
    for(i in 1:length(x)){
             x[i]   <- length(which(y == names(x)[i]))
    }
    return(x)
  }
 
  for(i in Targets$FileName){
     Try(cat("\nProcessing ",i))
     Try(p2 <- ScanBamParam(what="rname", flag=scanBamFlag(isUnmappedQuery=FALSE))) 
     #Try(tmp <- read.table(i, sep="\t", header=F, as.is=T))
     Try(tmp <- scanBam(i, param=p2))
     Try(miRNA.unique <- unique(as.character(tmp[[1]]$rname)))
     
     Try(vec.miRNA <- rep(0,length(miRNA.unique)))
     Try(names(vec.miRNA) <- miRNA.unique)
     Try(vec.miRNA <- .fillVec(vec.miRNA, as.character(tmp[[1]]$rname)))
     Try(cat("\nTotal microRNAs detected in ",i, ": ", length(vec.miRNA)))
     Try(data.list[[i]] <- vec.miRNA)
  }
  #building the data frame
  Try(miRNA.names <- sapply(data.list, function(x) names(x)))
  Try(miRNA.unique <- unique(as.character(unlist(miRNA.names))))
  Try(cat("\nDetected ", length(miRNA.unique), "microRNAs\n"))
  #creating matrix to be filled
  Try(mat.miRNA <- matrix(rep(0,length(miRNA.unique) * length(data.list)), nrow=length(miRNA.unique)))
  Try(dimnames(mat.miRNA) <- list(miRNA.unique, names(data.list)))
  #assigning values
  .fillMat <- function(x, y){
    for(i in 1:dim(x)[1]){
      for(j in 1:length(y)){
          if(length(y[[j]][which(names(y[[j]]) == dimnames(x)[[1]][i])]) > 0)
               x[i,j]   <- y[[j]][which(names(y[[j]]) == dimnames(x)[[1]][i])]
      }
    }
    return(x)
  }
  Try(cat("\n"))
  
  Try(mat.miRNA <- .fillMat(mat.miRNA, data.list))
  #saving the data table before annotation addition
  
   .SaveNGSmatrix <- function(mymat)
   {
      Try(FileName <- tclvalue(tkgetSaveFile(initialfile=paste("countMatrix.xls",sep=""),filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
      Try(if(!nchar(FileName))
      return())
      Try(write.table(mymat,file=FileName,quote=FALSE, sep="\t", row.names=T, col.names=NA))
   }
   
  Try(countVal <- tkmessageBox(title="Adding Annotation",
                            message="IMPORTANT: annotation will remove microRNAs characterized by multiple locations in the genome.\n If you answer NO annotation will not be added.",
                            icon="question",type="yesno",default="yes"))
      Try(if(tclvalue(countVal)=="no"){

  Try(tmp.genome <- NULL)
  Try(tmp.genome[1] <- length(grep("hsa", rownames(mat.miRNA))))
  Try(tmp.genome[2] <- length(grep("mmu", rownames(mat.miRNA))))
  Try(tmp.genome[3] <- length(grep("rno", rownames(mat.miRNA))))
  Try(my.genome <- which(tmp.genome == max(tmp.genome))) 
  if(my.genome == 1){
      Try(genome.version <- "hg19")
      Try(chrs <- seq(1, 25))
      Try(chrs.names <- c(chrs[1:22], "X", "Y", "MT"))
      Try(names(chrs) <- chrs.names)
      #require(BSgenome.Hsapiens.UCSC.hg19) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Hsapiens.UCSC.hg19") ; require(BSgenome.Hsapiens.UCSC.hg19)}
      Try(data("chrLength",package="oneChannelGUI"))
      Try(chrLength <- get("chrLength",envir=.GlobalEnv))
      Try(chrs.length <- chrLength$hg19)
      Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
  }
  if(my.genome == 2){
       Try(genome.version <- "mm8")
       Try(chrs <- seq(1, 22))
       Try(chrs.names <- c(chrs[1:19], "X", "Y", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Mmusculus.UCSC.mm9) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Mmusculus.UCSC.mm9") ; require(BSgenome.Mmusculus.UCSC.mm9)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$mm9)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected M. musculus genome UCSC release mm9.",type="ok", icon="info"))
  }
  if(my.genome == 3){
       Try(genome.version <- "rn4")
       Try(chrs <- seq(1, 21))
       Try(chrs.names <- c(chrs[1:19], "X", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Rnorvegicus.UCSC.rn4) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Rnorvegicus.UCSC.rn4") ; require(BSgenome.Rnorvegicus.UCSC.rn4)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$rn4)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected R. norvegicus genome UCSC release rn4.",type="ok", icon="info"))
  }
  Try(NormalizedAffyData <- new("ExpressionSet", assayData = assayDataNew(exprs=mat.miRNA) , phenoData=tmp1.pd, annotation=genome.version))
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
  Try(assign("NGS.Available",TRUE,affylmGUIenvironment))
	Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="NGS counts from miRanalyser",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status" ,text="NGS data",font=.affylmGUIglobals$affylmGUIfontTree))

	Try(if("Name" %in% colnames(Targets))
	SlideNamesVec <- Targets$Name)
	Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))

 	Try(ReturnVal <- GetlimmaDataSetName())
	if(ReturnVal==0) return(0)
	return(1)
      } else{
          Try(tkmessageBox(title="Saving miRNA data",message="A data matrix before annotation will be saved.",type="ok", icon="info"))
          Try(.SaveNGSmatrix(mat.miRNA)) 
          Try(tmp.genome <- NULL)
  Try(tmp.genome[1] <- length(grep("hsa", rownames(mat.miRNA))))
  Try(tmp.genome[2] <- length(grep("mmu", rownames(mat.miRNA))))
  Try(tmp.genome[3] <- length(grep("rno", rownames(mat.miRNA))))
  Try(my.genome <- which(tmp.genome == max(tmp.genome))) 
  if(my.genome == 1){
      Try(genome.version <- "hg19")
      Try(chrs <- seq(1, 25))
      Try(chrs.names <- c(chrs[1:22], "X", "Y", "MT"))
      Try(names(chrs) <- chrs.names)
      #require(BSgenome.Hsapiens.UCSC.hg19) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Hsapiens.UCSC.hg19") ; require(BSgenome.Hsapiens.UCSC.hg19)}
      Try(data("chrLength",package="oneChannelGUI"))
      Try(chrLength <- get("chrLength",envir=.GlobalEnv))
      Try(chrs.length <- chrLength$hg19)
      Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
  }
  if(my.genome == 2){
       Try(genome.version <- "mm8")
       Try(chrs <- seq(1, 22))
       Try(chrs.names <- c(chrs[1:19], "X", "Y", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Mmusculus.UCSC.mm9) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Mmusculus.UCSC.mm9") ; require(BSgenome.Mmusculus.UCSC.mm9)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$mm9)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected M. musculus genome UCSC release mm9.",type="ok", icon="info"))
  }
  if(my.genome == 3){
       Try(genome.version <- "rn4")
       Try(chrs <- seq(1, 21))
       Try(chrs.names <- c(chrs[1:19], "X", "MT"))
       Try(names(chrs) <- chrs.names)
       #require(BSgenome.Rnorvegicus.UCSC.rn4) || {source("http://bioconductor.org/biocLite.R") ; biocLite("BSgenome.Rnorvegicus.UCSC.rn4") ; require(BSgenome.Rnorvegicus.UCSC.rn4)}
       Try(data("chrLength",package="oneChannelGUI"))
       Try(chrLength <- get("chrLength",envir=.GlobalEnv))
       Try(chrs.length <- chrLength$rn4)
       Try(assign("chrsLength", chrs.length, affylmGUIenvironment))
       Try(tkmessageBox(title="Genome selection",message="You have selected R. norvegicus genome UCSC release rn4.",type="ok", icon="info"))
  }
  Try(getNGSannotation())
  Try(chrs.length <- get("chrsLength", affylmGUIenvironment))
  Try(myAnn <- get("tmpNGSannotation", affylmGUIenvironment))
  Try(pm <- as.data.frame(myAnn))
  Try(p <- pm[which(pm$strand == 1),])
  Try(m <- pm[which(pm$strand == -1),])
  Try(pm <- rbind(p,m))
  Try(pm <- pm[which(pm$space %in% names(chrs.length)),])
  Try(chr <- as.character(pm$space))
  Try(annoData <- data.frame(chr=chr, strand=pm$strand, start=pm$start, end=pm$end, feature=as.character(pm$description)))
  Try(rownames(annoData) <- as.character(pm$names))
  Try(description <- as.character(annoData$feature))
  Try(annoData <- annoData[grep("miRBase", description),])
  Try(description <- as.character(annoData$feature))
  Try(description <- strsplit(description, " "))
  Try(description <- sapply(description, function(x) x[1]))
  if(my.genome == 1){
#        description <- paste("hsa-miR-", description, sep="")
        Try(annoData$feature <- description)
  }
  if(my.genome == 2){
#        description <- paste("mmu-miR-", description, sep="")
        Try(annoData$feature <- description)
 }
  if(my.genome == 3){
#        description <- paste("rno-miR-", description, sep="")
        Try(annoData$feature <- description)
  }
  #detecting and removing duplicated miRNA
  Try(duplicated <- which(annoData$feature %in% annoData$feature[which(duplicated(annoData$feature))]))
  Try(cat("\nThe following miRNAs were removed since present in duplicated positions\n"))
  Try(print(annoData[duplicated,]))
  Try(cat("\n"))
  Try(annoData <- annoData[setdiff(seq(1,dim(annoData)[1]), duplicated),])
  #

  Try(annoData <- annoData[which(annoData$feature %in% dimnames(mat.miRNA)[[1]]),])
  Try(annoData <- annoData[order(annoData$feature),])
  Try(mat.miRNA <- mat.miRNA[which(dimnames(mat.miRNA)[[1]] %in% annoData$feature),])
  Try(mat.miRNA <- mat.miRNA[order(dimnames(mat.miRNA)[[1]]),])
  Try(mat.rnames <- apply(annoData, 1, function(x) paste("chr:",x[1],"strand:",x[2], "start:", x[3], "end:", x[4], "description:", x[5] , sep=" ")))
  Try(mat.rnames <- paste(names(mat.rnames), mat.rnames))
  
  if(identical(dimnames(mat.miRNA)[[1]], annoData$feature)){
       Try(dimnames(mat.miRNA)[[1]] <-  mat.rnames)
  }else{
     Try(tkmessageBox(title="Internal error",message="Internal error 12346. Please contact oneChannelGUI maintainer",type="ok", icon="error"))
     return()
  }
  
  Try(NormalizedAffyData <- new("ExpressionSet", assayData = assayDataNew(exprs=mat.miRNA) , phenoData=tmp1.pd, annotation=genome.version))
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
  Try(assign("NGS.Available",TRUE,affylmGUIenvironment))
	Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="NGS counts from miRanalyser",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status" ,text="NGS data",font=.affylmGUIglobals$affylmGUIfontTree))

	Try(if("Name" %in% colnames(Targets))
	SlideNamesVec <- Targets$Name)
	Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
  Try(tkfocus(.affylmGUIglobals$ttMain))
 	Try(ReturnVal <- GetlimmaDataSetName())
	if(ReturnVal==0) return(0)
	return(1)

  
      }) 
    
}
################################################################################ 
#loading bam for mRNA-seq   Da sistemare
#readGAlignments
#Try(require(GenomicRanges)||stop("\nMissing GenomicRanges\n"))
"OpenmRNABam" <- function()
{
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
#  Try(require(Rsamtools)||stop("\nMissingRsamtools library!"))
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(ttExonandTargets<-tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttExonandTargets))
	Try(tkgrab.set(ttExonandTargets))
	Try(tkfocus(ttExonandTargets))
	Try(tkwm.title(ttExonandTargets,"Targets file"))
	Try(tkgrid(tklabel(ttExonandTargets,text="    ")))

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

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

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

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

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

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

	if(Abort==1)
				return(0)
  
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	Try(tkfocus(.affylmGUIglobals$ttMain))
	Try(Targets <- get("Targets",affylmGUIenvironment))
	#che if the target file contains bam data generated from oneChannelGUI
	Try(if(length(grep('bam$',Targets$FileName)) != length(Targets$FileName)) {
               Try(tkmessageBox(title="BAM data input",message="It seems that target file does not contains FileName with extension bam.\nPlease, check you target file.", type="ok", icon="error"))  
               Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	             Try(tkfocus(.affylmGUIglobals$ttMain))
	             Try(return())
  })
	Try(slides <- Targets$FileName)
	
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))
  #NGS reads number and reformatting Target in Targets #######################
  Try(tmpTarget <- Targets$Target)
  Try(tmpTarget <- strsplit(tmpTarget, "_"))
  Try(newTarget <- sapply(tmpTarget, function(x)x[1]))
  Try(Targets$Target <- newTarget)
  Try(rownames(Targets) <- NULL)
  Try(assign("Targets",Targets,envir=affylmGUIenvironment))
  Try(totalReads <- sapply(tmpTarget, function(x)x[2]))
  Try(mappedReads <- sapply(tmpTarget, function(x)x[3]))
  Try(assign("totalReads", as.numeric(totalReads),envir=affylmGUIenvironment))
  Try(assign("mappedReads", as.numeric(mappedReads),envir=affylmGUIenvironment))
 
  #Creating the expression set
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(rownames(Targets) <- Targets$FileName) 
  Try(var.tmp.pd<-data.frame(names(Targets)))
  Try(names(var.tmp.pd)<-"labelDescription" )
  Try(rownames(var.tmp.pd)<-names(Targets))
  Try(tmp1.pd<-new("AnnotatedDataFrame", data=Targets, varMetadata=var.tmp.pd))

  Try(mat.mRNA <- NULL)
  #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="hs19",font=.affylmGUIglobals$affylmGUIfont2))
  Try(rbIQR.25<-tkradiobutton(ttGetOrganism,text="M. musculus",variable=ttGetOrganismTcl,value="mm9",font=.affylmGUIglobals$affylmGUIfont2))
  Try(rbIQR.1<-tkradiobutton(ttGetOrganism,text="R. norvegicus",variable=ttGetOrganismTcl,value="rn4",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.configure(rbIQR.5,rbIQR.25,rbIQR.1,columnspan=2,sticky="w"))
	Try(tkgrid(tklabel(ttGetOrganism,text="    "),tklabel(ttGetOrganism,text="    ")))
  Try(ReturnVal <- "")
  Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGetOrganism));Try(tkdestroy(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain))})
  Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGetOrganismTcl));Try(tkgrab.release(ttGetOrganism));Try(tkdestroy(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain))})
  Try(OK.but     <- tkbutton(ttGetOrganism,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <- tkbutton(ttGetOrganism,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

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

  Try(tkbind(ttGetOrganism,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkbind(OK.but, "<Return>",onOK))
  Try(tkbind(Cancel.but, "<Return>",onCancel))      
  Try(tkwait.window(ttGetOrganism))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  
  if(ReturnVal == ""){
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
       Try(return())
  } else if (ReturnVal == "hs19"){
     Try(annlibname <- system.file("bowtie/hg19_gene-level.scaffold.Rda",package="oneChannelGUI"))
     Try(load(annlibname))
     Try(tkmessageBox(title="Genome selection",message="You have selected H. sapiens genome UCSC release hg19 as scaffold for gene-level analysis.",type="ok", icon="info"))
  } else if (ReturnVal == "mm9"){
     Try(annlibname <- system.file("bowtie/mm9_gene-level.scaffold.Rda",package="oneChannelGUI"))
     Try(load(annlibname))
     Try(tkmessageBox(title="Genome selection",message="You have selected Mus musculus genome UCSC release mm9 as scaffold for gene-level analysis.",type="ok", icon="info"))
  } else if (ReturnVal == "rn4"){
     Try(annlibname <- system.file("bowtie/rn4_gene-level.scaffold.Rda",package="oneChannelGUI"))
     Try(load(annlibname))
     Try(tkmessageBox(title="Genome selection",message="You have selected Rattus norvegicus genome UCSC release rn4 as scaffold for gene-level analysis.",type="ok", icon="info"))
  }
  #detecting the chr under analysis
  Try(chr <- strsplit(Targets$FileName[1], "_")) #getting the chr
  Try(chr <- as.vector(unlist(chr)))
  Try(chr <- chr[length(chr)])
  Try(chr <- sub(".bam", "", chr))  #needed to extract the right subset of gene-level annotation from  makeGeneScaffold generated GRanges list
  Try(chr <- sub("chr0", "chr", chr))
  #selecting the chromosome genomic reanges on which assigning BAM data
  Try(chr.gr <- chr.gr[which(names(chr.gr) == chr)])
  Try(chr.grNames <-  paste(as.character(seqnames(chr.gr[[1]])),paste(as.character(start(chr.gr[[1]])), as.character(end(chr.gr[[1]])), sep="-"), as.character(strand(chr.gr[[1]])), elementMetadata(chr.gr[[1]])$names, sep="_"))
  Try(mat.counts <- matrix(data=rep(0,length(chr.gr[[1]]) * length(Targets$FileName)), ncol= length(Targets$FileName)))
  Try(dimnames(mat.counts) <- list(chr.grNames, Targets$FileName))
  for(i in 1:length(Targets$FileName)){
     Try(mygenes.counts <- NULL)
     Try(cat("\nProcessing ",Targets$FileName[i]))
     Try(p2 <- readGAlignments(Targets$FileName[i], index=Targets$FileName[i]))
     Try(ungapped <- p2[which(ngap(p2)==0)]) #detecting ungapped alignments
     Try(ungapped <- as(ungapped, "GRanges"))
     Try(ungapped <- ranges(ungapped))   #extracting only ranges data
     Try(gapped <- p2[which(ngap(p2)==1)])   ##detecting gapped alignments
     #find in query the objects  are counted oall type of overlaps start, end, inside, we report all of them
    # Try(counts.tmp <- rep(0,length(chr.gr[[1]]))) #counting the intersection of the reads with each of the gene
    Try(query <- ranges(chr.gr[[1]]))
   #can be done with summarizeOverlaps GenomicRanges
    Try(mymatch   <- findOverlaps(query, subject = ungapped, type = "any", select = "all"))
    Try(match.counts <- matchMatrix(mymatch )[,1]) # extracting how many times query was foud overlapping to subjects
    Try(mygenes <- seq(1, dim(mat.counts)[1]))
    Try(mygenes.counts <- sapply(mygenes, function(x,y){length(which(y == x))},y=match.counts))
    Try(mat.counts[,i] <- mygenes.counts)
  }
  Try(NormalizedAffyData <- new("ExpressionSet", assayData = assayDataNew(exprs=mat.counts) , phenoData=tmp1.pd, annotation=ReturnVal))
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
  Try(assign("NGS.Available",TRUE,affylmGUIenvironment))
	Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="NGS counts from RNA-seq",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NGS.Status"))
	Try(tkinsert(.affylmGUIglobals$mainTree,"end","NGS","NGS.Status" ,text="NGS data",font=.affylmGUIglobals$affylmGUIfontTree))

	Try(if("Name" %in% colnames(Targets))
	SlideNamesVec <- Targets$Name)
	Try(assign("SlideNamesVec",SlideNamesVec,affylmGUIenvironment))
	Try(assign("ArraysLoaded",TRUE,affylmGUIenvironment))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
 	Try(ReturnVal <- GetlimmaDataSetName())
	if(ReturnVal==0) return(0)
	return(1)
   
}
#############
#changing menu to run tophat
tuxedoMenu <- function(){
	  Try(assign("whichArrayPlatform","NGS",affylmGUIenvironment))
         #changing the menu to be used for exons data
         Try(topMenu <- tkmenu(.affylmGUIglobals$ttMain))
       	   Try(tkconfigure(.affylmGUIglobals$ttMain,menu=topMenu))
       	   Try(Menus <- read.table(file.path(system.file("etc",package="oneChannelGUI"),"affylmGUI-menus.ngs.datasets.txt"), as.is=TRUE))
       	   Try(
	       	   for (m in 1:nrow(Menus)){
		       	   Try(if(Menus[m, 1] == "menu"){
				         	assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))
			       	    }else if(Menus[m, 1] == "item"){
				       	  if(Menus[m, 3] == "command")
					       	  tkadd(eval(parse(text=Menus[m, 2])),"command", label=Menus[m, 4], command=eval(parse(text=Menus[m, 5])))
				       	   else if(Menus[m, 3] == "cascade"){
					       	   cascadeMenu <- eval(parse(text=Menus[m, 5]))
					       	   tkadd(eval(parse(text=Menus[m, 2])),"cascade", label=Menus[m, 4], menu=cascadeMenu)
					       	 if(Menus[m, 4]=="File"){
						         	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
						       	  Try(menuNames <- unique(Menus[,2,drop=TRUE]))
						       	  Try(numMenus <- length(menuNames))
						       	  Try(menus <- list())
						       	  Try(for (j in (1:numMenus))
							       	  menus[[j]] <- eval(parse(text=Menus[j,2]))
						       	  )#end of Try
						       	  Try(names(menus) <- menuNames)
						       	  Try(affylmGUIglobals$menus <- menus)
						       	  Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
					       	   }#end of if(Menus[m, 4]=="File")
				       	   }else if(Menus[m, 3] == "separator"){#end of else if(Menus[m, 3] == "cascade")
					       	  if(nrow(Menus)>m && Menus[m+1, 4]=="Exit"){
						       	  recentFilesFileName <- system.file("etc/recent-files.txt",package="oneChannelGUI")
						       	  recentFiles <- readLines(recentFilesFileName)
						       	  recentFiles <- gsub("\\\\","/",recentFiles)
						       	  # Remove any blank lines:
						       	  blanks <- grep("^[ \t\n]*$",recentFiles)
						       	  if(length(blanks)>0)
							       	  recentFiles <- recentFiles[-blanks]
						       	    numRecentFiles <- length(recentFiles)
						       	  if(numRecentFiles>0){
							       	   tkadd(eval(parse(text=Menus[m, 2])),"separator")
							       	   for (i in (1:numRecentFiles)){
								       	   label <- recentFiles[i]
								       	   fileNameOnly <- strsplit(label,"/")[[1]]
							       	     fileNameOnly <- fileNameOnly[length(fileNameOnly)]
								       	   if(nchar(recentFiles[i])>60)
										         	label <- paste(".../",fileNameOnly)
								       	      eval(parse(text=paste("assign(\".OpenALimmaFile_",i,"\",function() OpenALimmaFile(\"",recentFiles[i],"\"),.GlobalEnv)",sep="")))
								       	   Try(
									       	   if(.Platform$OS.type=="windows"){
										       	   tkadd(
											       	   eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",gsub("/","\\\\",label),sep=""),
											       	   command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
										       	   )#end of tkadd
								       	     }else{
										       	    tkadd(
										       	    eval(parse(text=Menus[m,2])),"command",label=paste(i,". ",label,sep=""),
											       	  command=eval(parse(text=paste(".OpenALimmaFile_",i,sep="")))
										       	 )#end of tkadd
									       	 }#end of else/if
						       	     )#end of Try
							       	 }#end of for (i in (1:numRecentFiles))
						       	 }#end of if(numRecentFiles>0)
					       	 }#end of if(nrow(Menus)>m && Menus[m+1, 4]=="Exit")
					       	  tkadd(eval(parse(text=Menus[m, 2])),"separator")
				       	    }else{
					         	  stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
				       	    }#end of else if(Menus[m, 3] == "separator")
			     	      }else{
				         	    stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
		   	      }#end of else/if(Menus[m, 1] == "item")
		       	)#end of Try(if(Menus[m, 1] == "menu") assign(Menus[m, 2], tkmenu(eval(parse(text=Menus[m, 3])), tearoff=FALSE))...)
	       	}#end of for (m in 1:nrow(Menus))
       	)#end of Try(for (m in 1:nrow(Menus))..)

       	Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=affylmGUIenvironment))
       	Try(affylmGUIglobals$mainMenu <- topMenu)
       	Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
        Try(tkfocus(.affylmGUIglobals$ttMain))  
}

Try the oneChannelGUI package in your browser

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

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