.packageName <- "affylmGUI"
###########################################################################################################################
# R2HTML Plot Function (Modified to accept a plotFunction argument, rather than using the main R Graphics Device)

"HTMLplotUsingFunction" <- function (Caption = "", File = .HTML.file, GraphRelativeDirectory = ".", GraphAbsoluteDirectory = NULL, GraphFileName = "", GraphSaveAs = "png", GraphBorder = 1,  Align = "center", plotFunction = NULL,Width=600,Height=600,PointSize=12,BG="white",res=72,...)
{
    if (is.null(GraphAbsoluteDirectory))
      GraphAbsoluteDirectory <- getwd()
    if (GraphFileName == "") {
        nowd <- date()
        GraphFileName <- paste("GRAPH_", substring(nowd, 5, 7), substring(nowd, 9, 10), "_", substring(nowd, 12, 13), substring(nowd, 15,  16), substring(nowd, 18, 19), sep = "")
    }
    GraphFileName <- paste(GraphFileName, ".", GraphSaveAs, sep = "")

#    AbsGraphFileName <- paste(GraphRelativeDirectory,.Platform$file.sep,GraphFileName,sep="")
    AbsGraphFileName <- file.path(GraphAbsoluteDirectory, GraphFileName)
    if (GraphSaveAs=="png") 
    {
      if (is.null(plotFunction))
        dev.print(png, file = AbsGraphFileName, width=Width,height=Height,pointsize=PointSize,bg=BG)
      else
      {
        Try(if (exists("X11", env=.GlobalEnv) && Sys.info()["sysname"] != "Windows" && Sys.info()["sysname"] != "Darwin")  
          Try(bitmap(file = AbsGraphFileName,bg=BG,res=res))
        else
          Try(png(filename = AbsGraphFileName, width=Width,height=Height,pointsize=PointSize,bg=BG)))
        plotFunction()      
        dev.off()
      }
    }
    else if (GraphSaveAs=="jpg") 
    {
      if (is.null(plotFunction))
        dev.print(jpeg, file = AbsGraphFileName, width=Width,height=Height,pointsize=PointSize,bg=BG)
      else
      {
        Try(if (exists("X11", env=.GlobalEnv) && Sys.info()["sysname"] != "Windows" && Sys.info()["sysname"] != "Darwin")  
          Try(bitmap(filename = AbsGraphFileName,bg=BG,res=res,type="jpeg"))
        else
          Try(jpeg(filename = AbsGraphFileName, width=Width,height=Height,pointsize=PointSize,bg=BG)))
        plotFunction()      
        dev.off()
      }
    }
    else if (GraphSaveAs=="gif") 
    {
      if (is.null(plotFunction))
        dev.print(gif, file = AbsGraphFileName, width=Width,height=Height,pointsize=PointSize,bg=BG)
      else
      {
        stop("When passing a plot function to HTMLplot, device must be jpg or png.")      
      }
    }
    else stop("GraphSaveAs must be either jpg, png or gif")
    cat(paste("<p align=", Align, "><img src='", paste(GraphRelativeDirectory,"/",GraphFileName,sep=""), "' border=", GraphBorder, ">", sep = "", collapse = ""), file = File, append = TRUE, sep = "")
    if (Caption != "") {
        cat(paste("<br><i>", Caption, "</i>"), file = File, append = TRUE, sep = "")
    }
    cat("</P>", file = File, append = TRUE, sep = "\n")
    try(assign(".HTML.graph", TRUE, env = get("HTMLenv", envir = .GlobalEnv)))
    invisible(return())
}

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

GetComponentsToExportInHTMLreport <- function(contrastParameterizationIndex=NULL)
{
  Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))  

  Try(ttHTMLreportDialog<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttHTMLreportDialog))
  Try(tkgrab.set(ttHTMLreportDialog))
  Try(tkfocus(ttHTMLreportDialog))
  Try(tkwm.title(ttHTMLreportDialog,"HTML Report"))
  Try(tkgrid(tklabel(ttHTMLreportDialog,text="    "),tklabel(ttHTMLreportDialog,text="    ")))

  Try(TargetsTcl                    <- tclVar("1"))  
  Try(NormalizationMethodTcl        <- tclVar("1"))
  Try(RawIntensityBoxPlotTcl        <- tclVar("1"))
  Try(NormalizedIntensityBoxPlotTcl <- tclVar("1"))  
  Try(DesignMatrixTcl               <- tclVar("1"))

  Try(if (NumContrastParameterizations>0)
    Try(ContrastMatrixTcl             <- tclVar("1"))
  else
    Try(ContrastMatrixTcl             <- tclVar("0")))
  Try(if (NumContrastParameterizations>0)
    Try(MAPlotsContrastsTcl           <- tclVar("1"))
  else
    Try(MAPlotsContrastsTcl           <- tclVar("0")))
  Try(if (NumContrastParameterizations>0)
    Try(Top50ToptablesTcl             <- tclVar("1"))
  else
    Try(Top50ToptablesTcl             <- tclVar("0")))
  Try(if (NumContrastParameterizations>0)    
    Try(CompleteToptablesTcl          <- tclVar("1"))
  else
    Try(CompleteToptablesTcl          <- tclVar("0")))
  Try(if (NumContrastParameterizations>0)  
    Try(Top50ToptablesTcl    <- tclVar("1"))    
  else
    Try(Top50ToptablesTcl    <- tclVar("0")))
  Try(CompleteToptablesTcl <- tclVar("0"))      

  Try(TargetsCheckbox                     <- tkcheckbutton(ttHTMLreportDialog,variable=TargetsTcl))
  Try(NormalizationMethodCheckbox         <- tkcheckbutton(ttHTMLreportDialog,variable=NormalizationMethodTcl))
  Try(RawIntensityBoxPlotCheckbox         <- tkcheckbutton(ttHTMLreportDialog,variable=RawIntensityBoxPlotTcl))
  Try(NormalizedIntensityBoxPlotCheckbox  <- tkcheckbutton(ttHTMLreportDialog,variable=NormalizedIntensityBoxPlotTcl))
  Try(DesignMatrixCheckbox                <- tkcheckbutton(ttHTMLreportDialog,variable=DesignMatrixTcl))
  Try(ContrastMatrixCheckbox              <- tkcheckbutton(ttHTMLreportDialog,variable=ContrastMatrixTcl))
  Try(MAPlotsContrastsCheckbox            <- tkcheckbutton(ttHTMLreportDialog,variable=MAPlotsContrastsTcl))
  Try(Top50ToptablesCheckbox              <- tkcheckbutton(ttHTMLreportDialog,variable=Top50ToptablesTcl))              
  Try(CompleteToptablesCheckbox           <- tkcheckbutton(ttHTMLreportDialog,variable=CompleteToptablesTcl))                

  Try(lbl2 <- tklabel(ttHTMLreportDialog,text="Components to be Included in the HTML Report",font=.affylmGUIglobals$affylmGUIfont2))
  tkgrid(tklabel(ttHTMLreportDialog,text="    "),lbl2)
  Try(tkgrid.configure(lbl2,columnspan=3,sticky="w"))
  tkgrid(tklabel(ttHTMLreportDialog,text="    "))
  
  Try(currentLabel <- tklabel(ttHTMLreportDialog,text="RNA Targets",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttHTMLreportDialog,text="    "),TargetsCheckbox,currentLabel))
  Try(tkgrid.configure(TargetsCheckbox,sticky="e"));  Try(tkgrid.configure(currentLabel,sticky="w",columnspan=2))
  Try(currentLabel <- tklabel(ttHTMLreportDialog,text="Normalization Method",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttHTMLreportDialog,text="    "),NormalizationMethodCheckbox,currentLabel))
  Try(tkgrid.configure(NormalizationMethodCheckbox,sticky="e"));  Try(tkgrid.configure(currentLabel,sticky="w",columnspan=2))  
  Try(currentLabel <- tklabel(ttHTMLreportDialog,text="Raw Intensity Box Plot",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttHTMLreportDialog,text="    "),RawIntensityBoxPlotCheckbox,currentLabel))
  Try(tkgrid.configure(RawIntensityBoxPlotCheckbox,sticky="e"));  Try(tkgrid.configure(currentLabel,sticky="w",columnspan=2))
  Try(currentLabel <- tklabel(ttHTMLreportDialog,text="Normalized Intensity Box Plot",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttHTMLreportDialog,text="    "),NormalizedIntensityBoxPlotCheckbox,currentLabel))
  Try(tkgrid.configure(NormalizedIntensityBoxPlotCheckbox,sticky="e"));  Try(tkgrid.configure(currentLabel,sticky="w",columnspan=2))
  Try(currentLabel <- tklabel(ttHTMLreportDialog,text="Design Matrix (Parameterization)",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttHTMLreportDialog,text="    "),DesignMatrixCheckbox,currentLabel))
  Try(tkgrid.configure(DesignMatrixCheckbox,sticky="e"));  Try(tkgrid.configure(currentLabel,sticky="w",columnspan=2))

  Try(currentLabel <- tklabel(ttHTMLreportDialog,text="Contrasts Matrix (Parameterization)",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttHTMLreportDialog,text="    "),ContrastMatrixCheckbox,currentLabel))
  Try(tkgrid.configure(ContrastMatrixCheckbox,sticky="e"));  Try(tkgrid.configure(currentLabel,sticky="w",columnspan=2))
  Try(currentLabel <- tklabel(ttHTMLreportDialog,text="M A Plots for Contrasts",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttHTMLreportDialog,text="    "),MAPlotsContrastsCheckbox,currentLabel))
  Try(tkgrid.configure(MAPlotsContrastsCheckbox,sticky="e"));  Try(tkgrid.configure(currentLabel,sticky="w",columnspan=2))
  Try(currentLabel <- tklabel(ttHTMLreportDialog,text="Top 50 DE Genes",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttHTMLreportDialog,text="    "),Top50ToptablesCheckbox,currentLabel))
  Try(tkgrid.configure(Top50ToptablesCheckbox,sticky="e"));  Try(tkgrid.configure(currentLabel,sticky="w",columnspan=2))
  Try(currentLabel <- tklabel(ttHTMLreportDialog,text="Complete Lists of DE-Ranked Genes",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttHTMLreportDialog,text="    "),CompleteToptablesCheckbox,currentLabel))
  Try(tkgrid.configure(CompleteToptablesCheckbox,sticky="e"));  Try(tkgrid.configure(currentLabel,sticky="w",columnspan=2))

  if (NumContrastParameterizations==0)
  {
    Try(tkconfigure(ContrastMatrixCheckbox,state="disabled"))
    Try(tkconfigure(MAPlotsContrastsCheckbox,state="disabled"))    
    Try(tkconfigure(Top50ToptablesCheckbox,state="disabled"))    
    Try(tkconfigure(CompleteToptablesCheckbox,state="disabled"))      
  }
  
  tkgrid(tklabel(ttHTMLreportDialog,text="    "))
  tkgrid(tklabel(ttHTMLreportDialog,text="    "))
  ReturnVal <- list()
  onOK <- function()
  {
      if (tclvalue(TargetsTcl)=="1") ReturnVal[["Targets"]] <- TRUE else ReturnVal[["Targets"]] <- FALSE
      if (tclvalue(NormalizationMethodTcl)=="1") ReturnVal[["NormalizationMethod"]] <- TRUE else ReturnVal[["NormalizationMethod"]] <- FALSE      
      if (tclvalue(RawIntensityBoxPlotTcl)=="1") ReturnVal[["RawIntensityBoxPlot"]] <- TRUE else ReturnVal[["RawIntensityBoxPlot"]] <- FALSE
      if (tclvalue(NormalizedIntensityBoxPlotTcl)=="1") ReturnVal[["NormalizedIntensityBoxPlot"]] <- TRUE else ReturnVal[["NormalizedIntensityBoxPlot"]] <- FALSE
      
      if (tclvalue(DesignMatrixTcl)=="1") ReturnVal[["DesignMatrix"]] <- TRUE else ReturnVal[["DesignMatrix"]] <- FALSE
      if (tclvalue(ContrastMatrixTcl)=="1") ReturnVal[["ContrastsMatrix"]] <- TRUE else ReturnVal[["ContrastsMatrix"]] <- FALSE
      if (tclvalue(MAPlotsContrastsTcl)=="1") ReturnVal[["MAPlotsContrasts"]] <- TRUE else ReturnVal[["MAPlotsContrasts"]] <- FALSE
      if (tclvalue(Top50ToptablesTcl)=="1") ReturnVal[["Top50ToptablesTcl"]] <- TRUE else ReturnVal[["Top50Toptables"]] <- FALSE
      if (tclvalue(CompleteToptablesTcl)=="1") ReturnVal[["CompleteToptablesTcl"]] <- TRUE else ReturnVal[["CompleteToptablesTcl"]] <- FALSE
      
      Try(tkgrab.release(ttHTMLreportDialog));Try(tkdestroy(ttHTMLreportDialog));Try(tkfocus(.affylmGUIglobals$ttMain))
      ReturnVal <<- ReturnVal
  }
  onCancel <- function() {Try(tkgrab.release(ttHTMLreportDialog));Try(tkdestroy(ttHTMLreportDialog));Try(tkfocus(.affylmGUIglobals$ttMain)); ReturnVal <<- list()}      
  OK.but <-tkbutton(ttHTMLreportDialog,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  Cancel.but <-tkbutton(ttHTMLreportDialog,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(tklabel(ttHTMLreportDialog,text="    "),tklabel(ttHTMLreportDialog,text="    "),OK.but,Cancel.but,tklabel(ttHTMLreportDialog,text="    "),tklabel(ttHTMLreportDialog,text="    "))
  tkgrid.configure(OK.but,    sticky="e")
  tkgrid.configure(Cancel.but,sticky="w")
  tkgrid(tklabel(ttHTMLreportDialog,text="    "),tklabel(ttHTMLreportDialog,text="    "),tklabel(ttHTMLreportDialog,text="    "),
       tklabel(ttHTMLreportDialog,text="    "),tklabel(ttHTMLreportDialog,text="    "))
  Try(tkfocus(ttHTMLreportDialog))
  Try(tkbind(ttHTMLreportDialog, "<Destroy>", function() {Try(tkgrab.release(ttHTMLreportDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkwait.window(ttHTMLreportDialog))

  return (ReturnVal)
  
  
}

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

ExportHTMLreport <- function()
{
# We will use the R2HTML package, but with my own HTMLplot function.
# Will we need xtable or does R2HTML have its own HTMLtable function?
  Require("xtable")
  Require("R2HTML")

  Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment))   
  Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))  
  Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
  Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
  
  if (ArraysLoaded==FALSE)
  {
      Try(tkmessageBox(title="Export HTML Report",message="No arrays have been loaded.  Please try New or Open from the File menu.",type="ok",icon="error"))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      return()
  }

  if (NumContrastParameterizations>0)
  {
		Try(contrastParameterizationIndex <- ChooseContrastParameterization())
		Try(if (contrastParameterizationIndex==0) return()) # Cancel
    
    Try(ContrastParameterizationNamesVec <- get("ContrastParameterizationNamesVec",envir=affylmGUIenvironment))
		Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
		Try(contrastsMatrix <- as.matrix(ContrastParameterizationList[[contrastParameterizationIndex]]$contrastsMatrixInList$contrasts))
		Try(ContrastNamesVec  <- colnames(contrastsMatrix))
    Try(NumContrasts <- length(ContrastNamesVec))
    Try(ContrastParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
  	Try(fit <- (ContrastParameterizationList[[ContrastParameterizationNameNode]])$fit)
  	Try(fit <- eBayes(fit))
    
    Try(ComponentsToExport <- GetComponentsToExportInHTMLreport(contrastParameterizationIndex))
 }
 else
     Try(ComponentsToExport <- GetComponentsToExportInHTMLreport())
  
  Try(if (length(ComponentsToExport)==0) return())

  Try(fileNameWithPath<- tkgetSaveFile(initialfile=limmaDataSetNameText,filetypes="{{HTML Files} {.html .htm}} {{All files} *}"))  
  Try(if (nchar(tclvalue(fileNameWithPath))==0)
    return())
  Try(path     <- tclvalue(tkfile.dir (tclvalue(fileNameWithPath))))
  Try(fileName <- tclvalue(tkfile.tail(tclvalue(fileNameWithPath))))
   
  Try(len <- nchar(fileName))
  if (len<4)
      Try(fileName <- paste(fileName,".html",sep=""))
  else if   ((tolower(substring(fileName,len-4,len))!=".html") &&
  (len<5 ||  (tolower(substring(fileName,len-4,len))!=".html")))
          Try(fileName <- paste(fileName,".html",sep=""))

  Try(fileNameWithoutExtension <- substring(fileName,1,nchar(fileName)-5))
                                                                
  Try(HTMLfilePath <- paste(path,.Platform$file.sep,fileNameWithoutExtension,"_files",sep=""))
  Try(HTMLfileRelativePath <- paste(fileNameWithoutExtension,"_files",sep=""))
  Try(dir.create(HTMLfilePath))
  
  Try(fileNameWithPath <- paste(path,"/",fileName,sep=""))                                                 

  Try(R2HTMLpath <- system.file(package="R2HTML","output"))
  Try(cssFileSource <- paste(R2HTMLpath,"/","R2HTML.css",sep=""))
  Try(cssFileDestination <- paste(path,"/","R2HTML.css",sep=""))  
  Try(R2HTMLlogoSource <- paste(R2HTMLpath,"/","R2HTMLlogo.gif",sep=""))
  Try(R2HTMLlogoDestination <- paste(path,"/","R2HTMLlogo.gif",sep=""))  
  Try(file.copy(cssFileSource,cssFileDestination,overwrite=TRUE))  
  Try(file.copy(R2HTMLlogoSource,R2HTMLlogoDestination,overwrite=TRUE))    

  Try(HTMLtarget <- HTMLInitFile(path,filename=fileNameWithoutExtension,Title=paste(limmaDataSetNameText,"- Statistical Microarray Analysis using affylmGUI"), HTMLframe=FALSE,BackGroundColor="#FFFFFF"))

  Try(HTML.title(paste(limmaDataSetNameText,"- Statistical Microarray Analysis using affylmGUI"),HR=1))

  Try(ExportTargets                    <- ComponentsToExport$Targets)  
  Try(ExportNormalizationMethod        <- ComponentsToExport$NormalizationMethod)    
  Try(ExportRawIntensityBoxPlot        <- ComponentsToExport$RawIntensityBoxPlot)    
  Try(ExportNormalizedIntensityBoxPlot <- ComponentsToExport$NormalizedIntensityBoxPlot)      
  Try(ExportDesignMatrix               <- ComponentsToExport$DesignMatrix)
  Try(ExportContrastsMatrix            <- ComponentsToExport$ContrastsMatrix)  
  Try(ExportMAPlotsContrasts           <- ComponentsToExport$MAPlotsContrasts)
  Try(ExportTop50Toptables             <- ComponentsToExport$Top50Toptables)    
  Try(ExportCompleteToptables          <- ComponentsToExport$CompleteToptables)      

  if (ExportRawIntensityBoxPlot || ExportNormalizedIntensityBoxPlot || ExportMAPlotsContrasts)
  {
    Try(if (exists("X11", env=.GlobalEnv) && Sys.info()["sysname"] != "Windows" && Sys.info()["sysname"] != "Darwin")  
    {
      Try(pngParams <- GetJpegOrPngX11Params(graphFileType="PNG"))  
      Try(if (length(pngParams)==0) return())
      Try(plotBG        <- pngParams$bg)
      Try(plotRes       <- pngParams$res)    
    }
    else
    {
      Try(pngParams <- GetJpegOrPngParams(graphFileType="PNG"))
      Try(if (length(pngParams)==0) return())    
      Try(plotWidth     <- pngParams$width)
      Try(plotHeight    <- pngParams$height)
      Try(plotPointSize <- pngParams$pointsize)
      Try(plotBG        <- pngParams$bg)
    })    
  }

  Try(HTML.title("Contents",HR=2))
  Try(if (ExportTargets) Try(HTMLli(txt="<a href=\"#Targets\"><b>Targets</b></a>")))
  Try(if (ExportNormalizationMethod) Try(HTMLli(txt="<a href=\"#NormalizationMethod\"><b>Normalization Method</b></a>")))
  Try(if (ExportRawIntensityBoxPlot) Try(HTMLli(txt="<a href=\"#RawIntensityBoxPlot\"><b>Raw Intensity Box Plot</b></a>")))
  Try(if (ExportNormalizedIntensityBoxPlot) Try(HTMLli(txt="<a href=\"#NormalizedIntensityBoxPlot\"><b>Normalized Intensity Box Plot</b></a>")))
  Try(if (ExportDesignMatrix) Try(HTMLli(txt="<a href=\"#DesignMatrix\"><b>Design Matrix</b></a>")))
  Try(if (ExportContrastsMatrix) Try(HTMLli(txt="<a href=\"#ContrastsMatrix\"><b>Contrasts Matrix</b></a>")))
  Try(if (ExportMAPlotsContrasts) Try(HTMLli(txt="<a href=\"#MAPlotsContrasts\"><b>M A Plots for Contrasts</b></a>")))
  Try(if (ExportTop50Toptables) Try(HTMLli(txt="<a href=\"#Top50Toptables\"><b>Tables of Top 50 Differentially Expressed Genes</b></a>")))
  Try(if (ExportCompleteToptables) Try(HTMLli(txt="<a href=\"#CompleteToptables\"><b>Complete Tables of Genes Ranked in order of Evidence for Differential Expression</b></a>")))

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

  if (ExportTargets)
  {
    Try(Targets <- get("Targets",envir=affylmGUIenvironment))
    Try(displayVector <- rep("s",ncol(Targets)+1))
    Try(for (i in (0:ncol(Targets)))
      if (i==0 || colnames(Targets)[i]=="SlideNumber")
        displayVector[i] <- "d")
    Try(TargetsXtable <- xtable(Targets,display=displayVector))
    Try(HTML.title("<a name=\"Targets\">RNA Targets</a>",HR=2))
    Try(print(TargetsXtable,type="html",file=fileNameWithPath,append=TRUE))    
  }

  if (ExportNormalizationMethod)
  {
    Try(NormMethod <- get("NormMethod", envir=affylmGUIenvironment))
    Try(HTML.title("<a name=\"NormalizationMethod\">Normalization method</a>",HR=2))
    Try(if (NormMethod=="RMA")
      Try(HTMLli(txt="<b>RMA (Robust Multiarray Averaging)</b>")) else
        Try(HTMLli(txt="<b>PLM (Robust Probe-level Linear Model)</b>")))
  }

  if (ExportRawIntensityBoxPlot)
  {
    Try(HTML.title("<a name=\"RawIntensityBoxPlot\">Raw (Unnormalized) Intensity Box Plot</a>",HR=2))
    Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))
    Try(SlideNamesVec  <- get("SlideNamesVec",envir=affylmGUIenvironment))    
    Try(LocalHScale <- get("Myhscale",envir=.GlobalEnv))
     Try(plotFunction <- function() 
    {
      Try(opar<-par(bg="white",cex=0.7))
      Try(boxplot(RawAffyData,col="red",las=2,names=SlideNamesVec))
      Try(title(plotTitle))
      Try(tmp<-par(opar))
    }) 
    Try(plotTitle <- "Raw intensity distribution for each slide")
    Try(HTMLplotUsingFunction(Caption = plotTitle, File = fileNameWithPath, GraphRelativeDirectory = HTMLfileRelativePath , 
        GraphAbsoluteDirectory = HTMLfilePath, GraphFileName = "RawIntensityBoxPlot", 
        GraphSaveAs = "png", GraphBorder = 1,  Align = "left", plotFunction=plotFunction,
        Width=plotWidth,Height=plotHeight,PointSize=plotPointSize,BG=plotBG,res=plotRes))      
  }
  
  if (ExportNormalizedIntensityBoxPlot)
  {
    Try(HTML.title("<a name=\"NormalizedIntensityBoxPlot\">Normalized Intensity Box Plot</a>",HR=2))
    Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
    Try(SlideNamesVec  <- get("SlideNamesVec",envir=affylmGUIenvironment))    
    Try(LocalHScale <- get("Myhscale",envir=.GlobalEnv))
		Try(plotFunction <- function() 
		{
			Try(opar<-par(bg="white",cex=0.7))
			Try(boxplot(data.frame(exprs(NormalizedAffyData)),col="blue",las=2,names=SlideNamesVec))
			Try(title(plotTitle))			
			Try(tmp<-par(opar))
		}) 
		Try(plotTitle<-"Normalized intensity distribution for each slide")
    Try(HTMLplotUsingFunction(Caption = plotTitle, File = fileNameWithPath, GraphRelativeDirectory = HTMLfileRelativePath , 
        GraphAbsoluteDirectory = HTMLfilePath, GraphFileName = "NormalizedIntensityBoxPlot", 
        GraphSaveAs = "png", GraphBorder = 1,  Align = "left", plotFunction=plotFunction,
        Width=plotWidth,Height=plotHeight,PointSize=plotPointSize,BG=plotBG,res=plotRes))      
  }


  if (ExportDesignMatrix)
  {
    Try(design <- get("design",envir=affylmGUIenvironment))
    Try(displayVector <- rep("g",ncol(design)+1))
    Try(displayVector[0] <- "s")
    Try(DesignXtable <- xtable(design,display=displayVector))
    Try(HTML.title("<a name=\"DesignMatrix\">Design Matrix</a>",HR=2))
    Try(print(DesignXtable,type="html",file=fileNameWithPath,append=TRUE))    
  }

  if (ExportContrastsMatrix)
  {
    Try(displayVector <- rep("g",ncol(contrastsMatrix)+1))
    Try(displayVector[0] <- "s")
    Try(ContrastsXtable <- xtable(contrastsMatrix,display=displayVector))
    Try(HTML.title("<a name=\"ContrastsMatrix\">Contrasts Matrix</a>",HR=2))
    Try(print(ContrastsXtable,type="html",file=fileNameWithPath,append=TRUE))      
  }

  if (ExportMAPlotsContrasts)
  {		
    Try(HTML.title("<a name=\"MAPlotsContrasts\">M A Plots for Contrasts</a>",HR=2))
		Try(A <- rowMeans(exprs(NormalizedAffyData)))
		Try(pch <- 16)
		Try(cex <- 0.2)

    Try(for (contrast in (1:NumContrasts))
    {
      Try(plotTitle<-paste("M A Plot (",ContrastNamesVec[contrast],")",sep=""))
      Try(HTML.title(plotTitle,HR=2))
      Try(M <- fit$coefficients[,contrast])
		  Try(plotFunction <- function() 
		  {
		   Try(opar<-par(bg="white"))
		   Try(plot(A,M,pch=pch,cex=cex,xlab="A",ylab="M",main=plotTitle))
		   Try(tmp<-par(opar))
		  }) 
      Try(HTMLplotUsingFunction(Caption = plotTitle, File = fileNameWithPath, GraphRelativeDirectory = HTMLfileRelativePath , 
        GraphAbsoluteDirectory = HTMLfilePath, GraphFileName = paste("contrastMAplot.",contrast,sep=""), 
        GraphSaveAs = "png", GraphBorder = 1,  Align = "left", plotFunction=plotFunction,
        Width=plotWidth,Height=plotHeight,PointSize=plotPointSize,BG=plotBG,res=plotRes))
		})
  }

  if (ExportTop50Toptables || ExportCompleteToptables)
  {
    Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))
    Try(cdfenv<-getCdfInfo(RawAffyData))      
		Try(genelist <- data.frame(ID=I(ls(cdfenv))))

		Try(geneNames <- get("geneNames",envir=affylmGUIenvironment))
		Try(geneSymbols <- get("geneSymbols",envir=affylmGUIenvironment))		
		Try(if (length(geneNames)==0||length(geneSymbols)==0)
		{
			Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))  
			Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))
			Try(dataName <- strsplit(cleancdfname(RawAffyData@cdfName),"cdf")[[1]])
			Require("reposTools")
			Try(annoPackages <- getReposEntry("http://www.bioconductor.org/data/metaData"))    
			Try(matchIndex <- match(dataName,annoPackages@repdatadesc@repdatadesc[,"Package"]))
			Try(if (!is.na(matchIndex))
			{
				Try(install.packages2(dataName,annoPackages))
				Require(dataName)
				Try(code2eval <- paste("Try(geneNames <- as.character(unlist(multiget(ls(envir=",dataName,"GENENAME),env=",dataName,"GENENAME))))",sep=""))
				Try(eval(parse(text=code2eval)))
				Try(assign("geneNames",geneNames,affylmGUIenvironment))
				Try(code2eval <- paste("Try(geneSymbols <- as.character(unlist(multiget(ls(envir=",dataName,"SYMBOL),env=",dataName,"SYMBOL))))",sep=""))
				Try(eval(parse(text=code2eval)))
				Try(assign("geneSymbols",geneSymbols,affylmGUIenvironment))
				Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
				Try(genelist <- cbind(as.matrix(as.character(ls(cdfenv))),as.matrix(geneSymbols),as.matrix(geneNames)))
				Try(colnames(genelist) <- c("ID","Symbol","Name"))
			}
			else
			{
				Try(genelist <- data.frame(ID=I(ls(cdfenv))))
				Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
			})

		}
		else
		{
			Try(genelist <- cbind(as.matrix(as.character(ls(cdfenv))),as.matrix(geneSymbols),as.matrix(geneNames)))
			Try(colnames(genelist) <- c("ID","Symbol","Name"))  
		})    
  }

  if (ExportTop50Toptables)
  {
    Try(HTML.title(paste("<a name=\"Top50Toptables\">Top 50 Differentially Expressed Genes for each Contrast in Contrasts Parameterization ",
      ContrastParameterizationNamesVec[contrastParameterizationIndex],"</a>",sep=""),HR=2))
    Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
	  Try(if (!("Amean" %in% names(fit)))
	    fit$Amean <- rowMeans(exprs(NormalizedAffyData)))
    Try(fit$genes <- genelist)
    
    for (coef in (1:NumContrasts))
    {
      Try(options(digits=3))
      Try(table1 <- topTable2(coef=coef,number=50,genelist=genelist,fit=fit))
      Try(toptableDisplay <- rep("s",ncol(table1)+1))
      Try(toptableDisplay[1] <- "d")
      Try(for (i in (2:(ncol(table1)+1)))
      {                
        Try(if (colnames(table1)[i-1]=="M")       toptableDisplay[i] <- "f")      
        Try(if (colnames(table1)[i-1]=="A")       toptableDisplay[i] <- "f")              
        Try(if (colnames(table1)[i-1]=="t")       toptableDisplay[i] <- "f")                      
        Try(if (colnames(table1)[i-1]=="P.Value") toptableDisplay[i] <- "e")                                            
        Try(if (colnames(table1)[i-1]=="B") toptableDisplay[i] <- "f")                                      
      })
      Try(toptableXtable <- xtable(table1,display=toptableDisplay))
      Try(HTML.title(paste("Top 50 Differentially Expressed Genes for",ContrastNamesVec[coef]),HR=3))
      Try(print(toptableXtable,type="html",file=fileNameWithPath,append=TRUE))
    }
  
  }
  
  if (ExportCompleteToptables) 
  {
    Try(HTML.title(paste("<a name=\"CompleteToptables\">Complete Tables of Genes Ranked in order of Evidence for Differential Expression for each contrast in Contrasts Parameterization ",ContrastParameterizationNamesVec[contrastParameterizationIndex],"</a>",sep=""),HR=2))     

    Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
	  Try(if (!("Amean" %in% names(fit)))
	    fit$Amean <- rowMeans(exprs(NormalizedAffyData)))
    Try(fit$genes <- genelist)
    
    for (coef in (1:NumContrasts))
    {
      Try(options(digits=3))
      Try(table1 <- topTable2(coef=coef,number=nrow(genelist),genelist=genelist,fit=fit))
      Try(ToptableAbsoluteFilename <- paste(HTMLfilePath ,.Platform$file.sep,"CompleteToptable_Contrast",coef,".txt",sep=""))
      Try(ToptableRelativeFilename <- paste(HTMLfileRelativePath ,.Platform$file.sep,"CompleteToptable_Contrast",coef,".txt",sep=""))
      Try(write.table(table1,file=ToptableAbsoluteFilename,quote=FALSE,col.names=NA,sep="\t"))      
      Try(HTML.title(paste("Complete Table of Genes Ranked in order of Evidence for Differential Expression for ",ContrastNamesVec[coef]),HR=3))
      Try(HTMLli(txt=paste("<a href=\"",ToptableRelativeFilename,"\"><b>",paste("CompleteToptable_Contrast",coef,".txt",sep=""),"</b></a>",sep=""))) 
    }  
  }
  

  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkfocus(.affylmGUIglobals$ttMain))    
  Try(HTMLhr())
  Try(HTMLli(txt="This report was generated by "))
  Try(HTMLli(txt=paste("affylmGUI Version",getPackageVersion("affylmGUI"),"(by James Wettenhall), using")))
  Try(HTMLli(txt=paste("affy Version",getPackageVersion("affy"),"(by Rafael A. Irizarry, Laurent Gautier and Benjamin Bolstad),")))
  Try(HTMLli(txt=paste("affyPLM Version",getPackageVersion("affyPLM"),"(by Benjamin Bolstad),")))
  Try(HTMLli(txt=paste("limma Version",getPackageVersion("limma"),"(by Gordon Smyth),")))
  Try(HTMLli(txt=paste("R2HTML Version",getPackageVersion("R2HTML"),"(by Eric Lecoutre) and ")))
  Try(HTMLli(txt=paste("xtable Version",getPackageVersion("xtable"),"(by David Dahl)")))
  Try(HTMLEndFile())

}

if (require(limma)==FALSE)
{
    if (interactive())
      tkmessageBox(title="An error has occured!",message=paste("Cannot find package limma"),icon="error",type="ok")
    stop("Cannot find package limma")
}

if (require(affy)==FALSE)
{
    if (interactive())
      tkmessageBox(title="An error has occured!",message=paste("Cannot find package affy"),icon="error",type="ok")
    stop("Cannot find package affy")
}


Try <- function(expr) 
{
    if (data.class(result<-try(expr,TRUE))=="try-error")
    {
        tkmessageBox(title="An error has occured!",message=as.character(result),icon="error",type="ok")
    } 
    else 
    {
        return (result)
    }
}

TryReadImgProcFile <- function(expr) 
{
    if (data.class(result<-try(expr,TRUE))=="try-error")
    {
        tkmessageBox(title="Reading Image Processing Files Failed!",
          message="affylmGUI was unable to read the CEL files listed in the Targets file.",icon="error",type="ok")
    } 
    else 
    {
        return (result)
    }
}


Require <- function(pkg) 
{
    if (data.class(result<-try(.find.package(pkg),TRUE))=="try-error")
    {
        tkmessageBox(title="An error has occured!",message=paste("Cannot find package",pkg),icon="error",type="ok")
    } 
    else 
    {
        result <- Try(require(pkg,character.only=TRUE))
    }
    return (result)
}

TclRequire <- function(tclPkg)
{
    if ((data.class(result<-try(tclRequire(tclPkg),TRUE))=="try-error") || (is.logical(result) && result==FALSE))
    {
      affylmGUIglobals <- .affylmGUIglobals
      affylmGUIglobals$TclRequireFailed <- TRUE
      assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv)
      Try(winTitle<-"Tcl/Tk Extension(s) Not Found")
      Try(message<-paste("Cannot find Tcl/Tk package \"", tclPkg,
      "\".  affylmGUI cannot continue.\n\n",
      "affylmGUI requires the Tcl/Tk extensions, BWidget and Tktable.\n",
      "You must have Tcl/Tk installed on your computer, not just the minimal\n",
      "Tcl/Tk installation which comes with R (for Windows).  If you do have\n",
      "Tcl/Tk installed, including the extensions (e.g. using the ActiveTcl\n",
      "distribution in Windows), make sure that R can find the path to the\n",
      "Tcl library, e.g. C:\\Tcl\\lib (on Windows) or /usr/lib (on Linux/Unix)\n",
      "or /sw/lib on Mac OSX.\n\n",
      "If you don't know how to set environment variables in Windows, one way\n",
      "to make sure that R can find the Tcl/Tk extensions Tktable2.8 and bwidget1.6\n",
      "is to copy them from your ActiveTcl installation e.g. in C:\\Tcl\\lib into\n",
      "the Tcl subdirectory of your R installation.\n",
      "If you do understand how to set environment variables...\n",
      "make sure that you have the TCL_LIBRARY environment variable set to the\n",
      "appropriate path, e.g.C:\\Tcl\\lib\\tcl8.4 and the MY_TCLTK environment\n",
      "variable set to a non-empty string, e.g. \"Yes\".\n\n",
      "If using Windows, be sure to read the R for windows FAQ at\nhttp://www.stats.ox.ac.uk/pub/R/rw-FAQ.html\n\n",
      "If your Tcl/Tk extensions still can't be found, try\n",
      "addTclPath(\"<path to Tcl library>\").\nThis could be put in $HOME/.Rprofile\n\n",
      "If you need further instructions, please contact your system administrator\n",
      "and consider emailing r-help@stat.math.ethz.ch, or browse through the R-help\n",
      "archives for a similar question.\n\n",
      "The URLs for Tktable and BWidget are:\n",
      "http://tktable.sourceforge.net\n",
      "http://tcllib.sourceforge.net",      
      sep=""))
      
      # Don't make ttMain a parent of this, because we might want to use TclRequire before
      # defining ttMain.
      Try(ttTclTkExtension <- tktoplevel())
      onDestroy <- function()
      {
        if (exists(".affylmGUIglobals",envir=.GlobalEnv)&&"ttMain" %in% names(.affylmGUIglobals))
          try(tkdestroy(.affylmGUIglobals$ttMain),silent=TRUE)        
        else
          stop("Tcl/Tk extensions (Tktable and BWidget) not found!")
        stop("Aborted from affylmGUI.")
      }
	    Try(tkbind(ttTclTkExtension, "<Destroy>", onDestroy))
      Try(tkwm.title(ttTclTkExtension,winTitle))
      Try(tkwm.deiconify(ttTclTkExtension))
      Try(scr <- tkscrollbar(ttTclTkExtension, repeatinterval=5,
                             command=function(...)tkyview(txt,...)))
      Try(txt <- tktext(ttTclTkExtension,bg="white",yscrollcommand=function(...)tkset(scr,...)))
      Try(tkgrid(txt,scr,columnspan=2))
      Try(tkgrid.configure(scr,columnspan=1,sticky="ns"))
      Try(tkgrid.configure(txt,sticky="nsew"))
      Try(tkinsert(txt,"end",message))
      Try(tkconfigure(txt, state="disabled"))
      Try(tkfocus(txt))
      Try(onOK <- function() 
      {
        try(tkdestroy(ttTclTkExtension),silent=TRUE)
        if (exists(".affylmGUIglobals",envir=.GlobalEnv)&&"ttMain" %in% names(.affylmGUIglobals))
          try(tkdestroy(.affylmGUIglobals$ttMain),silent=TRUE)        
        else
          stop("Tcl/Tk extensions (Tktable and BWidget) not found!")
        Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))    
        Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
        if (limmaDataSetNameText!="Untitled")
        {
          Try(if (LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
          Try(mbVal <- tkmessageBox(title="Aborting from affylmGUI",
                message=paste("Save changes to ",LimmaFileName,"?",sep=""),
                icon="question",type="yesno",default="yes"))
          try(if (tclvalue(mbVal)=="yes")
              try(SaveLimmaFile(),silent=TRUE),silent=TRUE)
         }
         stop("Tcl/Tk extensions (Tktable and BWidget) not found!")
      })
      Try(OK.but <- tkbutton(ttTclTkExtension,text="  OK  ",command=onOK))  
      Try(tkgrid.configure(txt,columnspan=2))
      Try(tkgrid(tklabel(ttTclTkExtension,text="    ")))
      Try(tkgrid(tklabel(ttTclTkExtension,text="affylmGUI will now exit."),columnspan=2))
      Try(tkgrid(tklabel(ttTclTkExtension,text="    ")))      
      Try(tkgrid(OK.but))
      Try(tkgrid.configure(OK.but,sticky="e"))
      Try(tkgrid(tklabel(ttTclTkExtension,text="    ")))    
      Try(tkfocus(OK.but))
      Try(tkwait.window(ttTclTkExtension))            
    }
}

 
affylmGUIhelp <- function() 
{
	Try(affylmGUIhelpIndex <- file.path(system.file("doc",package="affylmGUI"),"index.html"))
	Try(browseURL(affylmGUIhelpIndex))
	Try(tkmessageBox(title="affylmGUI Help",message=paste("Opening affylmGUI help...\nIf nothing happens, please open :\n",affylmGUIhelpIndex,"\nyourself.",sep="")))
}

limmaHelp <- function() 
{
	Try(limmaHelpIndex <- file.path(system.file("doc",package="limma"),"usersguide.html"))
	Try(browseURL(limmaHelpIndex))
	Try(tkmessageBox(title="limma Help",message=paste("Opening limma help...\nIf nothing happens, please open :\n",limmaHelpIndex,"\nyourself.",sep="")))
}

affyHelp <- function() 
{
	Try(affyHelpIndex <- paste(system.file("doc",package="affy"),"affy.pdf",sep="/"))
	Try(browseURL(affyHelpIndex))
	Try(tkmessageBox(title="affy Help",message=paste("Opening affy help...\nIf nothing happens, please open :\n",affyHelpIndex,"\nyourself.",sep="")))
}

Try(onDestroy <- function()
{
	Try(.JustAskedWhetherToSave <- get(".JustAskedWhetherToSave",envir=.GlobalEnv))    
	Try(if (.JustAskedWhetherToSave==FALSE)
	{
		Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))    
		Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
		if (limmaDataSetNameText!="Untitled")
		{
			Try(if (LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only
			Try(mbVal <- tkmessageBox(title="Aborting from affylmGUI",
						message=paste("Save changes to ",LimmaFileName,"?",sep=""),
						icon="question",type="yesno",default="yes"))
			try(if (tclvalue(mbVal)=="yes")
					try(SaveLimmaFile(),silent=TRUE),silent=TRUE)              
		}
		Try(assign(".JustAskedWhetherToSave",TRUE,.GlobalEnv))
	})
})    

affylmGUI <- function(BigfontsForaffylmGUIpresentation=FALSE)
{
  assign("affylmGUIenvironment",new.env(),.GlobalEnv)
  assign("Try",get("Try",envir=.GlobalEnv),affylmGUIenvironment)
  # This option is for when I give a Presentation/talk on affylmGUI and want large affylmGUIfonts.  Currently, there are
  # some affylmGUIfonts which affylmGUI can't control, like menus, so as well as changing .affylmGUIglobals$affylmGUIpresentation to TRUE here, I
  # Right-Click the Windows Desktop, click Properties (to get Display properties which can also be accessed
  # through the Control Panel) then click on Appearance, and then change the affylmGUIfont size for menu,window title, etc.)
  # Rather than change each affylmGUIfont (menu,window title,...) manually each time, I save the changes as a "scheme".  
  Try(affylmGUIglobals <- list())
  Try(if (BigfontsForaffylmGUIpresentation==TRUE)
    Try(affylmGUIglobals$affylmGUIpresentation <- TRUE)
  else
    Try(affylmGUIglobals$affylmGUIpresentation <- FALSE))
  Try(affylmGUIglobals$limmaDataSetNameTcl <- tclVar("Untitled"))
  Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))

  Try(initGlobals())

  Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=.GlobalEnv))  
  Try(affylmGUIglobals$Myhscale <- 1)
  Try(affylmGUIglobals$Myvscale <- 1)
  Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
  
  Try(if (exists("X11", env=.GlobalEnv) && Sys.info()["sysname"] != "Windows") 
  {
 
   Try(if (Sys.info()["sysname"]=="Darwin")
   {
     Try(addTclPath("/sw/lib/tcl8.4"))
     Try(addTclPath("/sw/lib"))
     Try(addTclPath("./lib"))
     Try(addTclPath("/sw/lib/tk8.4"))
     Try(addTclPath(paste(Sys.getenv("HOME"),.Platform$file.sep,"TkExtensions",sep="")))
   })    
   Try(addTclPath("/usr/local/lib"))
   Try(addTclPath("/usr/local/Tcl/lib"))
   Try(addTclPath("/usr/local/lib/Tcl"))
   Try(addTclPath("/usr/lib"))
   Try(addTclPath("/usr/lib/Tcl"))
   Try(addTclPath("/usr/local/ActiveTcl/lib"))
   Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=.GlobalEnv))  
   Try(affylmGUIglobals$Myhscale <- 1)
   Try(affylmGUIglobals$Myvscale <- 1)
   Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
 })

  Try(if (Sys.info()["sysname"] == "Windows") 
  {
   Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=.GlobalEnv))  
   Try(affylmGUIglobals$Myhscale <- 1.6)
   Try(affylmGUIglobals$Myvscale <- 1.6)
   Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
  })

  Try(if (Sys.info()["sysname"] == "Darwin" && !exists("X11", env=.GlobalEnv)) 
  {
    Try(addTclPath("/Library/Tcl"))
    Try(addTclPath("/Network/Library/Tcl"))
    Try(addTclPath("/System/Library/Tcl"))
    Try(addTclPath("/Library/Frameworks/Tcl"))
    Try(HOME <- Sys.getenv("HOME"))
    Try(if (nchar(HOME)>0)
    {
      Try(addTclPath(paste(HOME,"/Library/Tcl",sep="")))
      Try(addTclPath(paste(HOME,"/Network/Library/Tcl",sep="")))
      Try(addTclPath(paste(HOME,"/System/Library/Tcl",sep="")))
      Try(addTclPath(paste(HOME,"/Library/Frameworks/Tcl",sep="")))
    })
    Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=.GlobalEnv))  
    Try(affylmGUIglobals$Myhscale <- 1)
    Try(affylmGUIglobals$Myvscale <- 1)
    Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
  })

  Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=.GlobalEnv))
  Try(if (.affylmGUIglobals$affylmGUIpresentation==TRUE)
    Try(affylmGUIglobals$affylmGUIfont1  <- tkfont.create(family="times",size=48,weight="bold",slant="italic"))
  else
    Try(affylmGUIglobals$affylmGUIfont1  <- tkfont.create(family="times",size=24,weight="bold",slant="italic")))
  Try(if (.affylmGUIglobals$affylmGUIpresentation==TRUE)  
    Try(affylmGUIglobals$affylmGUIfont2 <- tkfont.create(family="arial",size=16))
  else
    Try(affylmGUIglobals$affylmGUIfont2 <- tkfont.create(family="arial",size=10)))
  Try(if (.affylmGUIglobals$affylmGUIpresentation==TRUE)  
    Try(affylmGUIglobals$affylmGUIfontTree <- tkfont.create(family="arial",size=14))
  else
    Try(affylmGUIglobals$affylmGUIfontTree <- tkfont.create(family="arial",size=10)))

  Try(if (.affylmGUIglobals$affylmGUIpresentation==TRUE)  
    Try(affylmGUIglobals$affylmGUIfontTable <- tkfont.create(family="arial",size=16))
  else
    Try(affylmGUIglobals$affylmGUIfontTable <- tkfont.create(family="arial",size=10)))
  Try(if (.affylmGUIglobals$affylmGUIpresentation==TRUE)  
    Try(affylmGUIglobals$affylmGUIfontTopTable <- tkfont.create(family="arial",size=12,weight="bold"))
  else
    Try(affylmGUIglobals$affylmGUIfontTopTable <- affylmGUIglobals$affylmGUIfontTable))

  Try(if (.affylmGUIglobals$affylmGUIpresentation==TRUE)    
    Try(affylmGUIglobals$affylmGUIfont2b <- tkfont.create(family="arial",size=16,weight="bold"))
  else
    Try(affylmGUIglobals$affylmGUIfont2b <- tkfont.create(family="arial",size=10,weight="bold")))

  Try(if (.affylmGUIglobals$affylmGUIpresentation==TRUE)  
    Try(affylmGUIglobals$affylmGUIfontCourier <- tkfont.create(family="courier",size=16))
  else
    Try(affylmGUIglobals$affylmGUIfontCourier <- tkfont.create(family="courier",size=10)))

  Try(affylmGUIglobals$mainTreeWidth <- 30)

  Try(if (.affylmGUIglobals$affylmGUIpresentation==TRUE)
    Try(affylmGUIglobals$ContrastParameterizationTREEWidth <- 40)
  else
    Try(affylmGUIglobals$ContrastParameterizationTREEWidth <- 30))

  Try(if (.affylmGUIglobals$affylmGUIpresentation==TRUE)
  {
    Try(affylmGUIglobals$ContrastParameterizationTREEHeight <- 20)
    Try(affylmGUIglobals$mainTreeHeight <- 20)
  }
  else
  {
    Try(affylmGUIglobals$ContrastParameterizationTREEHeight <- 15)
    Try(affylmGUIglobals$mainTreeHeight <- 15)
  })
  # Try(assign("affylmGUIfontMenu",tkfont.create(family="arial",size=10),.GlobalEnv))

  Try(affylmGUIglobals$ttMain <- tktoplevel())  
  Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
  Try(tkbind(.affylmGUIglobals$ttMain, "<Destroy>", onDestroy))

  TclRequire("BWidget")
  if ("TclRequireFailed" %in% names(.affylmGUIglobals))
    stop("Error occurred in TclRequire(\"BWidget\")")
  TclRequire("Tktable")
  if ("TclRequireFailed" %in% names(.affylmGUIglobals))  
    stop("Error occurred in TclRequire(\"Tktable\")")

  # Try(assign("opar",par(bg="white"),.GlobalEnv))
  Try(oldOptions <- options(warn=-1)) # Otherwise R complains that I'm trying to set main in plots, i.e. set a plot title)
# Maybe it would be nice to eventually use the MainFrame widget from BWidget so we can have a nice toolbar etc.

  Try(if (.affylmGUIglobals$affylmGUIpresentation==FALSE)
    Try(mainFrame <- tkframe(.affylmGUIglobals$ttMain,relief="groove",borderwidth="2"))
  else
    Try(mainFrame <- tkframe(.affylmGUIglobals$ttMain)))    
  Try(if (.affylmGUIglobals$affylmGUIpresentation==FALSE)
  {
    Try(toolbarFrame <- tkframe(mainFrame,relief="groove",borderwidth="2"))
    Try(tb <- tkframe(toolbarFrame,relief="groove",borderwidth="2"))
    # The Bitmap::get stuff below requires the BWidget package.
    # I think this could be done more simply with something like :
    #   Try(newButton <- tkbutton(tb,image=tkcmd("Bitmap::get"new"),command=NewLimmaFile))
    Try(newButton <- .Tcl(paste("button",.Tk.subwin(tb),"-image [Bitmap::get new]",.Tcl.args(command=NewLimmaFile))))
    Try(openButton <- .Tcl(paste("button",.Tk.subwin(tb),"-image [Bitmap::get open]",.Tcl.args(command=OpenLimmaFile))))
    Try(saveButton <- .Tcl(paste("button",.Tk.subwin(tb),"-image [Bitmap::get save]",.Tcl.args(command=SaveLimmaFile))))  
    Try(tkgrid(newButton,openButton,saveButton,sticky="w"))
    Try(tkgrid(tb,sticky="nw"))
  #  Try(tkgrid(toolbarFrame,sticky="ew"))
    Try(tkgrid(toolbarFrame,sticky="w"))
  #  Try(tkgrid.configure(tb,sticky="w"))
  })
  
  Try(LimmaFileName <- get("LimmaFileName",affylmGUIenvironment))
  Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
  Try(if (LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only 
  Try(tkwm.title(.affylmGUIglobals$ttMain,paste("affylmGUI -",LimmaFileName)))
  Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=.GlobalEnv))  
  Try(affylmGUIglobals$CDFfileBoxTitle <- tclVar("Please select a Chip Definition (CDF) file."))
  Try(affylmGUIglobals$CDFfileName <- tclVar("No filename is selected at the moment.  Press the Select CDF File Button."))
  Try(affylmGUIglobals$TargetsfileBoxTitle <- tclVar("Please select a tab-delimited file listing the CEL files."))
  Try(affylmGUIglobals$TargetsfileName <- tclVar("No filename is selected at the moment.  Press the Select Targets File Button."))
  Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))   
   
  Try(tkgrid(tklabel(mainFrame,text="         "),columnspan=3))
  Try(if (.affylmGUIglobals$affylmGUIpresentation==TRUE)
    Try(tkgrid(tklabel(mainFrame,text="affylmGUI",font=.affylmGUIglobals$affylmGUIfont1),column=1,columnspan=3,sticky="ew"))
  else
    Try(tkgrid(tklabel(mainFrame,text="     affylmGUI ",font=.affylmGUIglobals$affylmGUIfont1),column=2,sticky="ew")))
  Try(tkgrid(tklabel(mainFrame,text="Welcome to affylmGUI, a package for Linear Modelling of Microarray Data",font=.affylmGUIglobals$affylmGUIfont2),columnspan=5))
  Try(tkgrid(tklabel(mainFrame,text="         "),columnspan=5))
  Try(tkgrid(tklabel(mainFrame,text="         "),columnspan=5))
  Try(limmaDataSetName.but <- tkbutton(mainFrame,text="Data Set Name",command=GetlimmaDataSetName,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(limmaDataSetName.but,column=2,columnspan=1))
  Try(tkgrid(tklabel(mainFrame,text="         "),columnspan=5))
  Try(TclRequire("BWidget"))
  Try(mainTreeXScr <- tkscrollbar(mainFrame, repeatinterval=5,command=function(...)tkxview(.affylmGUIglobals$mainTree,...),orient="horizontal"))
  Try(mainTreeYScr <- tkscrollbar(mainFrame, repeatinterval=5,command=function(...)tkyview(.affylmGUIglobals$mainTree,...)))
  Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=.GlobalEnv))
  Try(affylmGUIglobals$mainTree <- tkwidget(mainFrame,"Tree",xscrollcommand=function(...)tkset(mainTreeXScr,...),yscrollcommand=function(...)tkset(mainTreeYScr,...),width=.affylmGUIglobals$mainTreeWidth,height=.affylmGUIglobals$mainTreeHeight,bg="white"))
  Try(LinModTreeXScr <- tkscrollbar(mainFrame, repeatinterval=5,command=function(...)tkxview(.affylmGUIglobals$ContrastParameterizationTREE,...),orient="horizontal"))
  Try(LinModTreeYScr <- tkscrollbar(mainFrame, repeatinterval=5,command=function(...)tkyview(.affylmGUIglobals$ContrastParameterizationTREE,...)))
  Try(affylmGUIglobals$ContrastParameterizationTREE <- tkwidget(mainFrame,"Tree",xscrollcommand=function(...)tkset(LinModTreeXScr,...),yscrollcommand=function(...)tkset(LinModTreeYScr,...),width=.affylmGUIglobals$ContrastParameterizationTREEWidth,height=.affylmGUIglobals$ContrastParameterizationTREEHeight,bg="white"))
  Try(affylmGUIglobals$limmaDataSetNameTextLabel <- tklabel(mainFrame,text=limmaDataSetNameText,font=.affylmGUIglobals$affylmGUIfont2b))
  Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))

  Try(tkgrid(tklabel(mainFrame,text="    "),.affylmGUIglobals$limmaDataSetNameTextLabel,tklabel(mainFrame,text="    "),tklabel(mainFrame,text="CONTRASTS PARAMETERIZATIONS",font=.affylmGUIglobals$affylmGUIfont2b),tklabel(mainFrame,text="                ")))
  Try(tkgrid(tklabel(mainFrame,text="    "),.affylmGUIglobals$mainTree,mainTreeYScr,.affylmGUIglobals$ContrastParameterizationTREE,LinModTreeYScr))
  Try(tkconfigure(.affylmGUIglobals$limmaDataSetNameTextLabel,textvariable=.affylmGUIglobals$limmaDataSetNameTcl))
  Try(tkgrid.configure(.affylmGUIglobals$mainTree,rowspan=6,sticky="ns"))
  Try(tkgrid.configure(mainTreeYScr,rowspan=6,sticky="wns"))
  Try(tkgrid.configure(.affylmGUIglobals$ContrastParameterizationTREE,rowspan=6,sticky="ns"))
  Try(tkgrid.configure(LinModTreeYScr,rowspan=6,sticky="wns"))
  Try(tkgrid(tklabel(mainFrame,text="    "),mainTreeXScr,tklabel(mainFrame,text="    "),LinModTreeXScr))
  Try(tkgrid.configure(mainTreeXScr,sticky="ewn"))
  Try(tkgrid.configure(LinModTreeXScr,sticky="ewn"))

  Try(tkgrid(tklabel(mainFrame,text="         "),columnspan=5))
  
  Try(tkgrid(mainFrame))

  Try(tkinsert(.affylmGUIglobals$mainTree,"end","root","RawAffyData" ,text="Raw Affy Data",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkinsert(.affylmGUIglobals$mainTree,"end","RawAffyData","RawAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkinsert(.affylmGUIglobals$mainTree,"end","root","NormalizedAffyData" ,text="Normalized Affy Data",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkinsert(.affylmGUIglobals$mainTree,"end","root","LinearModelFit" ,text="Linear Model Fit",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status" ,text="Not Available",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkinsert(.affylmGUIglobals$mainTree,"end","root","Parameters" ,text="Parameters",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters","Parameters.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree))  
  Try(tkinsert(.affylmGUIglobals$mainTree,"end","root","ContrastParameterizations" ,text="Contrasts Parameterizations",font=.affylmGUIglobals$affylmGUIfontTree))
  Try(tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree))

  Try(assign("ArraysLoaded",FALSE,affylmGUIenvironment))


  # Menu code below was taken from Rcmdr (and slightly modified)

  Try(etc <- system.file("etc",package="affylmGUI"))
  Try(cat(paste("\nSearching for user-defined affylmGUI commands in",etc,"...\n")))
  Try(source.files <- list.files(etc, pattern="*.R$"))
    Try(for (file in source.files) {
        Try(source(file.path(etc, file)))
        Try(cat(paste("Sourced:", file, "\n")))
        })

#  Try(topMenu <- tkmenu(.affylmGUIglobals$ttMain))
  Try(topMenu <- tkmenu(.affylmGUIglobals$ttMain))
#  Try(tkconfigure(.affylmGUIglobals$ttMain,menu=topMenu))
  Try(tkconfigure(.affylmGUIglobals$ttMain,menu=topMenu))
  Try(Menus <- read.table(file.path(system.file("etc",package="affylmGUI"),"affylmGUI-menus.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")
						tkadd(eval(parse(text=Menus[m, 2])),"cascade", label=Menus[m, 4], menu=eval(parse(text=Menus[m, 5])))
			  else if (Menus[m, 3] == "separator")
			      tkadd(eval(parse(text=Menus[m, 2])),"separator")
				else stop(paste("menu defintion error:", Menus[m, ], collapse=" "))
				}
		else stop(paste("menu defintion error:", Menus[m, ], collapse=" ")))
		})

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

  Try(if (.affylmGUIglobals$affylmGUIpresentation==FALSE)
  {
    Try(labelStatusBar <- tklabel(.affylmGUIglobals$ttMain,font=.affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(labelStatusBar,sticky="w"))
    Try(CurrentStatus <- tclVar("    "))
    Try(tkconfigure(labelStatusBar,textvariable=CurrentStatus))
    Try(tkbind(saveButton,"<Enter>",function() tclvalue(CurrentStatus) <- "Save the current Limma file."))
    Try(tkbind(saveButton,"<Leave>",function() tclvalue(CurrentStatus) <- "    "))
    Try(tkbind(openButton,"<Enter>",function() tclvalue(CurrentStatus) <- "Open an existing Limma file."))
    Try(tkbind(openButton,"<Leave>",function() tclvalue(CurrentStatus) <- "    "))
    Try(tkbind(newButton,"<Enter>",function() tclvalue(CurrentStatus) <- "Start a new Limma analysis."))
    Try(tkbind(newButton,"<Leave>",function() tclvalue(CurrentStatus) <- "    "))
  })
  
  #Try(tkwm.resizable(.affylmGUIglobals$ttMain,"true","false"))

  Try(tkbind(.affylmGUIglobals$ttMain, "<Control-N>", NewLimmaFile))
  Try(tkbind(.affylmGUIglobals$ttMain, "<Control-S>", SaveLimmaFile))
  Try(tkbind(.affylmGUIglobals$ttMain, "<Control-O>", OpenLimmaFile))
  Try(tkbind(.affylmGUIglobals$ttMain, "<Control-n>", NewLimmaFile))
  Try(tkbind(.affylmGUIglobals$ttMain, "<Control-s>", SaveLimmaFile))
  Try(tkbind(.affylmGUIglobals$ttMain, "<Control-o>", OpenLimmaFile))

  Try(tkfocus(.affylmGUIglobals$ttMain))

  Try(temp <- options(oldOptions))
  invisible()
}

getPackageVersion <- function(pkgName)
{
  DESCRIPTION <- readLines(paste(system.file(package=pkgName),"/DESCRIPTION",sep=""))
  lineNum <- grep("Version",DESCRIPTION)
  VersionLineWords <- strsplit(DESCRIPTION[lineNum]," ")[[1]]
  numWords <- length(VersionLineWords)
  VersionLineWords[numWords]
}

initGlobals <- function()
{
  assign("affylmGUIVersion",getPackageVersion("affylmGUI"),affylmGUIenvironment)
  assign("limmaVersion",getPackageVersion("limma"),affylmGUIenvironment)  
  assign("LimmaFileName","Untitled",affylmGUIenvironment)
  assign("RawAffyData" , 0,affylmGUIenvironment)
  assign("CDFFile" , "",affylmGUIenvironment)
  assign("ContrastParameterizationList" , list(),affylmGUIenvironment)
  assign("cdf" , data.frame(),affylmGUIenvironment)
  assign("NumSlides" , 0,affylmGUIenvironment)
  assign("NumContrastParameterizations", 0, affylmGUIenvironment)
  assign("ContrastParameterizationNamesVec", c(), affylmGUIenvironment)
  assign("ContrastParameterizationTREEIndexVec",c(), affylmGUIenvironment)
  assign("NumParameters" , 0,affylmGUIenvironment)
  assign("SlideNamesVec" , c(),affylmGUIenvironment)
  assign("Targets" , data.frame(),affylmGUIenvironment)
  assign("limmaDataSetNameText" , "Untitled",affylmGUIenvironment)
  Try(tclvalue(.affylmGUIglobals$limmaDataSetNameTcl) <- "Untitled")
  assign("ArraysLoaded",FALSE,affylmGUIenvironment)
  assign("RawAffyData.Available",FALSE,affylmGUIenvironment)
  assign("NormalizedAffyData.Available",FALSE,affylmGUIenvironment)
  assign("LinearModelFit.Available",FALSE,affylmGUIenvironment)
  assign("numConnectedSubGraphs",1,affylmGUIenvironment)
  assign("connectedSubGraphs",list(),affylmGUIenvironment)  
  assign("NumRNATypes",2,affylmGUIenvironment)
  assign("NormalizedAffyData",0,affylmGUIenvironment)
  assign("geneNames",c(),affylmGUIenvironment)
  assign("geneSymbols",c(),affylmGUIenvironment)  
  assign("NormMethod","RMA",affylmGUIenvironment)
  assign("weightsPLM",data.frame(),affylmGUIenvironment)
  assign(".JustAskedWhetherToSave",FALSE,.GlobalEnv)
}

deleteItemFromList <- function(list1,itemName=NULL,index=NULL)
{
    if (is.null(index))
      index <- match(itemName,attributes(list1)$names)
    if (is.na(index))
        return(list1)
    len <- length(list1)
    newlist <- list()
    count <- 0
    for (i in (1:len))
        if (i!=index)
        {
            count <- count + 1
            if (!is.null(attributes(list1)$names[i]))
            {
              newlist <- c(newlist,list(foo=list1[[i]]))
              attributes(newlist)$names[count] <- attributes(list1)$names[i]
            }
            else
              newlist[[count]] <- list1[[i]]
        }
    return (newlist)    
}


OpenCDFFile <- function()
{
  Try(cdf <- ChooseCDF())
  Try(if (cdf=="") return())
  Try(assign("CDFFile",cdf,affylmGUIenvironment))
  Try(CDFFile <- get("CDFFile",envir=affylmGUIenvironment))
  Try(tclvalue(.affylmGUIglobals$CDFfileBoxTitle) <- "Chip Definition (CDF) File")
  Try(tclvalue(.affylmGUIglobals$CDFfileName) <-paste(CDFFile))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  Require("reposTools")
  Try(cdfRepos <- getReposEntry("http://www.bioconductor.org/data/cdfenvs/repos"))
  Try(install.packages2(cdf,cdfRepos))
  Try(assign("cdf",cdf,affylmGUIenvironment)) # Can then use ls(env=cdf)
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))  
  Try(ArraysLoaded <- FALSE)
  Try(assign("ArraysLoaded",ArraysLoaded,affylmGUIenvironment))

  tkfocus(.affylmGUIglobals$ttMain)
}

OpenTargetsFile <- function()
{
  Try(TargetsFile <- tclvalue(tkgetOpenFile(filetypes="{{Targets Files} {.txt}} {{All files} *}")))
  Try(if (!nchar(TargetsFile)) return())
  Try(assign("TargetsFile",TargetsFile,affylmGUIenvironment))
  Try(tclvalue(.affylmGUIglobals$TargetsfileBoxTitle) <- paste("Targets File"))
  Try(tclvalue(.affylmGUIglobals$TargetsfileName) <- paste(TargetsFile))
  Try(Targets <- read.table(TargetsFile,header=TRUE,sep="\t",quote="\"",as.is=TRUE))
  Try(if (!("FileName" %in% colnames(Targets)))
  {
    Try(tkmessageBox(title="RNA Targets File Error",message="The RNA Targets file should have a \"FileName\" column.",icon="error"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    return()
  })
  Try(if (!("Target" %in% colnames(Targets)))
  {
    Try(tkmessageBox(title="RNA Targets File Error",message="The RNA Targets file should have a \"Target\" column.",icon="error"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    return()
  })   
  Try(if (!("Name" %in% colnames(Targets)))
  {
    Try(tkmessageBox(title="RNA Targets File Error",message="The RNA Targets file should have a \"Name\" column.",icon="error"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    return()
  })   
  
  Try(assign("Targets",Targets,affylmGUIenvironment))
  Try(assign("NumSlides",nrow(Targets),affylmGUIenvironment))

  Try(ArraysLoaded <- FALSE)
  Try(assign("ArraysLoaded",ArraysLoaded,affylmGUIenvironment))

  Try(tkfocus(.affylmGUIglobals$ttMain))
}

tclArrayVar <- function()
{
    Try(n <- evalq(TclVarCount <- TclVarCount + 1, .TkRoot$env))
    Try(name <- paste("::RTcl", n,sep = ""))
    Try(l <- list(env = new.env()))
    Try(assign(name, NULL, envir = l$env))
    Try(reg.finalizer(l$env, function(env) tkcmd("unset", ls(env))))
    Try(class(l) <- "tclArrayVar")
    Try(.Tcl(paste("set ",name,"(0,0) \"\"",sep="")))
    l
}


GetContrasts <- function(NumContrasts=0)  
{ 
  Try(NumSlides         <- get("NumSlides",        envir=affylmGUIenvironment))
  Try(Targets           <- get("Targets",          envir=affylmGUIenvironment))
  Try(ArraysLoaded      <- get("ArraysLoaded",     envir=affylmGUIenvironment)) 
  Try(LinearModelFit.Available <- get("LinearModelFit.Available", envir=affylmGUIenvironment))
  
  Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
  
  if (ArraysLoaded==FALSE)
  {
      Try(tkmessageBox(title="Contrasts Matrix",message="No arrays have been loaded.  Please try New or Open from the File menu.",type="ok",icon="error"))
      Try(tkfocus(.affylmGUIglobals$ttMain))      
      return()
  }

  if (LinearModelFit.Available==FALSE)
  {
    Try(ComputeLinearModelFit())
#    Try(tkmessageBox(title="Compute Contrasts",message="There is no linear model fit available.  Select \"Compute Linear Model Fit\" from the \"Linear Model\" menu.",type="ok",icon="error"))
#    Try(tkfocus(.affylmGUIglobals$ttMain))
#    return()  
  }  

  Try(design            <- get("design",           envir=affylmGUIenvironment))
  Try(NumParameters     <- ncol(design))
  Try(ParameterNamesVec <- colnames(design))  
  
  GetContrastsTable <- function(contrastsFromDropDowns)
  {
    Try(TclRequire("Tktable"))
    Try(ttContrastsTable <- tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.deiconify(ttContrastsTable))
    Try(tkgrab.set(ttContrastsTable))
    Try(tkfocus(ttContrastsTable))
    Try(tkwm.title(ttContrastsTable,"Contrasts Matrix"))
    Try(ReturnVal <- list(contrasts=data.frame(),contrastsCreatedFromDropDowns=FALSE))
    Try(contrastsMatrix <- contrastsFromDropDowns$contrasts)    
    Try(tclArrayVar1 <- tclArrayVar())
    Try(tclArrayName <- ls(tclArrayVar1$env))

    onOK <- function()
    {
        Try(tkcmd("event","generate",.Tk.ID(table1),"<Leave>"))
        NumRows <- NumParameters
        NumCols <- NumContrasts
        Try(contrastsMatrix <- as.data.frame(matrix(nrow=NumRows,ncol=NumCols)))
        Try(rownamescontrastsMatrix <- c())
        for (i in (1:NumRows))
            Try(rownamescontrastsMatrix[i] <- tclvalue(paste(tclArrayName,"(",i,",0)",sep="")))
        Try(colnamescontrastsMatrix <- c())
        if (NumCols>0)
          for (j in (1:NumCols))
            Try(colnamescontrastsMatrix[j] <- tclvalue(paste(tclArrayName,"(0,",j,")",sep="")))
        Try(rownames(contrastsMatrix) <- rownamescontrastsMatrix)
        Try(colnames(contrastsMatrix) <- colnamescontrastsMatrix)
        if (NumCols>0)
          for (i in (1:NumRows))
            for (j in (1:NumCols))
                Try(contrastsMatrix[i,j] <- as.numeric(tclvalue(paste(tclArrayName,"(",i,",",j,")",sep=""))))
        Try(tkgrab.release(ttContrastsTable))
        Try(tkdestroy(ttContrastsTable))
        Try(tkfocus(.affylmGUIglobals$ttMain))
        Try(ReturnVal <<- list(contrasts=contrastsMatrix,contrastsCreatedFromDropDowns=FALSE))        
    }
    onCancel <- function() 
    {
      Try(tkgrab.release(ttContrastsTable))
      Try(tkdestroy(ttContrastsTable))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      ReturnVal <<- list(contrasts=data.frame(),contrastsCreatedFromDropDowns=FALSE)
    }       
    Try(OK.but <-tkbutton(ttContrastsTable,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
    Try(Cancel.but <-tkbutton(ttContrastsTable,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
    Try(tkgrid(tklabel(ttContrastsTable,text="    ")))
    Try(PleaseEntercontrastsMatrixLabel<-tklabel(ttContrastsTable,text="Please enter the contrasts matrix to be used for linear-modelling.",font=.affylmGUIglobals$affylmGUIfont2))      
    Try(tkgrid(tklabel(ttContrastsTable,text="    "),PleaseEntercontrastsMatrixLabel))
    Try(tkgrid.configure(PleaseEntercontrastsMatrixLabel,columnspan=2))
    Try(tkgrid(tklabel(ttContrastsTable,text="    ")))
    NumRows <- NumParameters
    NumCols <- NumContrasts
    
    Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec)
    Try(if (nrow(contrastsMatrix)==0)
    {
      Try(ContrastsNamesVec <- c())
      if (NumContrasts>0)
        for (i in (1:NumContrasts)) 
          Try(ContrastsNamesVec <- c(ContrastsNamesVec,paste("Contrast ",i,sep="")))              
    }
    else
        Try(ContrastsNamesVec <- colnames(contrastsMatrix)))      
    Try(ColNamesVec <- ContrastsNamesVec)
        
    Try(rownamescontrastsMatrix <- c())
    Try(myRarray <- "    ")
    for (i in (1:NumRows))
    {
        Try(RowName <- ParameterNamesVec[i])
        Try(rownamescontrastsMatrix <- c(rownamescontrastsMatrix,RowName))
        Try(myRarray <- c(myRarray,paste(RowName)))
    }
    if (NumCols>0)
      for (j in (1:NumCols))      
      {
        Try(myRarray <- c(myRarray,paste(ColNamesVec[j])))
        for (i in (1:NumRows))
        {          
            if (nrow(contrastsMatrix)==0)
                Try(myRarray <- c(myRarray,"0"))
            else
                Try(myRarray <- c(myRarray,paste(contrastsMatrix[i,j])))
        }      
      } 
      # This will give an error if tclArray doesn't exist.
      # .Tcl("unset tclArray")
      Try(dim(myRarray) <- c(NumRows+1,NumCols+1))
      if (NumCols>0)
        for (i in (0:NumRows))
          for (j in (0:NumCols))
          {
             # Modified to use tkcmd!
             Try(tkcmd("set",paste(tclArrayName,"(",i,",",j,")",sep=""),paste(myRarray[i+1,j+1])))             
          }

      # Below, can I just use tkwidget(ttContrastsTable,"table",...) ?  Yes, of course.
      Try(table1 <- .Tk.subwin(ttContrastsTable))
      Try(.Tcl(paste("table",.Tk.ID(table1),.Tcl.args(variable=tclArrayName,rows=paste(NumRows+1),cols=paste(NumCols+1),titlerows="0",titlecols="0",selectmode="extended",colwidth="13",background="white",rowseparator="\"\n\"",colseparator="\"\t\"",resizeborders="col",multiline="0"))))
      Try(tkgrid(tklabel(ttContrastsTable,text="    "),table1))

      Try(tkcmd(.Tk.ID(table1),"width","0",paste(max(4,max(nchar(rownamescontrastsMatrix))+2))))
      Try(if (nrow(contrastsMatrix)>0)
      {     

        Try(for (j in (1:NumCols))      
          Try(tkcmd(.Tk.ID(table1),"width",paste(j),paste(max(4,max(nchar(ColNamesVec))+2,max(nchar(contrastsMatrix[,j]))+2)))))
      })

#         Try(tkcmd(.Tk.ID(table1),"width","0","25"))

      Try(tkconfigure(table1,font=.affylmGUIglobals$affylmGUIfontTable))
      Try(tkgrid.configure(table1,columnspan=2))

      Try(copyFcn <-      function() .Tcl(paste("event","generate",.Tcl.args(.Tk.ID(table1),"<<Copy>>"))))

      openContrastsMatrixFile <- function()
      {
        Try(contrastsMatrixFileName <- tclvalue(tkgetOpenFile(filetypes="{{Contrasts Matrix Files} {.txt}} {{All files} *}")))
        Try(if (!nchar(contrastsMatrixFileName)) return())
        Try(contrastsMatrixTable <- read.table(contrastsMatrixFileName,header=FALSE,sep="\t",quote="\"",as.is=TRUE))
        # This will give an error if tclArray doesn't exist.
        # .Tcl("unset tclArray")
        if (NumCols>0)
          for (i in (0:NumRows))
            for (j in (0:NumCols))
              Try(tkcmd("set",paste(tclArrayName,"(",i,",",j,")",sep=""),paste(contrastsMatrixTable[i+1,j+1])))
      }

      saveContrastsMatrixFile <- function()
      {
        Try(contrastsMatrixFileName <- tclvalue(tkgetSaveFile(filetypes="{{Contrasts Matrix Files} {.txt}} {{All files} *}")))
        Try(if (!nchar(contrastsMatrixFileName)) return())
        Try(len <- nchar(contrastsMatrixFileName))
        if (len<=4)
          Try(  contrastsMatrixFileName <- paste(contrastsMatrixFileName,".txt",sep=""))
        else if (substring(contrastsMatrixFileName,len-3,len)!=".txt")
              Try(contrastsMatrixFileName <- paste(contrastsMatrixFileName,".txt",sep=""))
        Try(contrastsMatrix <- as.data.frame(matrix(nrow=NumSlides,ncol=NumParameters)))
        Try(rownamescontrastsMatrix <- c())
        Try(for (i in (1:NumRows))
            rownamescontrastsMatrix[i] <- tclvalue(paste(tclArrayName,"(",i,",0)",sep="")))
        Try(colnamescontrastsMatrix <- c())
        if (NumParameters>0)
          Try(for (j in (1:NumCols))
            colnamescontrastsMatrix[j] <- tclvalue(paste(tclArrayName,"(0,",j,")",sep="")))
        Try(rownames(contrastsMatrix) <- rownamescontrastsMatrix)
        Try(colnames(contrastsMatrix) <- colnamescontrastsMatrix)
        if (NumParameters>0)
          Try(for (i in (1:NumRows))
            for (j in (1:NumParameters))
                contrastsMatrix[i,j] <- as.numeric(tclvalue(paste(tclArrayName,"(",i,",",j,")",sep=""))))

        Try(write.table(contrastsMatrix,file=contrastsMatrixFileName,col.names=NA,sep="\t",quote=FALSE,row.names=TRUE))
      }

      Try(topMenu <- tkmenu(ttContrastsTable, tearoff=FALSE))
      Try(fileMenu <- tkmenu(topMenu, tearoff=FALSE))
      Try(tkadd(fileMenu, "command", label="Open",      command=openContrastsMatrixFile)) # ) # ,font=affylmGUIfontMenu))
      Try(tkadd(fileMenu, "command", label="Save As",      command=saveContrastsMatrixFile)) # ) # ,font=affylmGUIfontMenu))
      Try(tkadd(topMenu,  "cascade", label="File",menu=fileMenu)) # ) # ,font=affylmGUIfontMenu))  

      Try(editMenu <- tkmenu(topMenu, tearoff=FALSE))
      Try(tkadd(editMenu, "command", label="Copy <Ctrl-C>",      command=copyFcn)) # ) # ,font=affylmGUIfontMenu))
      Try(tkadd(topMenu,  "cascade", label="Edit",menu=editMenu)) # ) # ,font=affylmGUIfontMenu))  

      Try(tkconfigure(ttContrastsTable,menu=topMenu))

      Try(BlankLabel1<-tklabel(ttContrastsTable,text="    "))
      Try(tkgrid(BlankLabel1))
      Try(BlankLabel2<-tklabel(ttContrastsTable,text="    "))
      Try(tkgrid(BlankLabel2,OK.but,Cancel.but))
      Try(tkgrid.configure(OK.but,sticky="e"))
      Try(tkgrid.configure(Cancel.but,sticky="w"))
      Try(BlankLabel3<-tklabel(ttContrastsTable,text="    "))
      Try(tkgrid(BlankLabel3))

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

  if (NumParameters<=0)
  {
    Try(tkmessageBox(title="At Least Two RNA Types Are Required",message="You must have at least two types of RNA in your Targets file.",type="ok",icon="error"))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    return(list(contrasts=data.frame(),contrastsCreatedFromDropDowns=FALSE))    
  }
  
  Try(NumRows <- NumParameters)
  Try(NumCols <- NumContrasts)

  Try(ttContrasts<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttContrasts))
  Try(tkgrab.set(ttContrasts))
  Try(tkfocus(ttContrasts))
  Try(tkwm.title(ttContrasts,"Contrasts"))

  Try(lbl2<-tklabel(ttContrasts,text="Please specify pairs of parameters for which contrasts will be estimated",font=.affylmGUIglobals$affylmGUIfont2))
  Try(lbl3<-tklabel(ttContrasts,text="                                                                    "))
  Try(tkgrid(tklabel(ttContrasts,text="       "),row=0,column=1,columnspan=1))
  Try(tkgrid(tklabel(ttContrasts,text="       "),row=0,column=4,columnspan=1))
  Try(tkgrid(lbl2,row=1,column=2,columnspan=4,rowspan=1,sticky="ew"))
  Try(tkgrid.configure(lbl2,sticky="w"))
  Try(tkgrid(tklabel(ttContrasts,text="         "),column=1))
  Try(tkgrid(tklabel(ttContrasts,text="         ")))
  Try(tkgrid(tklabel(ttContrasts,text="         "),column=1))
#  plus<-tklabel(ttContrasts,text="   +   ",font=.affylmGUIglobals$affylmGUIfont2)
#  minus<-tklabel(ttContrasts,text="   -   ",font=.affylmGUIglobals$affylmGUIfont2)
#  tkgrid(plus,row=3, column=2,sticky="ew")
#  tkgrid(minus,row=3,column=6,sticky="ew")

  Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec)

  Try(TclList1AsString <- "{")
  Try(for (i in (1:NumParameters))
    TclList1AsString <- paste(TclList1AsString,"{",ParameterNamesVec[i],"} ",sep=""))
  TclList1AsString <- paste(TclList1AsString,"}",sep="")
  TclList2AsString <- TclList1AsString
  
#  Try(plusOrMinusTclListAsString <- "{{minus} {plus}}")
  Try(plusOrMinusTclListAsString <- "{{minus}}")
  
  Try(TclRequire("BWidget"))      

  Try(combo1 <- c())
  Try(combo2 <- c())
  Try(combo3 <- c())
  Try(if (NumCols>0)
    for (contrastIndex in (1:NumCols))
    {
      Try(FirstDropDownColumn <- .Tk.subwin(ttContrasts))
      combo1 <- c(combo1,FirstDropDownColumn)
      Try(.Tcl(paste("ComboBox",.Tk.ID(FirstDropDownColumn),"-editable false -values",TclList1AsString)))
      Try(SecondDropDownColumn <- .Tk.subwin(ttContrasts))
      Try(combo2 <- c(combo2,SecondDropDownColumn))
      Try(.Tcl(paste("ComboBox",.Tk.ID(SecondDropDownColumn),"-editable false -values",TclList2AsString)))
      Try(plusOrMinusDropDown <- .Tk.subwin(ttContrasts))
      Try(combo3 <- c(combo3,plusOrMinusDropDown))
      Try(.Tcl(paste("ComboBox",.Tk.ID(plusOrMinusDropDown),"-editable false -values",plusOrMinusTclListAsString)))
      Try(tkcmd(.Tk.ID(plusOrMinusDropDown),"setvalue","first"))
      Try(if (.affylmGUIglobals$affylmGUIpresentation==TRUE)            
      {
        Try(tkconfigure(FirstDropDownColumn,width=10))
        Try(tkconfigure(SecondDropDownColumn,width=10))      
        Try(tkconfigure(plusOrMinusDropDown,width=10))              
      })
      Try(dropdownLabel <- paste("Contrast",contrastIndex, "  ")  )
      
      Try(tkgrid(tklabel(ttContrasts,text=dropdownLabel,font=.affylmGUIglobals$affylmGUIfont2),row=2+contrastIndex,
                        column=0,sticky="w"))
      Try(tkconfigure(FirstDropDownColumn,font=.affylmGUIglobals$affylmGUIfont2))
      Try(tkconfigure(SecondDropDownColumn,font=.affylmGUIglobals$affylmGUIfont2))
      Try(tkconfigure(plusOrMinusDropDown,font=.affylmGUIglobals$affylmGUIfont2))      
      Try(tkgrid(FirstDropDownColumn,row=2+contrastIndex,column=2,columnspan=1,rowspan=1))
      Try(tkgrid(plusOrMinusDropDown,row=2+contrastIndex,column=4,columnspan=1,rowspan=1))      
      Try(tkgrid(SecondDropDownColumn,row=2+contrastIndex,column=6,columnspan=1,rowspan=1))

      Try(tkgrid(tklabel(ttContrasts,text="    "),row=2+contrastIndex,column=7))
    })
  Try(tkgrid(tklabel(ttContrasts,text="                                                 "),rowspan=1,columnspan=4))

  Try(ReturnVal <- list(contrasts=data.frame(),contrastsCreatedFromDropDowns=TRUE,Param1=c(),Param2=c()))
  
  OnAdvanced <- function()
  {
      Try(contrastsFromDropDowns <- GetContrastsFromDropDowns())
      Try(ReturnValcontrastsMatrixTable <- GetContrastsTable(contrastsFromDropDowns)) # Returns contrastsMatrix list object including contrastsMatrix matrix as data.frame
      NumRows <- nrow(ReturnValcontrastsMatrixTable$contrasts)
      if (NumRows>0 ) # OK was clicked, not Cancel
      {
          Try(tkgrab.release(ttContrasts))
          Try(tkdestroy(ttContrasts))
          Try(tkfocus(.affylmGUIglobals$ttMain))
          ReturnVal <<- ReturnValcontrastsMatrixTable   # List contains contrastsMatrix matrix as data.frame
      }   
  }

  GetContrastsFromDropDowns <- function()
  {
   
    NumRows <- NumParameters
    NumCols <- NumContrasts
   
    Param1 <-c()
    Param2 <-c()    
    
    NoParameter <- 99999
      
      
    if (NumCols>0)
      for (contrastIndex in (1:NumCols))
      {
        # I think I wrote this code when I was an R Tcl/Tk beginner.  Check and update!
        # I think combo1 and combo2 should really be lists, not vectors!!!
        # *2 below, because the c() combines the tkwin objects which are acutally         
        # lists with 2 components: window ID and environment.

        selection1 <- tclvalue(.Tcl(paste(.Tk.ID(combo1[contrastIndex*2-1]),"getvalue")))
        selection2 <- tclvalue(.Tcl(paste(.Tk.ID(combo2[contrastIndex*2-1]),"getvalue")))        
        selection3 <- tclvalue(.Tcl(paste(.Tk.ID(combo3[contrastIndex*2-1]),"getvalue")))                
        Try(if ((selection1!="-1"))
          Try(Param1 <- c(Param1,as.numeric(selection1)+1))
        else
          Try(Param1 <- c(Param1,NoParameter)))
        Try(if ((selection2!="-1"))          
          Try(Param2 <- c(Param2,as.numeric(selection2)+1))
        else
          Try(Param2 <- c(Param2,NoParameter)))
      }

    contrastsMatrix <- as.data.frame(matrix(nrow=NumRows,ncol=NumCols))
    Try(rownames(contrastsMatrix) <- ParameterNamesVec)

    Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec)
    ContrastNamesVec <- vector(length=NumContrasts)    
    if (NumContrasts>0)
      for (j in (1:NumContrasts))          
        ContrastNamesVec[j] <- SimplifyContrastsExpression(paste("(",ParameterNamesVec[Param1[j]],")-(",ParameterNamesVec[Param2[j]],")",sep=""))
    colnames(contrastsMatrix) <- ContrastNamesVec    

    Try(for (i in (1:NumParameters))
      for (j in (1:NumContrasts))
      {
        Try(contrastsMatrix[i,j] <- 0)
        Try(if (Param1[j]==i)  
          contrastsMatrix[i,j] <- 1)
        Try(if(Param2[j]==i)
            contrastsMatrix[i,j] <- -1)         
      })        
      
  
    Try(if (max(abs(contrastsMatrix))==0)
      Try(return(list(contrasts=data.frame(),contrastsCreatedFromDropDowns=TRUE,Param1=c(),Param2=c()))))      
      
#    # Go through from the right hand column to the left and check for all zeros (i.e. check if max(abs(...)) == 0). If so try to reduce the
#    # number of columns (contrasts).
#    Try(while(max(abs(contrastsMatrix[,NumContrasts]))==0 && NumContrasts > 1)
#      NumContrasts <<- NumContrasts - 1)
#    Try(contrastsMatrix <- contrastsMatrix[,1:NumContrasts,drop=FALSE])
#    Try(Param1 <- Param1[1:NumContrasts])    
#    Try(Param2 <- Param2[1:NumContrasts])   
    
    return(list(contrasts=contrastsMatrix,contrastsCreatedFromDropDowns=TRUE,Param1=Param1,Param2=Param2))
  }

  onOK <- function()
  {
    Try(contrastsMatrixList <- GetContrastsFromDropDowns())
    Try(if (nrow(contrastsMatrixList$contrasts)==0)    
    {
      Try(tkmessageBox(title="Contrasts",message=paste("Error in creating contrasts matrix from drop-down selection. ",
                       "Make sure you have selected a parameter pair for each contrast."),type="ok",icon="error"))                    
      Try(ReturnVal <<- list(contrasts=data.frame(),contrastsCreatedFromDropDowns=TRUE,Param1=c(),Param2=c()))
      return()
    } 
    else
    {
      Try(tkgrab.release(ttContrasts))
      Try(tkdestroy(ttContrasts))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(ReturnVal <<- contrastsMatrixList)
      Try(tkfocus(.affylmGUIglobals$ttMain))
      return()
    })
  }
  onCancel <- function() 
  {
    Try(tkgrab.release(ttContrasts))
    Try(tkdestroy(ttContrasts))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    ReturnVal <<- list(contrasts=data.frame(),contrastsCreatedFromDropDowns=TRUE,Param1=c(),Param2=c())    
  }   
  Advanced.but <- tkbutton(ttContrasts,text="Advanced...",command=OnAdvanced,font=.affylmGUIglobals$affylmGUIfont2)
  Try(OK.but <-tkbutton(ttContrasts,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <-tkbutton(ttContrasts,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(OK.but,column=2,row=9+NumParameters))
  Try(tkgrid(Cancel.but,column=4,row=9+NumParameters))
  Try(tkgrid(Advanced.but,column=6,row=9+NumParameters))
  Try(tkgrid(tklabel(ttContrasts,text="    ")))
      
  Try(tkfocus(ttContrasts))
  
  Try(tkbind(ttContrasts, "<Destroy>", function() {Try(tkgrab.release(ttContrasts));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkwait.window(ttContrasts))
  return (ReturnVal)
}


# Actually in the two functions below, RNA should really be Param, but it doesn't really make a difference.
# This came from the cDNA version.

SimplifyContrastsExpression <- function(string)
{
  RNATypesAndSign <- GetRNATypesFrom.ContrastsFromDropDowns.String(string)
  RNA1 <- RNATypesAndSign$RNA1
  RNA2 <- RNATypesAndSign$RNA2
  RNA3 <- RNATypesAndSign$RNA3
  RNA4 <- RNATypesAndSign$RNA4
  plusOrMinusSign <- RNATypesAndSign$plusOrMinusSign
  ReturnVal <- string
  
  if (RNA1==RNA3&&plusOrMinusSign=='-')
    ReturnVal <- paste("(",RNA4,")-(",RNA2,")",sep="")  
  if (RNA2==RNA4&&plusOrMinusSign=='-')  
    ReturnVal <- paste("(",RNA1,")-(",RNA3,")",sep="")  
  if (RNA1==RNA4&&plusOrMinusSign=='+')
    ReturnVal <- paste("(",RNA3,")-(",RNA2,")",sep="")    
  if (RNA2==RNA3&&plusOrMinusSign=='+')  
    ReturnVal <- paste("(",RNA1,")-(",RNA4,")",sep="")      
  return(ReturnVal)
  
}

GetRNATypesFrom.ContrastsFromDropDowns.String <- function(string)
{
  len <- nchar(string)
  string <- substr(string,3,len)
  # string == "a)-(b))-((b)-(c"
  len <- nchar(string)
  i <- 1
  while (substr(string,i,i)!=")" && (i<=len))
    i <- i + 1
  RNA1 <- substr(string,1,i-1)
  len <- nchar(string)
  string <- substr(string,i+3,len)
  len <- nchar(string)  
  i<-1
  while (substr(string,i,i)!=")" && (i<=len))
    i <- i + 1
  RNA2 <- substr(string,1,i-1)
  len <- nchar(string)
  plusOrMinusSign <- substr(string,i+2,i+2)
  string <- substr(string,i+5,len)
  len <- nchar(string)  
  i<-1
  while (substr(string,i,i)!=")" && (i<=len))
    i <- i + 1
  RNA3 <- substr(string,1,i-1)
  len <- nchar(string)
  string <- substr(string,i+3,len)
  len <- nchar(string)  
  i<-1
  while (substr(string,i,i)!=")" && (i<=len))
    i <- i + 1
  RNA4 <- substr(string,1,i-1)
  list(RNA1=RNA1,RNA2=RNA2,RNA3=RNA3,RNA4=RNA4,plusOrMinusSign=plusOrMinusSign)
}

ViewContrastsMatrixInTable <- function(contrastsMatrixList,contrastParameterizationIndex=NULL)
{
  Try(design <- get("design",envir=affylmGUIenvironment))  
  Try(ParameterNamesVec <- colnames(design))
  Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))  
  Try(ContrastParameterizationNamesVec <- get("ContrastParameterizationNamesVec",envir=affylmGUIenvironment))
  Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
  Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])

  Try(TclRequire("Tktable"))
  Try(ttViewContrastsMatrixTable <- tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttViewContrastsMatrixTable))
  Try(tkgrab.set(ttViewContrastsMatrixTable))
  Try(tkfocus(ttViewContrastsMatrixTable))
  Try(tkwm.title(ttViewContrastsMatrixTable,paste("Contrasts matrix for contrasts parameterization ", ContrastParameterizationNamesVec[contrastParameterizationIndex])))
  Try(contrastsMatrix <- contrastsMatrixList$contrasts)
  Try(NumContrasts <- ncol(contrastsMatrix))
    
  onClose <- function() {Try(.Tcl(paste("event","generate",.Tcl.args(.Tk.ID(table1),"<Leave>"))));Try(tkgrab.release(ttViewContrastsMatrixTable));Try(tkdestroy(ttViewContrastsMatrixTable));Try(tkfocus(.affylmGUIglobals$ttMain))}

  Try(NumRows <- NumParameters)
  Try(NumCols <- NumContrasts)
    
  Try(if (is.null(colnames(contrastsMatrix)))
  {
      Try(ColumnNamesVec <- c())
      if (NumCols>0)
        for (i in (1:NumCols)) 
            Try(ColumnNamesVec <- c(ColumnNamesVec,paste("Contrast",i)))
  }
  else
      Try(ColumnNamesVec <- colnames(contrastsMatrix)))

  Try(RowNamesVec <- c())
  Try(myRarray <- "    ")
  Try(for (i in (1:NumRows))
  {
      Try(if (contrastsMatrix=="Design")      
      {
        Try(if(is.null(rownames(contrastsMatrix)))
          Try(RowName <- SlideNamesVec[i])
        else
          Try(RowName <- rownames(contrastsMatrix)[i]))        
      }
      else # Contrasts
      {
        Try(if (is.null(rownames(contrastsMatrix)))
          Try(RowName <- paste("Param",i))
        else
          Try(RowName <- rownames(contrastsMatrix)[i]))
      })
      Try(RowNamesVec <- c(RowNamesVec,RowName))
      Try(myRarray <- c(myRarray,paste(RowName)))
  })
  
  if (NumCols>0)
    for (j in (1:NumCols))      
    {
      Try(myRarray <- c(myRarray,paste(ColumnNamesVec[j])))
      for (i in (1:NumRows))
      {          
          if (nrow(contrastsMatrix)==0)
              Try(myRarray <- c(myRarray,"0"))
          else
              Try(myRarray <- c(myRarray,paste(contrastsMatrix[i,j])))
      }      
    }      

#      Try(n <- evalq(TclVarCount <- TclVarCount + 1, .TkRoot$env))
#      Try(tclArrayName <- paste("::RTcl", n, sep = ""))  
#      Try(l <- list(env = new.env()))
#      Try(assign(tclArrayName, NULL, envir = l$env))
#      Try(reg.finalizer(l$env, function(env) tkcmd("unset", ls(env)))
      Try(tclArrayVar1 <- tclArrayVar())
      Try(tclArrayName <- ls(tclArrayVar1$env))

      Try(dim(myRarray) <- c(NumRows+1,NumCols+1))

      # This will give an error if tclArray doesn't exist.
      # .Tcl("unset tclArray")
      if (NumCols>0)
        for (i in (0:NumRows))
          for (j in (0:NumCols))
             Try(tkcmd("set",paste(tclArrayName,"(",i,",",j,")",sep=""),paste(myRarray[i+1,j+1])))

      Try(table1 <- tkwidget(ttViewContrastsMatrixTable,"table"))
      Try(tkconfigure(table1,variable=tclArrayName,rows=paste(NumRows+1),cols=paste(NumCols+1),
        titlerows="0",titlecols="0",selectmode="extended",colwidth="13",background="white",rowseparator="\"\n\"",
        colseparator="\"\t\"",resizeborders="col",multiline="0",
        xscrollcommand=function(...) tkset(xscr,...),yscrollcommand=function(...) tkset(yscr,...),state="disabled"))
      Try(xscr <- tkscrollbar(ttViewContrastsMatrixTable,orient="horizontal", command=function(...)tkxview(table1,...)))
      Try(yscr <- tkscrollbar(ttViewContrastsMatrixTable,command=function(...)tkyview(table1,...)))               
      Try(tkgrid(table1,yscr))
      Try(tkgrid.configure(yscr,sticky="nsw"))
      Try(tkconfigure(table1,font=.affylmGUIglobals$affylmGUIfontTable))
      Try(tkgrid(xscr,sticky="new"))
      Try(copyFcn <-      function() .Tcl(paste("event","generate",.Tcl.args(.Tk.ID(table1),"<<Copy>>"))))


      Try(tkcmd(.Tk.ID(table1),"width","0",paste(max(4,max(nchar(rownames(contrastsMatrix)))+2))))
      Try(for (j in (1:NumCols))      
        Try(tkcmd(.Tk.ID(table1),"width",paste(j),paste(max(4,nchar(colnames(contrastsMatrix)[j])+2,max(nchar(contrastsMatrix[,j]))+2)))))


      onSaveContrastsMatrixAs <- function()
      {
        Try(if (contrastsMatrix=="Design")        
          Try(contrastsMatrixFileName <- tclvalue(tkgetSaveFile(filetypes="{{Design Matrix Files} {.txt}} {{All files} *}")))
        else
          Try(contrastsMatrixFileName <- tclvalue(tkgetSaveFile(filetypes="{{Contrasts Matrix Files} {.txt}} {{All files} *}"))))         
        Try(if (!nchar(contrastsMatrixFileName)) return())
        Try(len <- nchar(contrastsMatrixFileName))
        if (len<=4)
          Try(contrastsMatrixFileName <- paste(contrastsMatrixFileName,".txt",sep=""))
        else if (substring(contrastsMatrixFileName,len-3,len)!=".txt")
              Try(contrastsMatrixFileName <- paste(contrastsMatrixFileName,".txt",sep=""))
        Try(contrastsMatrix <- as.data.frame(matrix(nrow=NumRows,ncol=NumCols)))
        Try(rownamescontrastsMatrix <- c())
        Try(for (i in (1:NumRows))
            rownamescontrastsMatrix[i] <- tclvalue(paste(tclArrayName,"(",i,",0)",sep="")))
        Try(colnamescontrastsMatrix <- c())
        if (NumParameters>0)
          Try(for (j in (1:NumCols))
            colnamescontrastsMatrix[j] <- tclvalue(paste(tclArrayName,"(0,",j,")",sep="")))
        Try(rownames(contrastsMatrix) <- rownamescontrastsMatrix)
        Try(colnames(contrastsMatrix) <- colnamescontrastsMatrix)
        if (NumParameters>0)
          Try(for (i in (1:NumRows))
            for (j in (1:NumParameters))
                contrastsMatrix[i,j] <- as.numeric(tclvalue(paste(tclArrayName,"(",i,",",j,")",sep=""))))

        Try(write.table(contrastsMatrix,file=contrastsMatrixFileName,col.names=NA,sep="\t",quote=FALSE,row.names=TRUE))
      }



      Try(topMenu <- tkmenu(ttViewContrastsMatrixTable, tearoff=FALSE))

      Try(fileMenu <- tkmenu(topMenu, tearoff=FALSE))
      Try(tkadd(fileMenu, "command", label="Save As",    command=onSaveContrastsMatrixAs))       
      Try(tkadd(fileMenu, "command", label="Close",      command=onClose)) 
      Try(tkadd(topMenu,  "cascade", label="File",menu=fileMenu)) 
      Try(editMenu <- tkmenu(topMenu, tearoff=FALSE))
      Try(tkadd(editMenu, "command", label="Copy <Ctrl-C>",      command=copyFcn)) 
      Try(tkadd(topMenu,  "cascade", label="Edit",menu=editMenu)) 

      Try(tkconfigure(ttViewContrastsMatrixTable,menu=topMenu))

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

ViewContrastsMatrixAsPairs <- function(contrastsMatrix,contrastsMatrixList,contrastParameterizationIndex=NULL)
{
  Try(SlideNamesVec <- get("SlideNamesVec",envir=affylmGUIenvironment))  
  Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))  
  Try(ContrastParameterizationNamesVec <- get("ContrastParameterizationNamesVec",envir=affylmGUIenvironment))
  Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
  Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec)
  Try(NumSlides <- get("NumSlides",envir=affylmGUIenvironment))    

  Try(contrastsMatrix <- contrastsMatrixList$contrasts)  
  Try(NumContrasts <- ncol(contrastsMatrix))
  NumRows <- NumParameters
  NumCols <- NumContrasts
    
  ttViewContrastsMatrixAsPairs<-tktoplevel(.affylmGUIglobals$ttMain)
  tkwm.deiconify(ttViewContrastsMatrixAsPairs)
  tkgrab.set(ttViewContrastsMatrixAsPairs)
  tkfocus(ttViewContrastsMatrixAsPairs)
  Try(tkwm.title(ttViewContrastsMatrixAsPairs,paste("Contrasts in contrasts parameterization ", ContrastParameterizationNamesVec[contrastParameterizationIndex],".",sep="")))  
  Try(TitleLabel<-tklabel(ttViewContrastsMatrixAsPairs,text=paste("Contrasts in contrasts parameterization ", ContrastParameterizationNamesVec[contrastParameterizationIndex],sep=""),font=.affylmGUIglobals$affylmGUIfont2b))     

  Try(tkgrid(tklabel(ttViewContrastsMatrixAsPairs,text="    ")))    
  Try(tkgrid(tklabel(ttViewContrastsMatrixAsPairs,text="    "),TitleLabel))
  Try(tkgrid.configure(TitleLabel,columnspan=4))
  Try(tkgrid(tklabel(ttViewContrastsMatrixAsPairs,text="    ")))  
  Try(ParameterOrContrastLabel <- tklabel(ttViewContrastsMatrixAsPairs,text="Contrast",font=.affylmGUIglobals$affylmGUIfont2b))
  # Note that plusOrMinus IS A VECTOR (can be different for each contrast).
  Try(plusOrMinus <- contrastsMatrixList$plusOrMinus)
  Try(tkgrid(tklabel(ttViewContrastsMatrixAsPairs,text="    "),
             ParameterOrContrastLabel))

  if (is.null(colnames(contrastsMatrix)))
  {
      Try(ColumnNamesVec <- c())
      if (NumCols>0)
        for (i in (1:NumCols)) 
          Try(ColumnNamesVec <- c(ColumnNamesVec,paste("Contrast",i)))
  }
  else
      Try(ColumnNamesVec <- colnames(contrastsMatrix))

  Try(RowNamesVec <- c())
  Try(for (i in (1:NumRows))
  {
      Try(if (is.null(rownames(contrastsMatrix)))
        Try(RowName <- paste("Param",i))
      else
        Try(RowName <- rownames(contrastsMatrix)[i]))
      Try(RowNamesVec <- c(RowNamesVec,RowName))
  })

  if (NumCols>0)
    for (i in (1:NumCols))
    {
      Try(FirstItemOfPair  <- paste(RowNamesVec[contrastsMatrixList$Param1[i]]))
      Try(SecondItemOfPair <- paste(RowNamesVec[contrastsMatrixList$Param2[i]]))
      Try(if (plusOrMinus[i]=="+") plusOrMinusText <- "plus" else plusOrMinusText <- "minus")
      Try(tkgrid(tklabel(ttViewContrastsMatrixAsPairs,text="    "),
                 tklabel(ttViewContrastsMatrixAsPairs,text=ColumnNamesVec[i],background="white",font=.affylmGUIglobals$affylmGUIfont2),
                 tklabel(ttViewContrastsMatrixAsPairs,text="    "),
                 tklabel(ttViewContrastsMatrixAsPairs,text=FirstItemOfPair,background="white",font=.affylmGUIglobals$affylmGUIfont2),
                 tklabel(ttViewContrastsMatrixAsPairs,text="    "),
                 tklabel(ttViewContrastsMatrixAsPairs,text=plusOrMinusText,font=.affylmGUIglobals$affylmGUIfont2,bg="white"),                 
                 tklabel(ttViewContrastsMatrixAsPairs,text="    "),
                 tklabel(ttViewContrastsMatrixAsPairs,text=SecondItemOfPair,background="white",font=.affylmGUIglobals$affylmGUIfont2),
                 tklabel(ttViewContrastsMatrixAsPairs,text="    ")                 
                 ))
      Try(tkgrid(tklabel(ttViewContrastsMatrixAsPairs,text="    ")))
    }
  tkgrid(tklabel(ttViewContrastsMatrixAsPairs,text="     "))
  
  Advanced.but <- tkbutton(ttViewContrastsMatrixAsPairs,text="Advanced...",command=function() {ViewContrastsMatrixInTable(contrastsMatrixList,contrastParameterizationIndex)},font=.affylmGUIglobals$affylmGUIfont2)
  onOK <- function() {Try(tkgrab.release(ttViewContrastsMatrixAsPairs));Try(tkdestroy(ttViewContrastsMatrixAsPairs));Try(tkfocus(.affylmGUIglobals$ttMain))}
  OK.but <-tkbutton(ttViewContrastsMatrixAsPairs,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(tklabel(ttViewContrastsMatrixAsPairs,text="    "),OK.but,Advanced.but)
  tkgrid(tklabel(ttViewContrastsMatrixAsPairs,text="    "))
      
  Try(tkfocus(ttViewContrastsMatrixAsPairs))
  
  Try(tkbind(ttViewContrastsMatrixAsPairs, "<Destroy>", function() {Try(tkgrab.release(ttViewContrastsMatrixAsPairs));Try(tkfocus(.affylmGUIglobals$ttMain))}))
  Try(tkwait.window(ttViewContrastsMatrixAsPairs))
}

ViewExistingContrastParameterization <- function()
{
  Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
  Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
  if (NumContrastParameterizations==0)
  {
    Try(tkmessageBox(title="View Existing Contrasts Parameterization",message="There are no contrast parameterizations loaded.  Select \"Compute Contrasts\" from the \"Linear Model\" menu.",type="ok",icon="error"))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    return()  
  }
  
  Try(contrastParameterizationIndex <- ChooseContrastParameterization())
  Try(if (contrastParameterizationIndex==0)    return())
  Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])

  Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
  Try(ContrastParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
  
  Try(ContrastParameterizationTREEIndexVec <- ContrastParameterizationList[[ContrastParameterizationNameNode]]$ContrastParameterizationTREEIndexVec)
  Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])          
  Try(ContrastsContrastParameterizationListNode <- paste("ContrastParameterizations.",.affylmGUIglobals$ContrastParameterizationTREEIndex,".",.affylmGUIglobals$ContrastParameterizationTREEIndex, sep=""))  
  Try(contrastsList <- ContrastParameterizationList[[ContrastParameterizationNameNode]]$contrastsMatrixInList)  
  Try(if (contrastsList$contrastsCreatedFromDropDowns==FALSE)
      Try(ViewContrastsMatrixInTable(contrastsMatrix="Contrasts",contrastsList,contrastParameterizationIndex))
  else
      Try(ViewContrastsMatrixAsPairs(contrastsMatrix="Contrasts",contrastsList,contrastParameterizationIndex)))
}

ViewRNATargets <- function()
{
      Try(NumSlides <- get("NumSlides",envir=affylmGUIenvironment))
      Try(Targets <- get("Targets",envir=affylmGUIenvironment))      
      Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  
      if (ArraysLoaded==FALSE)
      {
          Try(tkmessageBox(title="RNA Targets",message="No arrays have been loaded.  Please try New or Open from the File menu.",type="ok",icon="error"))
          Try(tkfocus(.affylmGUIglobals$ttMain))
          return()
      }
      if (nrow(Targets)==0)
      {
          Try(tkmessageBox(title="RNA Targets",message="No RNA targets have been loaded.  Please try New or Open from the File menu.",type="ok",icon="error"))
          Try(tkfocus(.affylmGUIglobals$ttMain))
          return()
      }

      Try(TclRequire("Tktable"))
      Try(ttViewRNATargets <- tktoplevel(.affylmGUIglobals$ttMain))
      Try(tkwm.deiconify(ttViewRNATargets))
#      Try(tkgrab.set(ttViewRNATargets))
      Try(tkfocus(ttViewRNATargets))
      Try(tkwm.title(ttViewRNATargets,"RNA Targets"))
      
#      Try(n <- evalq(TclVarCount <- TclVarCount + 1, .TkRoot$env))
#     Try(tclArrayName <- paste("::RTcl", n, sep = ""))
      Try(tclArrayVar1 <- tclArrayVar())
      Try(tclArrayName <- ls(tclArrayVar1$env))
      
#      onClose <- function() {Try(tkgrab.release(ttViewRNATargets));Try(tkdestroy(ttViewRNATargets));Try(tkfocus(.affylmGUIglobals$ttMain))}
      onClose <- function() {Try(tkdestroy(ttViewRNATargets));Try(tkfocus(.affylmGUIglobals$ttMain))}
      
      Try(NumCols <- ncol(Targets))
      Try(NumRows <- nrow(Targets))
     
      Try(myRarray <- c())

      if (NumCols>0)
        for (j in (1:NumCols))      
        {
          Try(myRarray <- c(myRarray,paste(colnames(Targets)[j])))
          for (i in (1:NumRows))
          {          
              Try(myRarray <- c(myRarray,paste(Targets[i,j])))
          }      
        }      

          Try(dim(myRarray) <- c(NumRows+1,NumCols))

          # This will give an error if tclArray doesn't exist.
          # .Tcl("unset tclArray")
          if (NumRows>0 && NumCols>0)
            for (i in (0:NumRows))
              for (j in (1:NumCols))
#                 Try(.Tcl(paste("set ",tclArrayName,"(",i,",",j-1,") ",myRarray[i+1,j],sep="")))                 
                 Try(tkcmd("set",paste(tclArrayName,"(",i,",",j-1,")",sep=""),paste(myRarray[i+1,j])))
         
          # Below, I should just use tkwidget(ttViewRNATargets,"table",...) 
          Try(table1 <- .Tk.subwin(ttViewRNATargets))
          Try(.Tcl(paste("table",.Tk.ID(table1),.Tcl.args(variable=tclArrayName,rows=paste(NumRows+1),cols=paste(NumCols),titlerows="0",titlecols="0",selectmode="extended",colwidth="13",background="white",rowseparator="\"\n\"",colseparator="\"\t\"",resizeborders="col",multiline="0",
                titlerows=1,colstretchmode="unset",
                xscrollcommand=function(...) tkset(xscr,...),yscrollcommand=function(...) tkset(yscr,...),state="disabled"))))
          Try(xscr <- tkscrollbar(ttViewRNATargets,orient="horizontal", command=function(...)tkxview(table1,...)))
          Try(yscr <- tkscrollbar(ttViewRNATargets,command=function(...)tkyview(table1,...)))               
          Try(tkgrid(table1,yscr))
          Try(tkgrid.configure(yscr,sticky="nsw"))
          Try(tkgrid(xscr))
          Try(tkgrid.configure(xscr,sticky="new"))
          Try(tkconfigure(table1,font=.affylmGUIglobals$affylmGUIfontTable))

          for (j in (1:NumCols))      
            Try(tkcmd(.Tk.ID(table1),"width",paste(j-1),paste(max(4,nchar(colnames(Targets)[j])+2,max(nchar(Targets[,j]))+2))))

          Try(copyFcn <-      function() .Tcl(paste("event","generate",.Tcl.args(.Tk.ID(table1),"<<Copy>>"))))

          saveTargetsFile <- function()
          {
            Try(TargetsFileNameText <- tclvalue(tkgetSaveFile(filetypes="{{RNA Targets Files} {.txt}} {{All files} *}")))
            Try(if (!nchar(TargetsFileNameText)) return())
            Try(len <- nchar(TargetsFileNameText))
            if (len<=4)
              Try(  TargetsFileNameText <- paste(TargetsFileNameText,".txt",sep=""))
            else if (substring(TargetsFileNameText,len-3,len)!=".txt")
                  Try(TargetsFileNameText <- paste(TargetsFileNameText,".txt",sep=""))
            Try(Targets <- matrix(nrow=NumRows,ncol=NumCols))
            Try(colnamesTargets <- c())
            if (NumCols>0)
              Try(for (j in (1:NumCols))
                colnamesTargets[j] <- tclvalue(paste(tclArrayName,"(0,",j-1,")",sep="")))
            Try(colnames(Targets) <- colnamesTargets)       
            if (NumRows>0 && NumCols>0)
              Try(for (i in (1:NumRows))
                 for (j in (1:NumCols))
                    Targets[i,j] <- tclvalue(paste(tclArrayName,"(",i,",",j-1,")",sep="")))

            Try(write.table(Targets,file=TargetsFileNameText,sep="\t",quote=FALSE,col.names=TRUE,row.names=FALSE))
          }


          Try(topMenu <- tkmenu(ttViewRNATargets, tearoff=FALSE))

          Try(topMenu <- tkmenu(ttViewRNATargets, tearoff=FALSE))
          Try(fileMenu <- tkmenu(topMenu, tearoff=FALSE))
          Try(tkadd(fileMenu, "command", label="Save As",   command=saveTargetsFile)) # ) # ,font=affylmGUIfontMenu))
          Try(tkadd(fileMenu, "command", label="Close",   command=onClose)) # ) # ,font=affylmGUIfontMenu))          
          Try(tkadd(topMenu,  "cascade", label="File",menu=fileMenu)) # ) # ,font=affylmGUIfontMenu))  

          Try(editMenu <- tkmenu(topMenu, tearoff=FALSE))
          Try(tkadd(editMenu, "command", label="Copy <Ctrl-C>",      command=copyFcn)) # ) # ,font=affylmGUIfontMenu))
          Try(tkadd(topMenu,  "cascade", label="Edit",menu=editMenu)) # ) # ,font=affylmGUIfontMenu))  
                   
          Try(tkconfigure(ttViewRNATargets,menu=topMenu))

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

########################################################################################################
# Some C-style string searching functions, because I'm not very good at using regular expressions ;-) 

# Returns the index where needle is found in haystack or zero if not found.
nstrstr <- function(haystack,needle)
{
  lenHaystack <- nchar(haystack)
  lenNeedle   <- nchar(needle)
  if (lenHaystack < lenNeedle)
    return (0)
  if (lenHaystack == lenNeedle)
    return(haystack==needle)
  lenDiff <- lenHaystack-lenNeedle
  for (i in (1:lenDiff))
    if (needle==substr(haystack,i,i+lenNeedle-1))
      return(i)

  return (0)
}

strstr <- function(haystack,needle)
{
  strIndex <- nstrstr(haystack,needle)
  if (strIndex==0)
    return ("")
  return (substr(haystack,strIndex,nchar(haystack)))
}


ComputeContrasts <- function()
{
  # For now, we will assume that the number of contrasts is one less than the number of parameters,
  # e.g. with 4 treatments, we estimate 4 parameters, then 3 contrasts.
  
  Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
  Try(ContrastParameterizationNamesVec <- get("ContrastParameterizationNamesVec",envir=affylmGUIenvironment))
  Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
  Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))  
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(LinearModelFit.Available <- get("LinearModelFit.Available", envir=affylmGUIenvironment))

  if (ArraysLoaded==FALSE)
  {
      Try(tkmessageBox(title="Compute Contrasts",message="No arrays have been loaded.  Please try New or Open from the File menu.",type="ok",icon="error"))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      return()
  }
  
  if (LinearModelFit.Available==FALSE)
  {
    Try(ComputeLinearModelFit())
    Try(NumParameters <- get("NumParameters",envir=affylmGUIenvironment))
#    Try(tkmessageBox(title="Compute Contrasts",message="There is no linear model fit available.  Select \"Compute Linear Model Fit\" from the \"Linear Model\" menu.",type="ok",icon="error"))
#    Try(tkfocus(.affylmGUIglobals$ttMain))
#    return()  
  }  
  Try(fit    <- get("fit",   envir=affylmGUIenvironment))
  Try(design <- get("design",envir=affylmGUIenvironment))

  Try(ParameterNamesVec  <- colnames(design))
  
  Try(NumContrasts <- NumParameters - 1)

  Try(if (NumContrasts<=0)
  {
    tkmessageBox(title="Compute Contrasts",message=paste("You need to have two or more treatments in order to compute contrasts."),type="ok",icon="error")
    Try(tkfocus(.affylmGUIglobals$ttMain))
    return()
  })
  
  Try(NumContrasts <- min(NumContrasts,10))
  
  Try(contrastsMatrixInList <- GetContrasts(NumContrasts=NumContrasts))
  Try(if (nrow(contrastsMatrixInList$contrasts)==0) return())
  Try(contrastsMatrix <- as.matrix(contrastsMatrixInList$contrasts))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  Try(contrastsFit <- contrasts.fit(fit,contrastsMatrix))
  
  # NEW
  
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(if (min(contrastsFit$df)==0)
  {
    Try(tkmessageBox(title="No degrees of freedom",message="Empirical Bayes statistics will not be available because of the lack of replicate arrays.",icon="warning"))
    Try(ebayesAvailable <- FALSE)
  }
  else
    Try(ebayesAvailable <- TRUE))
  
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  Try(if (ebayesAvailable==TRUE)
    Try(contrastsEbayes <- eBayes(contrastsFit)))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(ContrastParameterizationNameText <- GetContrastParameterizationName())  
  Try(if (ContrastParameterizationNameText=="GetContrastParameterizationName.CANCEL") return())
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  Try(while (nchar(ContrastParameterizationNameText)==0)
  {
      Try(tkmessageBox(title="Contrasts Name",message="Please enter a name for this set of contrasts",type="ok",icon="error"))
      Try(ContrastParameterizationNameText <- GetContrastParameterizationName())
      if (ContrastParameterizationNameText=="GetContrastParameterizationName.CANCEL") 
      {
          Try(tkfocus(.affylmGUIglobals$ttMain))          
          return()
      }
  })
  
  Try(contrastParameterizationIndex <- 0)
  Try(newContrastParameterization <- 1)
  Try(if (ContrastParameterizationNameText %in% ContrastParameterizationNamesVec)
  {
      Try(contrastParameterizationIndex <- match(ContrastParameterizationNameText,ContrastParameterizationNamesVec))
      Try(mbVal<-tclvalue(tkmessageBox(title="Contrasts Parameterization Name",message="This contrasts parameterization name already exists.  Replace?",type="yesnocancel",icon="question")))
      Try(if (mbVal=="cancel") return())
      Try(if (mbVal=="yes") newContrastParameterization <- 0)
      Try(if (mbVal=="no") newContrastParameterization <- 1)
  }
  else
      Try(newContrastParameterization <- 1))

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

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

  if (newContrastParameterization==1)
  {
      Try(if (length(ContrastParameterizationTREEIndexVec)!=NumContrastParameterizations)
      {
          Try(tkmessageBox(title="Contrasts Parameterizations","Length of ContrastParameterizationTREEIndexVec is not equal to NumContrastParameterizations.",type="ok",icon="error"))
          Try(tkfocus(.affylmGUIglobals$ttMain))
          return()
      })
      Try(NumContrastParameterizations <- NumContrastParameterizations + 1)
      Try(contrastParameterizationIndex <- NumContrastParameterizations)
      Try(if (length(ContrastParameterizationTREEIndexVec)==0)
          Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- 1)
      else
          Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- max(ContrastParameterizationTREEIndexVec)+1))
      Try(ContrastParameterizationTREEIndexVec[contrastParameterizationIndex] <- .affylmGUIglobals$ContrastParameterizationTREEIndex)

      Try(ContrastParameterizationNamesVec <- c(ContrastParameterizationNamesVec,ContrastParameterizationNameText))     
      
      Try(ContrastParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
      Try(ContrastParameterizationList[[ContrastParameterizationNameNode]] <- ContrastParameterizationNameText)
  }
  else # Replace existing contrasts parameterization with the same name.
  {
      Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
      Try(tkdelete(.affylmGUIglobals$ContrastParameterizationTREE,paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep="")))
  }  
  
  Try(ContrastParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
 
  Try(ContrastParameterizationList[[ContrastParameterizationNameNode]] <- list())

  Try(ContrastParameterizationList[[ContrastParameterizationNameNode]]$NumContrastParameterizations <- NumContrastParameterizations)
  
  Try(NormalizedAffyData <- get("NormalizedAffyData",affylmGUIenvironment))
  Try(contrastsFit$Amean <- rowMeans(exprs(NormalizedAffyData)))
  
  Try(ContrastParameterizationList[[ContrastParameterizationNameNode]]$fit <- contrastsFit)
  Try(if (ebayesAvailable==TRUE)  
    Try(ContrastParameterizationList[[ContrastParameterizationNameNode]]$eb  <- contrastsEbayes)
  else
    Try(ContrastParameterizationList[[ContrastParameterizationNameNode]]$eb  <- list()))
  Try(ContrastParameterizationList[[ContrastParameterizationNameNode]]$contrastsMatrixInList <- contrastsMatrixInList)
  Try(ContrastParameterizationList[[ContrastParameterizationNameNode]]$ContrastParameterizationNameText <- ContrastParameterizationNameText)  
 
  if (NumContrastParameterizations>0)
    Try(ContrastsNames <- colnames(contrastsMatrix))
  Try(tkinsert(.affylmGUIglobals$ContrastParameterizationTREE,"end","root",ContrastParameterizationNameNode,text=ContrastParameterizationNameText,font=.affylmGUIglobals$affylmGUIfontTree))
  Try(NumContrastsInContrastParameterization <- length(ContrastsNames))
  
  Try(ContrastsNode <- paste("ContrastsNode.",.affylmGUIglobals$ContrastParameterizationTREEIndex))
  
  Try(tkinsert(.affylmGUIglobals$ContrastParameterizationTREE,"end",ContrastParameterizationNameNode,ContrastsNode,text="Contrasts",font=.affylmGUIglobals$affylmGUIfontTree))  
  
  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(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))      )
  Try(assign("ContrastParameterizationList",ContrastParameterizationList,affylmGUIenvironment))
  Try(assign("NumContrastParameterizations",NumContrastParameterizations,affylmGUIenvironment))  
  Try(assign("ContrastParameterizationTREEIndexVec",ContrastParameterizationTREEIndexVec,affylmGUIenvironment))
  Try(assign("ContrastParameterizationNamesVec",ContrastParameterizationNamesVec,affylmGUIenvironment))
  
  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(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))
    }
  else
    Try(tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)))  
  
  tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow")       
}

ComputeLinearModelFit <- function()
{
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(if (ArraysLoaded==FALSE)
  {
    Try(tkmessageBox(title="Linear Model",message="Error: No arrays have been loaded.",
        icon="error",default="ok"))
    return()
  })
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  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="Linear Model",message="An error occured while trying to normalize the data.")
    return()
  
  })
  Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
  Try(Targets <- get("Targets",envir=affylmGUIenvironment))
  Try(design <- as.matrix(as.data.frame(model.matrix(~ -1 + factor(Targets$Target)))))
  Try(NumParameters <- ncol(design))
  Try(assign("NumParameters",NumParameters,affylmGUIenvironment))
  Try(colnames(design) <- gsub("factor\\(Targets\\$Target\\)","",colnames(design)))
  Try(rownames(design) <- Targets$FileName)
  Try(assign("design",design,affylmGUIenvironment))  
  Try(fit <- lm.series(exprs(NormalizedAffyData),design,weights=NULL))
  Try(assign("LinearModelFit.Available",TRUE,affylmGUIenvironment))
  Try(assign("fit",fit,affylmGUIenvironment))
  Try(tkdelete(.affylmGUIglobals$mainTree,"LinearModelFit.Status"))        
  Try(tkinsert(.affylmGUIglobals$mainTree,"end","LinearModelFit","LinearModelFit.Status",text="Available",font=.affylmGUIglobals$affylmGUIfontTree))  
  Try(NumParameters <- get("NumParameters" , envir=affylmGUIenvironment))
  Try(if (NumParameters>0)
    Try(for (i in (1:NumParameters))
      Try(tkdelete(.affylmGUIglobals$mainTree,paste("Parameters.Status.",i,sep=""))))
  else
      Try(tkdelete(.affylmGUIglobals$mainTree,"Parameters.Status.1")))
  Try(for (i in (1:ncol(design)))
    Try(tkinsert(.affylmGUIglobals$mainTree,"end","Parameters",paste("Parameters.Status.",i,sep="") ,
      text=colnames(design)[i],font=.affylmGUIglobals$affylmGUIfontTree)))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))      
}

GetContrast <- function(contrastParameterizationIndex)
{
  Try(ttGetContrast<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttGetContrast))
  Try(tkgrab.set(ttGetContrast)  )
  Try(tkfocus(ttGetContrast))
  Try(tkwm.title(ttGetContrast,"Choose a contrast"))
  Try(scr <- tkscrollbar(ttGetContrast, repeatinterval=5,command=function(...)tkyview(tl,...)))
  Try(xscr <- tkscrollbar(ttGetContrast, repeatinterval=5,command=function(...)tkxview(tl,...) ,orient="horizontal"))                       
  ## Safest to make sure scr exists before setting yscrollcommand
  Try(tl<-tklistbox(ttGetContrast,height=4,width=30,selectmode="single",xscrollcommand=function(...)tkset(xscr,...),yscrollcommand=function(...)tkset(scr,...),background="white",font=.affylmGUIglobals$affylmGUIfont2)   )
  Try(lbl2<-tklabel(ttGetContrast,text="Which contrast is this for?",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttGetContrast,text="       "),row=0,column=1,columnspan=1))
  Try(tkgrid(tklabel(ttGetContrast,text="       "),row=0,column=4,columnspan=1))
  Try(tkgrid(lbl2,row=1,column=2,columnspan=2,rowspan=1))
  Try(tkgrid.configure(lbl2,sticky="w"))
  Try(tkgrid(tklabel(ttGetContrast,text="         "),row=2,column=1))
  Try(tkgrid(tl,row=2,column=2,columnspan=2,rowspan=4,sticky="ew"))
  Try(tkgrid(scr,row=2,column=4,columnspan=1,rowspan=4,sticky="wns"))
  Try(tkgrid(xscr,row=6,column=2,columnspan=2,sticky="wne"))
  
  Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))

  Try(ContrastNamesVec  <- colnames(as.matrix(ContrastParameterizationList[[contrastParameterizationIndex]]$contrastsMatrixInList$contrasts)))
  
  Try(NumContrasts <- length(ContrastNamesVec))
  
  coefIndexList <- list()

  if (NumContrasts>0)
    Try(for (i in (1:NumContrasts))     
      Try(tkinsert(tl,"end",ContrastNamesVec[i])))

  Try(tkselection.set(tl,0))

  Try(ReturnVal <- list(coefIndex=0)) # Other attributes can be added later if necessary.
  onOK <- function()
  {
      Try(contrastNum <- as.numeric(tclvalue(tkcurselection(tl)))+1)
      Try(tkgrab.release(ttGetContrast));Try(tkdestroy(ttGetContrast));Try(tkfocus(.affylmGUIglobals$ttMain))
        Try(ReturnVal <<- list(contrastIndex=contrastNum))
  }
  onCancel <- function() {Try(tkgrab.release(ttGetContrast));Try(tkdestroy(ttGetContrast));Try(tkfocus(.affylmGUIglobals$ttMain));Try(ReturnVal <<- list(contrastIndex=0))}
  Try(OK.but <-tkbutton(ttGetContrast,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <-tkbutton(ttGetContrast,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttGetContrast,text="    ")))
  Try(tkgrid(tklabel(ttGetContrast,text="    "),tklabel(ttGetContrast,text="    "),OK.but,Cancel.but))
  Try(tkgrid.configure(OK.but,sticky="e"))
  Try(tkgrid.configure(Cancel.but,sticky="w"))  
  Try(tkbind(OK.but, "<Return>",onOK))
  Try(tkbind(tl, "<Return>",onOK))    
  Try(tkbind(Cancel.but, "<Return>",onCancel))      
  Try(tkgrid(tklabel(ttGetContrast,text="    ")))
  Try(tkfocus(ttGetContrast))
  Try(tkbind(ttGetContrast, "<Destroy>", function() {Try(tkgrab.release(ttGetContrast));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkwait.window(ttGetContrast))

  return (ReturnVal)
}

showTopTable <- function()
{
  Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
  Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
  Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))  
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  
  Try(if (ArraysLoaded==FALSE)
  {
      Try(tkmessageBox(title="Top Table",message="No arrays have been loaded.  Please try New or Open from the File menu.",type="ok",icon="error"))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      return()
  })
  
  Try(if (NumContrastParameterizations==0)
  {
    Try(tkmessageBox(title="Top Table",message="There are no contrast parameterizations available.  Select \"Compute Contrasts\" from the \"Linear Model\" menu.",type="ok",icon="error"))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    return()  
  })  
  Try(contrastParameterizationIndex <- ChooseContrastParameterization())
  Try(if (contrastParameterizationIndex==0) return()) # Cancel
  
  Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
  Try(ContrastNamesVec  <- colnames(as.matrix(ContrastParameterizationList[[contrastParameterizationIndex]]$contrastsMatrixInList$contrasts)))

  Try(GetContrastReturnVal <- GetContrast(contrastParameterizationIndex))
  Try(if (GetContrastReturnVal$contrastIndex==0) return()) # Cancel
  Try(contrast <- GetContrastReturnVal$contrastIndex)
  Try(ContrastParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))

  Try(fit <- (ContrastParameterizationList[[ContrastParameterizationNameNode]])$fit)
#  Try(eb  <- (ContrastParameterizationList[[ContrastParameterizationNameNode]])$eb)

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

  # This is a bit silly, calculating it again.  This should be tidied up later.  But basically, we're
  # checking whether we had degrees of freedom > 0 from the linear model fit (i.e. were there any
  # replicate arrays?)  If so, eBayes should work, and we can use Gordon's new method (adding new
  # attributes to the fit object rather than using eb), because this seems to work best with topTable,
  # affy data etc.
  Try(if (ebayesAvailable==TRUE)
    Try(fit <- eBayes(fit)))
  
  Try(ttToptableDialog<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttToptableDialog))
  Try(tkgrab.set(ttToptableDialog))
  Try(tkfocus(ttToptableDialog))
  Try(tkwm.title(ttToptableDialog,"Toptable Options"))
  Try(tkgrid(tklabel(ttToptableDialog,text="    ")))
    
  Try(frame1 <- tkframe(ttToptableDialog,relief="groove",borderwidth=2))
  Try(HowManyQuestion1 <- tklabel(frame1,text=
    "Number of genes in table:",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(HowManyQuestion1))
  Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
  
  Try(numberOfGenesTcl <- tclVar("3"))
  Try(Ten.but      <- tkradiobutton(frame1,text="10",variable=numberOfGenesTcl,value="1",font=.affylmGUIglobals$affylmGUIfont2))
  Try(Thirty.but   <- tkradiobutton(frame1,text="30",variable=numberOfGenesTcl,value="2",font=.affylmGUIglobals$affylmGUIfont2))
  Try(Fifty.but    <- tkradiobutton(frame1,text="50",variable=numberOfGenesTcl,value="3",font=.affylmGUIglobals$affylmGUIfont2))  
  Try(Hundred.but  <- tkradiobutton(frame1,text="100",variable=numberOfGenesTcl,value="4",font=.affylmGUIglobals$affylmGUIfont2))    
  Try(AllGenes.but <- tkradiobutton(frame1,text="All genes",variable=numberOfGenesTcl,value="5",font=.affylmGUIglobals$affylmGUIfont2))      
  
  Try(tkgrid(Ten.but,sticky="w"))
  Try(tkgrid(Thirty.but,sticky="w"))
  Try(tkgrid(Fifty.but,sticky="w"))
  Try(tkgrid(Hundred.but,sticky="w"))  
  Try(tkgrid(AllGenes.but,sticky="w"))  
  Try(tkgrid.configure(HowManyQuestion1,Ten.but,Thirty.but,Fifty.but,Hundred.but,AllGenes.but,sticky="w"))

  Try(frame2 <- tkframe(ttToptableDialog,relief="groove",borderwidth=2))
  Try(sortByLabel <- tklabel(frame2,text="Sort by:",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(sortByLabel,sticky="w"))  
  Try(tkgrid.configure(sortByLabel,sticky="w"))
  Try(if (ebayesAvailable==TRUE)
    Try(sortByTcl <- tclVar("B"))
  else
    Try(sortByTcl <- tclVar("M")))
    
  Try(M.but <- tkradiobutton(frame2,text="M",variable=sortByTcl,value="M",font=.affylmGUIglobals$affylmGUIfont2))
  Try(A.but <- tkradiobutton(frame2,text="A",variable=sortByTcl,value="A",font=.affylmGUIglobals$affylmGUIfont2))
  Try(T.but <- tkradiobutton(frame2,text="t statistic",variable=sortByTcl,value="T",font=.affylmGUIglobals$affylmGUIfont2))  
  Try(P.but <- tkradiobutton(frame2,text="P value",variable=sortByTcl,value="P",font=.affylmGUIglobals$affylmGUIfont2))    
  Try(B.but <- tkradiobutton(frame2,text="B statistic",variable=sortByTcl,value="B",font=.affylmGUIglobals$affylmGUIfont2))      
  
  Try(tkgrid(M.but,sticky="w"))
  Try(tkgrid(A.but,sticky="w"))
  Try(tkgrid(T.but,sticky="w"))
  Try(tkgrid(P.but,sticky="w"))  
  Try(tkgrid(B.but,sticky="w"))

  Try(if (ebayesAvailable==FALSE)
  {
    Try(tkconfigure(T.but,state="disabled"))
    Try(tkconfigure(P.but,state="disabled"))
    Try(tkconfigure(B.but,state="disabled"))
  })

  Try(frame3 <- tkframe(ttToptableDialog,relief="groove",borderwidth=2))
  Try(adjustMethodLabel <- tklabel(frame3,text="Adjust method:",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(adjustMethodLabel,sticky="w"))
  Try(tkgrid.configure(adjustMethodLabel,sticky="w"))  
  Try(if (ebayesAvailable==TRUE)
    Try(adjustMethodTcl <- tclVar("holm"))
  else
     Try(adjustMethodTcl <- tclVar("none")))
  Try(bonferroni.but <- tkradiobutton(frame3,text="Bonferroni",variable=adjustMethodTcl,value="bonferroni",font=.affylmGUIglobals$affylmGUIfont2))
  Try(holm.but <- tkradiobutton(frame3,text="Holm",variable=adjustMethodTcl,value="holm",font=.affylmGUIglobals$affylmGUIfont2))
  Try(hochberg.but <- tkradiobutton(frame3,text="Hochberg",variable=adjustMethodTcl,value="hochberg",font=.affylmGUIglobals$affylmGUIfont2))  
  Try(hommel.but <- tkradiobutton(frame3,text="Hommel",variable=adjustMethodTcl,value="hommel",font=.affylmGUIglobals$affylmGUIfont2))    
  Try(fdr.but <- tkradiobutton(frame3,text="FDR",variable=adjustMethodTcl,value="fdr",font=.affylmGUIglobals$affylmGUIfont2))      
  Try(none.but <- tkradiobutton(frame3,text="None",variable=adjustMethodTcl,value="none",font=.affylmGUIglobals$affylmGUIfont2))      

  Try(tkgrid(bonferroni.but,sticky="w"))
  Try(tkgrid(holm.but,sticky="w"))
  Try(tkgrid(hochberg.but,sticky="w"))
  Try(tkgrid(hommel.but,sticky="w"))  
  Try(tkgrid(fdr.but,sticky="w"))
  Try(tkgrid(none.but,sticky="w"))  

  Try(if (ebayesAvailable==FALSE)
  {
    Try(tkconfigure(bonferroni.but,state="disabled"))
    Try(tkconfigure(holm.but,state="disabled"))
    Try(tkconfigure(hochberg.but,state="disabled"))
    Try(tkconfigure(hommel.but,state="disabled"))    
    Try(tkconfigure(fdr.but,state="disabled"))        
    Try(tkconfigure(none.but,state="disabled"))            
  })

  Try(totalGenes <- nrow(fit$coefficients))
  Try(Abort <- 1)
  Try(numberOfGenes <- 0)
  Try(sortBy <- "B")
  Try(adjustMethod <- "holm")
  Try(onOK <- function()
  {     
      Try(NumGenesChoice <- as.numeric(tclvalue(numberOfGenesTcl)))
      Try(tkgrab.release(ttToptableDialog))
      Try(tkdestroy(ttToptableDialog))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      NumbersOfGenes <- c(10,30,50,100,totalGenes)
      numberOfGenes <<- NumbersOfGenes[NumGenesChoice]      
      sortBy <<- tclvalue(sortByTcl)
      adjustMethod <<- tclvalue(adjustMethodTcl)      
      Abort <<- 0
  })

  Try(frame4 <- tkframe(ttToptableDialog,borderwidth=2))
  Try(onCancel <- function() {Try(tkgrab.release(ttToptableDialog));Try(tkdestroy(ttToptableDialog));Try(tkfocus(.affylmGUIglobals$ttMain));Abort <<- 1})
  Try(OK.but <-tkbutton(frame4,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <-tkbutton(frame4,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
  
  Try(tkgrid(tklabel(frame4,text="    "),OK.but,Cancel.but,tklabel(frame4,text="    ")))

  Try(tkgrid(tklabel(ttToptableDialog,text="    "),frame1,frame2,tklabel(ttToptableDialog,text="  ")))
  Try(tkgrid(tklabel(ttToptableDialog,text="    ")))
  Try(tkgrid(tklabel(ttToptableDialog,text="    "),frame3,frame4,tklabel(ttToptableDialog,text="  ")))
  Try(tkgrid(tklabel(ttToptableDialog,text="    ")))  
  Try(tkgrid.configure(frame1,frame3,sticky="w"))
#  Try(tkgrid.configure(frame4,sticky="s"))
  
  Try(tkfocus(ttToptableDialog))
  Try(tkbind(ttToptableDialog, "<Destroy>", function() {Try(tkgrab.release(ttToptableDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkwait.window(ttToptableDialog))
    
  Try(if (Abort==1) 
     return())
  
  Try(if (numberOfGenes==totalGenes) 
  {
      tkconfigure(.affylmGUIglobals$ttMain,cursor="watch")
      Try(tkfocus(.affylmGUIglobals$ttMain))
  })

  Try(options(digits=3))
    
  Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))
  Try(cdfenv<-getCdfInfo(RawAffyData))

  Try(genelist <- data.frame(ID=I(ls(cdfenv))))

  Try(geneNames <- get("geneNames",envir=affylmGUIenvironment))
  Try(geneSymbols <- get("geneSymbols",envir=affylmGUIenvironment))  
  Try(if (length(geneNames)==0|| length(geneSymbols)==0)
  {
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))  
    Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))
    Try(dataName <- strsplit(cleancdfname(RawAffyData@cdfName),"cdf")[[1]])
    Require("reposTools")
    Try(annoPackages <- getReposEntry("http://www.bioconductor.org/data/metaData"))    
    Try(matchIndex <- match(dataName,annoPackages@repdatadesc@repdatadesc[,"Package"]))
    Try(if (!is.na(matchIndex))
    {
      Try(install.packages2(dataName,annoPackages))
      Require(dataName)
      Try(code2eval <- paste("Try(geneNames <- as.character(unlist(multiget(ls(envir=",dataName,"GENENAME),env=",dataName,"GENENAME))))",sep=""))
      Try(eval(parse(text=code2eval)))
      Try(assign("geneNames",geneNames,affylmGUIenvironment))
      Try(code2eval <- paste("Try(geneSymbols <- as.character(unlist(multiget(ls(envir=",dataName,"SYMBOL),env=",dataName,"SYMBOL))))",sep=""))
      Try(eval(parse(text=code2eval)))
      Try(assign("geneSymbols",geneSymbols,affylmGUIenvironment))      
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(genelist <- cbind(as.matrix(as.character(ls(cdfenv))),as.matrix(geneSymbols),as.matrix(geneNames)))
      Try(colnames(genelist) <- c("ID","Symbol","Name"))
    }
    else
    {
      Try(genelist <- data.frame(ID=I(ls(cdfenv))))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    })
    
  }
  else
  {
    Try(genelist <- cbind(as.matrix(as.character(ls(cdfenv))),as.matrix(geneSymbols),as.matrix(geneNames)))
    Try(colnames(genelist) <- c("ID","Symbol","Name"))
  })

   Try(fit$genes <- genelist)
   Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
	 Try(if (!("Amean" %in% names(fit)))
	    fit$Amean <- rowMeans(exprs(NormalizedAffyData)))
	    
	    
	# Note that it is difficult to use the limma toptable/topTable functions if you don't have ebayes statistics, so
	# in the case of no replicate arrays (no residual degrees of freedom) we will just do our own sorting.
	
  Try(if (ebayesAvailable==FALSE)
  {
	  Try(M <- as.matrix(fit$coef)[,contrast])
	  Try(A <- fit$Amean)
	  Try(ord <- switch(sortBy, M = order(abs(M), decreasing = TRUE), A = order(A, decreasing = TRUE)))
	  Try(top <- ord[1:numberOfGenes])
    Try(table1 <- data.frame(genelist[top, ,drop=FALSE], M = M[top], A=A[top]))
    Try(rownames(table1) <- as.character(1:length(M))[top])
  })
	    
# The 2's in front of toptables mean that they use the drop=FALSE option (even if the user hasn't upgraded limma since the 1.3 BioC release.)
#  Try(table1 <- toptable2(coef=contrast,number=numberOfGenes,fit=fit,eb=eb,genelist=genelist,adjust.method=adjustMethod,sort.by=sortBy))
  Try(if (ebayesAvailable==TRUE)
    Try(table1 <- topTable2(coef=contrast,number=numberOfGenes,fit=fit,genelist=genelist,adjust.method=adjustMethod,sort.by=sortBy)))
#  Try(colnames(table1)[ncol(table1)-1] <- sprintf("%-10s",colnames(table1)[ncol(table1)-1]))

  Try(nrows <- nrow(table1))
  Try(ncols <- ncol(table1))  
  
  Try(if (nrows <=100)
  {
    Try(ttToptableTable <- tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.title(ttToptableTable,paste("Top",numberOfGenes,"Candidate Genes for Differential Expression for",ContrastNamesVec[contrast],".",sep=" ")))
    TclRequire("Tktable") 
    Try(toptableTable <- tkwidget(ttToptableTable,"table",
           xscrollcommand=function(...) tkset(xscr,...),yscrollcommand=function(...) tkset(yscr,...),
           rows=nrows+1,cols=ncols,titlerows=1,
           width=ncols,selectmode="extended",colwidth="13",background="white",
           rowseparator="\"\n\"",colseparator="\"\t\"",resizeborders="col",multiline="0",state="disabled",
           font=.affylmGUIglobals$affylmGUIfontTopTable))
    Try(xscr <-tkscrollbar(ttToptableTable,orient="horizontal", command=function(...)tkxview(toptableTable,...)))
    Try(yscr <- tkscrollbar(ttToptableTable,command=function(...)tkyview(toptableTable,...)))
    Try(tclArrayVar1 <- tclArrayVar())
    Try(tclArrayName <- ls(tclArrayVar1$env))
    Try(tkcmd("set",paste(tclArrayName,"0,0",sep=""),""))
    Try(for (j in (1:ncols))
        Try(tkcmd("set",paste(tclArrayName,"(",0,",",j-1,")",sep=""),colnames(table1)[j]))  )
    Try(for (i in (1:nrows))
      for (j in (1:ncols))
      {
        Try(if (is.numeric(table1[i,j]))
          item <- format(table1[i,j],digits=4)
        else
          item <- table1[i,j])
        Try(tkcmd("set",paste(tclArrayName,"(",i,",",j-1,")",sep=""),paste(item)))        
      })
    Try(tkgrid(toptableTable,yscr))
    Try(tkgrid.configure(toptableTable,sticky="news"))
    Try(tkgrid.configure(yscr,sticky="nsw"))
    Try(tkgrid(xscr,sticky="new"))
    Try(tkconfigure(toptableTable,bg="white",variable=tclArrayName))
    Try(for (i in (1:ncols))
    {
      if (tolower(colnames(table1)[i]) %in% c("block","row","column","gridrow","gridcolumn","gridcol","grid.row","grid.col","grid.column"))
      {
        Try(if (.affylmGUIglobals$affylmGUIpresentation==FALSE)
          Try(tkcmd(.Tk.ID(toptableTable),"width",paste(i-1),paste(max(4,nchar(colnames(table1)[i])+2))))
        else
          Try(tkcmd(.Tk.ID(toptableTable),"width",paste(i-1),paste(max(4,nchar(colnames(table1)[i]))))))        
        next()
      }
      if (colnames(table1)[i] %in% c("M","A","t","B"))
      {
        Try(tkcmd(.Tk.ID(toptableTable),"width",paste(i-1),"6"))
        next()
      }
      if (colnames(table1)[i] == "P.Value")
      {
        Try(tkcmd(.Tk.ID(toptableTable),"width",paste(i-1),"8"))
        next()
      }     
      if(tolower(colnames(table1)[i]) == "name")
      {
        Try(tkcmd(.Tk.ID(toptableTable),"width",paste(i-1),paste(30)))
        next()
      }

      if(tolower(colnames(table1)[i]) == "id")
      {
        Try(tkcmd(.Tk.ID(toptableTable),"width",paste(i-1),paste(min(max(4,max(nchar(as.character(table1[,i])))+2),40))))
        next()
      }

      if(tolower(colnames(table1)[i]) == "symbol")
      {
        Try(tkcmd(.Tk.ID(toptableTable),"width",paste(i-1),paste(min(max(4,max(nchar(as.character(table1[,i])))+2),30))))
        next()
      }

      Try(tkcmd(.Tk.ID(toptableTable),"width",paste(i-1),paste(min(max(4,max(nchar(as.character(table1[,i])))+2),40))))
    })
    Try(tkfocus(toptableTable))
  }
  else
  {
    Try(tkmessageBox(title="Large Toptable",message="Toptable is too big to display in a table widget, so it will be displayed in a text window instead.  You can save it as a tab-delimited text file and then import it into a spreadsheet program.",icon="info",type="ok"))

    write.table(table1,file="temp5317",quote=FALSE,col.names=NA,sep="\t")
    ttToptableTable <- tktoplevel(.affylmGUIglobals$ttMain)
    tkwm.title(ttToptableTable,paste("Top",numberOfGenes,"Candidate Genes for Differential Expression for",ContrastNamesVec[contrast],".",sep=" "));

    xscr <-tkscrollbar(ttToptableTable, repeatinterval=5,orient="horizontal",
                         command=function(...)tkxview(txt,...))
    scr <- tkscrollbar(ttToptableTable, repeatinterval=5,
                         command=function(...)tkyview(txt,...))
    txt <- tktext(ttToptableTable, bg="white", font="courier",xscrollcommand=function(...)tkset(xscr,...),
        yscrollcommand=function(...)tkset(scr,...),wrap="none",width=100)

    copyText2 <- function() .Tcl(paste("event","generate",.Tcl.args(.Tk.ID(txt),"<<Copy>>")))

    editPopupMenu2 <- tkmenu(txt, tearoff=FALSE)
    tkadd(editPopupMenu2, "command", label="Copy <Ctrl-C>",
    command=copyText2) # ,font=affylmGUIfontMenu

    RightClick2 <- function(x,y) # x and y are the mouse coordinates
    {
     rootx <- as.integer(tkwinfo("rootx",txt))
     rooty <- as.integer(tkwinfo("rooty",txt))
     xTxt <- as.integer(x)+rootx
     yTxt <- as.integer(y)+rooty
     .Tcl(paste("tk_popup",.Tcl.args(editPopupMenu2,xTxt,yTxt)))
    }
    tkbind(txt, "<Button-3>",RightClick2)            


    tkpack(scr, side="right", fill="y")
    tkpack(xscr, side="bottom", fill="x")
    tkpack(txt, side="left", fill="both", expand="yes")

    chn <- tclvalue(tkcmd("open", file.path(".","temp5317")))
    tkinsert(txt, "end", tclvalue(tkcmd("read", chn)))
    tkcmd("close", chn)
    tkconfigure(txt, state="disabled")
    tkmark.set(txt,"insert","0.0")
    tkfocus(txt)

    tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow")
        
  })
  
  
  SaveTopTable <- function()
  {
    Try(tmpTopTableFile <- tclvalue(tkgetSaveFile(initialfile=paste("toptable", contrast,".txt",sep=""))))
    Try(if (!nchar(tmpTopTableFile))
        return())
    Try(TopTableFile <- tmpTopTableFile)
    Try(write.table(table1,file=TopTableFile,quote=FALSE,col.names=NA,sep="\t"))
  } 
  
  Try(copyFcn <-      function() .Tcl(paste("event","generate",.Tcl.args(.Tk.ID(toptableTable),"<<Copy>>"))))
  
  topMenu2 <- tkmenu(ttToptableTable)
  tkconfigure(ttToptableTable, menu=topMenu2)
  fileMenu2 <- tkmenu(topMenu2, tearoff=FALSE)
  tkadd(fileMenu2, "command", label="Save As",
  command=SaveTopTable) # ) # ,font=affylmGUIfontMenu)
  tkadd(fileMenu2, "command", label="Close",
  command=function() tkdestroy(ttToptableTable)) # ) # ,font=affylmGUIfontMenu)
  tkadd(topMenu2, "cascade", label="File",
  menu=fileMenu2) # ,font=affylmGUIfontMenu)
  editMenu2 <- tkmenu(topMenu2, tearoff=FALSE)
  tkadd(editMenu2, "command", label="Copy <Ctrl-C>",
  command=copyFcn) # ,font=affylmGUIfontMenu)
  tkadd(topMenu2, "cascade", label="Edit",
  menu=editMenu2) # ,font=affylmGUIfontMenu)
}


GetSlideNum <- function()
{
  Try(SlideNamesVec <- get("SlideNamesVec",envir=affylmGUIenvironment))  
  Try(if (min(nchar(gsub("[^0-9]","",SlideNamesVec))==nchar(SlideNamesVec))==TRUE)
    SlideNamesVec <- paste("Slide",SlideNamesVec))  
  Try(NumSlides <- get("NumSlides",envir=affylmGUIenvironment))
  ttGetSlideNum<-tktoplevel(.affylmGUIglobals$ttMain)
  tkwm.deiconify(ttGetSlideNum)
  tkgrab.set(ttGetSlideNum)
  tkfocus(ttGetSlideNum)
  tkwm.title(ttGetSlideNum,"Please Specify Slide")
  scr <- tkscrollbar(ttGetSlideNum, repeatinterval=5,
                       command=function(...)tkyview(tl,...))
  ## Safest to make sure scr exists before setting yscrollcommand
  tl<-tklistbox(ttGetSlideNum,height=4,selectmode="browse",yscrollcommand=function(...)tkset(scr,...),background="white",font=.affylmGUIglobals$affylmGUIfont2) 
  tkgrid(tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "),
       tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "))
  lbl2<-tklabel(ttGetSlideNum,text="Choose a slide",font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(tklabel(ttGetSlideNum,text="    "),lbl2,tklabel(ttGetSlideNum,text="    "),
     tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "))
  tkgrid.configure(lbl2,sticky="w")
  tkgrid(tklabel(ttGetSlideNum,text="    "),row=2,column=0)
  tkgrid(tl,row=2,column=1,columnspan=2,rowspan=4,sticky="ew")
  tkgrid(scr,row=2,column=3,rowspan=4,sticky="wns")
  tkgrid(tklabel(ttGetSlideNum,text="    "),row=2,column=4)
  for (i in (1:NumSlides))
    tkinsert(tl,"end",SlideNamesVec[i])
  tkselection.set(tl,0)

  tkgrid(tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "),
     tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "))
  ReturnVal <- 0
  onOK <- function()
  {
      slidenum <- as.numeric(tclvalue(tkcurselection(tl)))+1
      Try(tkgrab.release(ttGetSlideNum));Try(tkdestroy(ttGetSlideNum));Try(tkfocus(.affylmGUIglobals$ttMain))
      ReturnVal <<- slidenum
  }
  onCancel <- function() {Try(tkgrab.release(ttGetSlideNum));Try(tkdestroy(ttGetSlideNum));Try(tkfocus(.affylmGUIglobals$ttMain)); ReturnVal <<- 0}      
  OK.but <-tkbutton(ttGetSlideNum,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  Cancel.but <-tkbutton(ttGetSlideNum,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(tklabel(ttGetSlideNum,text="    "),OK.but,Cancel.but,tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "))
  tkgrid.configure(OK.but,Cancel.but,sticky="w")
  tkgrid(tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "),
       tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "))
  Try(tkbind(OK.but, "<Return>",onOK))
  Try(tkbind(tl, "<Return>",onOK))    
  Try(tkbind(Cancel.but, "<Return>",onCancel))      
  Try(tkfocus(tl))
  Try(tkbind(ttGetSlideNum, "<Destroy>", function() {Try(tkgrab.release(ttGetSlideNum));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkwait.window(ttGetSlideNum))

  return (ReturnVal)
}


GetDEcutoff <- function()
{
  ttGetDEcutoff<-tktoplevel(.affylmGUIglobals$ttMain)
  tkwm.deiconify(ttGetDEcutoff)
  tkgrab.set(ttGetDEcutoff)  
  Try(tkwm.title(ttGetDEcutoff,"Cutoff for Differentially Expressed Genes"))
  Try(cutoffStatisticTcl <- tclVar("abs(t)"))
  Try(tkframe1 <- tkframe(ttGetDEcutoff,borderwidth=2))
  Try(tkframe2 <- tkframe(tkframe1,relief="groove",borderwidth=2))
  Try(tkframe4<-tkframe(tkframe1,borderwidth=2))

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

  Try(tkgrid(tklabel(tkframe2,text="Choose a cutoff for differentially expressed genes.",font=.affylmGUIglobals$affylmGUIfont2),rowspan=1,columnspan=2,sticky="w"))

  Try(tStatistic.but <- tkradiobutton(tkframe2,text="Abs(t)",variable=cutoffStatisticTcl,value="abs(t)",font=.affylmGUIglobals$affylmGUIfont2))
  Try(BStatistic.but <- tkradiobutton(tkframe2,text="B",variable=cutoffStatisticTcl,value="B",font=.affylmGUIglobals$affylmGUIfont2))

  Try(tkgrid(tStatistic.but))
  Try(tkgrid(BStatistic.but))
  Try(tkgrid.configure(tStatistic.but,BStatistic.but,sticky="w"))
  Try(tkgrid(tklabel(tkframe2,text="    ")))
  Try(cutoffValueTcl <- tclVar("0"))
  Try(entry.cutoffValue<-tkentry(tkframe2,width=30,font=.affylmGUIglobals$affylmGUIfont2,textvariable=cutoffValueTcl,bg="white"))
  Try(tkgrid(tklabel(tkframe2,text="Cutoff value ",font=.affylmGUIglobals$affylmGUIfont2),entry.cutoffValue,sticky="w"))
  
  Try(tkgrid(tkframe2))
  Try(ReturnVal <- list())
  onOK <- function()
  {
      Try(cutoffStatisticVal <- as.character(tclvalue(cutoffStatisticTcl)))
      Try(cutoffValue <- as.numeric(tclvalue(cutoffValueTcl)))
      Try(tkgrab.release(ttGetDEcutoff));Try(tkdestroy(ttGetDEcutoff));Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(ReturnVal <<- list(cutoffStatistic=cutoffStatisticVal,cutoff=cutoffValue))
  }
  onCancel <- function(){tkgrab.release(ttGetDEcutoff);tkdestroy(ttGetDEcutoff);tkfocus(.affylmGUIglobals$ttMain);ReturnVal <<- list()} 
  Try(OK.but <-tkbutton(tkframe4,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <-tkbutton(tkframe4,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(tkframe4,text="                    ")))
  Try(tkgrid(OK.but,Cancel.but))
  Try(tkgrid.configure(OK.but,sticky="e"))
  Try(tkgrid.configure(Cancel.but,sticky="e"))
  Try(tkgrid(tklabel(tkframe4,text="       ")))
  Try(tkgrid(tkframe4))
  Try(tkgrid(tkframe1))
  Try(tkfocus(ttGetDEcutoff))
  Try(tkbind(ttGetDEcutoff, "<Destroy>", function(){tkgrab.release(ttGetDEcutoff);tkfocus(.affylmGUIglobals$ttMain);} )) 
  Try(tkwait.window(ttGetDEcutoff))

  return (ReturnVal)
}

ChooseEbayesStatistic <- function()
{
  ttChooseEbayesStatistic<-tktoplevel(.affylmGUIglobals$ttMain)
  tkwm.deiconify(ttChooseEbayesStatistic)
  tkgrab.set(ttChooseEbayesStatistic)
  tkfocus(ttChooseEbayesStatistic)
  tkwm.title(ttChooseEbayesStatistic,"Empirical Bayes Statistic")   
  Try(tkgrid(tklabel(ttChooseEbayesStatistic,text="    "),tklabel(ttChooseEbayesStatistic,text="    ")))

  Try(EbayesStatisticTcl <- tclVar("t"))

  Try(tStatisticRadioButton <- tkradiobutton(ttChooseEbayesStatistic,variable=EbayesStatisticTcl,value="t"))
  Try(BStatisticRadioButton <- tkradiobutton(ttChooseEbayesStatistic,variable=EbayesStatisticTcl,value="lods"))  
  Try(PValueRadioButton     <- tkradiobutton(ttChooseEbayesStatistic,variable=EbayesStatisticTcl,value="p.value"))    
       
  Try(lbl2 <- tklabel(ttChooseEbayesStatistic,text="Please Choose an Empirical Bayes Statistic",font=.affylmGUIglobals$affylmGUIfont2))
  tkgrid(tklabel(ttChooseEbayesStatistic,text="    "),lbl2)
  Try(tkgrid.configure(lbl2,columnspan=2,sticky="w"))
  tkgrid(tklabel(ttChooseEbayesStatistic,text="    "))
  
  Try(currentLabel <- tklabel(ttChooseEbayesStatistic,text="t Statistic",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttChooseEbayesStatistic,text="    "),tStatisticRadioButton,currentLabel))
  Try(tkgrid.configure(tStatisticRadioButton,sticky="e"))
  Try(tkgrid.configure(currentLabel,sticky="w"))
  Try(currentLabel <- tklabel(ttChooseEbayesStatistic,text="B Statistic",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttChooseEbayesStatistic,text="    "),BStatisticRadioButton,currentLabel))
  Try(tkgrid.configure(BStatisticRadioButton,sticky="e"))
  Try(tkgrid.configure(currentLabel,sticky="w"))
  Try(currentLabel <- tklabel(ttChooseEbayesStatistic,text="P Value",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttChooseEbayesStatistic,text="    "),PValueRadioButton,currentLabel))
  Try(tkgrid.configure(PValueRadioButton,sticky="e"))
  Try(tkgrid.configure(currentLabel,sticky="w"))
  
  tkgrid(tklabel(ttChooseEbayesStatistic,text="    "))
  tkgrid(tklabel(ttChooseEbayesStatistic,text="    "))
  ReturnVal <- ""
  onOK <- function()
  {      
      Try(ReturnVal <- tclvalue(EbayesStatisticTcl))
      Try(tkgrab.release(ttChooseEbayesStatistic));Try(tkdestroy(ttChooseEbayesStatistic));Try(tkfocus(.affylmGUIglobals$ttMain))
      ReturnVal <<- ReturnVal
  }
  onCancel <- function() {Try(tkgrab.release(ttChooseEbayesStatistic));Try(tkdestroy(ttChooseEbayesStatistic));Try(tkfocus(.affylmGUIglobals$ttMain)); ReturnVal <<- ""}      
  OK.but <-tkbutton(ttChooseEbayesStatistic,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  Cancel.but <-tkbutton(ttChooseEbayesStatistic,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(tklabel(ttChooseEbayesStatistic,text="    "),OK.but,Cancel.but,tklabel(ttChooseEbayesStatistic,text="    "),tklabel(ttChooseEbayesStatistic,text="    "))
  tkgrid.configure(OK.but,    sticky="e")
  tkgrid.configure(Cancel.but,sticky="w")
  tkgrid(tklabel(ttChooseEbayesStatistic,text="    "),tklabel(ttChooseEbayesStatistic,text="    "),tklabel(ttChooseEbayesStatistic,text="    "),
       tklabel(ttChooseEbayesStatistic,text="    "),tklabel(ttChooseEbayesStatistic,text="    "))
  Try(tkfocus(ttChooseEbayesStatistic))
  Try(tkbind(ttChooseEbayesStatistic, "<Destroy>", function() {Try(tkgrab.release(ttChooseEbayesStatistic));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkwait.window(ttChooseEbayesStatistic))

  return (ReturnVal)

}

GetWtAreaParams <- function()
{
    ttWeightingwtArea <- tktoplevel(.affylmGUIglobals$ttMain)
    tkwm.deiconify(ttWeightingwtArea)
    tkgrab.set(ttWeightingwtArea)
    tkfocus(ttWeightingwtArea)
    tkwm.title(ttWeightingwtArea,"Good Spot Size")
    tkframe1 <- tkframe(ttWeightingwtArea)
    tkframe2 <- tkframe(tkframe1,relief="groove",borderwidth=2)
    tkframe4 <- tkframe(tkframe1)
    tkgrid(tklabel(tkframe1,text="    "))
    tkgrid(tklabel(tkframe1,text="Please enter the area range for good spots",font=.affylmGUIglobals$affylmGUIfont2),columnspan=2)
    tkgrid(tklabel(tkframe1,text="    "))
    tkgrid(tklabel(tkframe2,text="Area Range in Pixels",font=.affylmGUIglobals$affylmGUIfont2),columnspan=2)
    AreaLowerLimitTcl <- tclVar(paste(160))
    AreaUpperLimitTcl <- tclVar(paste(170))
    tkgrid(tklabel(tkframe2,text="    "))
    entry.AreaLowerLimit <-tkentry(tkframe2,width="12",font=.affylmGUIglobals$affylmGUIfont2,textvariable=AreaLowerLimitTcl,bg="white")
    entry.AreaUpperLimit <-tkentry(tkframe2,width="12",font=.affylmGUIglobals$affylmGUIfont2,textvariable=AreaUpperLimitTcl,bg="white")
    tkgrid(tklabel(tkframe2,text="Lower area limit in pixels",font=.affylmGUIglobals$affylmGUIfont2),entry.AreaLowerLimit,sticky="w")
    tkgrid(tklabel(tkframe2,text="Upper area limit in pixels",font=.affylmGUIglobals$affylmGUIfont2),entry.AreaUpperLimit,sticky="w")
    tkgrid(tkframe2)
    tkgrid(tklabel(tkframe1,text="    "))
    ReturnVal <- 0
    AreaLowerLimitVal <- 0
    AreaUpperLimitVal <- 0
    onOK <- function()
    {
        Try(AreaLowerLimitVal <<- as.integer(tclvalue(AreaLowerLimitTcl)))
        Try(AreaUpperLimitVal <<- as.integer(tclvalue(AreaUpperLimitTcl)))
        Try(assign("AreaLowerLimit",AreaLowerLimitVal,affylmGUIenvironment))
        Try(assign("AreaUpperLimit",AreaUpperLimitVal,affylmGUIenvironment))
        Try(assign("WeightingType",paste("wtarea, Ideal=(",AreaLowerLimitVal,",",AreaUpperLimitVal,")",sep=""),affylmGUIenvironment))        
        Try(tkgrab.release(ttWeightingwtArea));Try(tkdestroy(ttWeightingwtArea));Try(tkfocus(.affylmGUIglobals$ttMain))
        ReturnVal <<- 1
    }
    onCancel <- function() {Try(tkgrab.release(ttWeightingwtArea));Try(tkdestroy(ttWeightingwtArea));Try(tkfocus(.affylmGUIglobals$ttMain));ReturnVal<<-0}   
    OK.but <-tkbutton(tkframe4,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)   
    Cancel.but <-tkbutton(tkframe4,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
    tkgrid(OK.but,Cancel.but)
    tkgrid(tklabel(tkframe4,text="    "))
    tkgrid(tkframe4)
    tkgrid(tkframe1)
    Try(tkfocus(ttWeightingwtArea))
    Try(tkbind(ttWeightingwtArea, "<Destroy>", function() {Try(tkgrab.release(ttWeightingwtArea));Try(tkfocus(.affylmGUIglobals$ttMain));}))
    Try(tkwait.window(ttWeightingwtArea))

    return (ReturnVal)
}

GetWtFlagParams <- function()
{
    ttWeightingwtFlag <- tktoplevel(.affylmGUIglobals$ttMain)
    tkwm.deiconify(ttWeightingwtFlag)
    tkgrab.set(ttWeightingwtFlag)
    tkfocus(ttWeightingwtFlag)  
    tkwm.title(ttWeightingwtFlag,"Weighting for Spots with Flag Values Less Than Zero")
    tkframe1 <- tkframe(ttWeightingwtFlag)
    tkframe2 <- tkframe(tkframe1,relief="groove",borderwidth=2)
    tkframe4 <- tkframe(tkframe1)
    tkgrid(tklabel(tkframe1,text="    "))
    tkgrid(tklabel(tkframe1,text="Please enter the weighting for spots with flag values less than zero",font=.affylmGUIglobals$affylmGUIfont2),columnspan=2)
    tkgrid(tklabel(tkframe1,text="    "))
    tkgrid(tklabel(tkframe2,text="Spot Weighting",font=.affylmGUIglobals$affylmGUIfont2),columnspan=2)
    FlagSpotWeightingTcl <- tclVar(paste(0.1))
    tkgrid(tklabel(tkframe2,text="    "))
    entry.FlagSpotWeighting<-tkentry(tkframe2,width="12",font=.affylmGUIglobals$affylmGUIfont2,textvariable=FlagSpotWeightingTcl,bg="white")
    tkgrid(tklabel(tkframe2,text="Weighting (relative to 1 for all other spots)",font=.affylmGUIglobals$affylmGUIfont2),entry.FlagSpotWeighting,sticky="w")
    tkgrid(tkframe2)
    tkgrid(tklabel(tkframe1,text="    "))
    ReturnVal <- 0
    FlagSpotWeightingVal <- 0
    onOK <- function()
    {
        Try(FlagSpotWeightingVal <- as.numeric(tclvalue(FlagSpotWeightingTcl)))
        Try(tkgrab.release(ttWeightingwtFlag));Try(tkdestroy(ttWeightingwtFlag));Try(tkfocus(.affylmGUIglobals$ttMain))
        ReturnVal <<- 1
    }
    onCancel <- function() {Try(tkgrab.release(ttWeightingwtFlag));Try(tkdestroy(ttWeightingwtFlag));Try(tkfocus(.affylmGUIglobals$ttMain));ReturnVal<<-0}   
    OK.but <-tkbutton(tkframe4,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
    Cancel.but <-tkbutton(tkframe4,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
    tkgrid(OK.but,Cancel.but)
    tkgrid(tklabel(tkframe4,text="    "))
    tkgrid(tkframe4)
    tkgrid(tkframe1)
    Try(tkfocus(ttWeightingwtFlag))
    Try(tkbind(ttWeightingwtFlag, "<Destroy>", function() {Try(tkgrab.release(ttWeightingwtFlag));Try(tkfocus(.affylmGUIglobals$ttMain));}))
    Try(tkwait.window(ttWeightingwtFlag))
    
    Try(FlagSpotWeighting <- FlagSpotWeightingVal)
    Try(assign("FlagSpotWeighting", FlagSpotWeighting,affylmGUIenvironment))

    Try(assign("WeightingType",paste("wtflag, FlagSpotWeighting = ",FlagSpotWeighting,sep=""),affylmGUIenvironment))

    return (ReturnVal)
}

evalRcode <- function()
{
  Try(wfile <- "")
  Try(ttEvalRcode <- tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.title(ttEvalRcode ,"Enter R code in this window and then click on Run"))
  Try(scrCode <- tkscrollbar(ttEvalRcode , repeatinterval=5,
                         command=function(...)tkyview(txt,...)))
  Try(xscrCode <- tkscrollbar(ttEvalRcode , repeatinterval=5,orient="horizontal",
                         command=function(...)tkxview(txt,...)))
  Try(txt <- tktext(ttEvalRcode , height=20,
            yscrollcommand=function(...)tkset(scrCode,...),
            xscrollcommand=function(...)tkset(xscrCode,...),
            wrap="none",width=100,bg="white",
              font=.affylmGUIglobals$affylmGUIfontCourier))
  Try(cutText <- function() .Tcl(paste("event","generate",.Tcl.args(.Tk.ID(txt),"<<Cut>>")))    )
  Try(copyText <- function() .Tcl(paste("event","generate",.Tcl.args(.Tk.ID(txt),"<<Copy>>"))))
  Try(pasteText <- function() .Tcl(paste("event","generate",.Tcl.args(.Tk.ID(txt),"<<Paste>>")))  )

  Try(editPopupMenu <- tkmenu(txt, tearoff=FALSE))
  Try(tkadd(editPopupMenu, "command", label="Cut <Ctrl-X>",
  command=cutText)) # ) # ,font=affylmGUIfontMenu))
  Try(tkadd(editPopupMenu, "command", label="Copy <Ctrl-C>",
  command=copyText)) # ) # ,font=affylmGUIfontMenu))
  Try(tkadd(editPopupMenu, "command", label="Paste <Ctrl-V>",
  command=pasteText)) # ) # ,font=affylmGUIfontMenu))

  RightClick <- function(x,y) # x and y are the mouse coordinates
  {
   Try(rootx <- as.integer(tkwinfo("rootx",txt)))
   Try(rooty <- as.integer(tkwinfo("rooty",txt)))
   Try(xTxt <- as.integer(x)+rootx)
   Try(yTxt <- as.integer(y)+rooty)
   Try(.Tcl(paste("tk_popup",.Tcl.args(editPopupMenu,xTxt,yTxt))))
  }
  Try(tkbind(txt, "<Button-3>",RightClick))
  
  Try(tkpack(scrCode, side="right", fill="y"))
  Try(tkpack(xscrCode, side="bottom", fill="x"))
  Try(tkpack(txt, side="left", fill="both", expand="yes"))
  Try(tkfocus(txt))

  SaveRSourceFile <- function() 
  {
    Try(fileName <- tclvalue(tkgetSaveFile(initialfile=tclvalue(tkfile.tail(wfile)),initialdir=tclvalue(tkfile.dir(wfile)),
           filetypes="{{R Source Files} {.R}} {{All files} *}")))
    if (nchar(fileName)==0) return()
    Try(len <- nchar(fileName))
    if (len<=2)
      Try( fileName <- paste(fileName,".R",sep=""))
    else if (substring(fileName,len-1,len)!=".R")
      Try(fileName <- paste(fileName,".R",sep=""))
    Try(chn <- tkopen(fileName, "w"))
    Try(tkputs(chn, tclvalue(tkget(txt,"0.0","end"))))
    Try(tkclose(chn))
    Try(wfile <<- fileName)
    Try(tkfocus(txt))
  }

  OpenRSourceFile <- function() 
  {
    Try(fileName <- tclvalue(tkgetOpenFile(filetypes="{{R Source Files} {.R}} {{All files} *}")))
    if (nchar(fileName)==0) return()
    Try(chn <- tkopen(fileName, "r"))
    Try(tkinsert(txt, "0.0", tclvalue(tkread(chn))))
    Try(tkclose(chn))
    Try(wfile <<- fileName)
    Try(tkfocus(txt))
  }

  runOverall <- function(runType) {
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  Try(tkconfigure(ttEvalRcode,cursor="watch"))
  Try(tkfocus(ttEvalRcode))
  Try(code <- tclvalue(tkget(txt,"0.0","end")))
  if (runType!="runTextOnly")
  {
     Try(LocalHScale <- .affylmGUIglobals$Myhscale)
     Try(LocalVScale <- .affylmGUIglobals$Myvscale)   

    Try(ttGraph<-tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.withdraw(ttGraph))
    Try(tkwm.title(ttGraph,"Graphical Results from R Code Evaluation"))
    Try(codeGraph <- paste("assign(\"plotFunction\",function () {\nopar<-par(bg=\"white\")\nTry({\n",code,"\n})\n\ntempGraphPar <- par(opar)\n},affylmGUIenvironment)\n",sep=""))
  }

  if (runType!="runGraphicsOnly")
  {
    Try(RoutFileObject <- file("tmpEvalRcodeResults", open="wt"))
    Try(sink(RoutFileObject))
    Try(sink(RoutFileObject,type="message"))
    Try(e <- try(parse(text=code)))
    if (inherits(e, "try-error")) 
    {
      Try(tkmessageBox(message="Syntax error",icon="error"))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(sink(type="message"))
      Try(sink())
      Try(try(close(RoutFileObject),TRUE))
      return()
    }
    e2 <- try(print(eval(e,envir=affylmGUIenvironment)))
    if (inherits(e2, "try-error"))
    {
      Try(tkmessageBox(title="An error occured while trying to evaluate your R code",message=as.character(e2),icon="error"))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(sink(type="message"))
      Try(sink())
      Try(try(close(RoutFileObject),TRUE))
      return()      
    }
    Try(sink(type="message"))
    Try(sink())
    Try(try(close(RoutFileObject),TRUE))
  }

  if (runType!="runTextOnly")
  {
    Try(RoutFileObjectGraph <- file("tmpEvalRcodeResultsGraph",open="wt"))
    Try(sink(RoutFileObjectGraph))
    Try(sink(RoutFileObjectGraph,type="message"))
    Try(e3 <- try(parse(text=codeGraph)))
    if (inherits(e3, "try-error")) 
    {
      Try(tkmessageBox(message="Syntax error",icon="error"))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(sink(type="message"))
      Try(sink())
      Try(close(RoutFileObjectGraph))
      return()
    }
    e4 <- try(print(eval(e3,envir=affylmGUIenvironment)))
    if (inherits(e4, "try-error"))
    {
      Try(tkmessageBox(message="An error occured while trying to plot the graph(s) for your R code",icon="error"))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(sink(type="message"))
      Try(sink())
      Try(close(RoutFileObjectGraph))
      return()            
    }
    Try(sink(type="message"))
    Try(sink())
    Try(try(close(RoutFileObjectGraph),TRUE))
    Require("tkrplot")

    Try(plotFunction <- get("plotFunction",envir=affylmGUIenvironment))
    Try(imgaffylmGUI<-tkrplot(ttGraph,plotFunction,hscale=LocalHScale,vscale=LocalVScale))
    SetupPlotKeyBindings(tt=ttGraph,img=imgaffylmGUI)
    SetupPlotMenus(tt=ttGraph,initialfile="",plotFunction,img=imgaffylmGUI)  

    Try(tkgrid(imgaffylmGUI))
    Try(if (as.numeric(tclvalue(tkwinfo("reqheight",imgaffylmGUI)))<10)  # Nothing plotted.
      Try(tkdestroy(ttGraph))
    else
    {
      Try(tkwm.deiconify(ttGraph))
      Try(tkfocus(imgaffylmGUI))   
    })
    
    CopyToClip <- function()
    {
      Try(tkrreplot(imgaffylmGUI))
    }
  }

  if (runType!="runGraphicsOnly") 
  {
    Try(tt2 <-tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.title(tt2,"Text Results of R Code Evaluation"))
    Try(scr <- tkscrollbar(tt2, repeatinterval=5,
                         command=function(...)tkyview(txt2,...)))
    Try(xscr <- tkscrollbar(tt2, repeatinterval=5,orient="horizontal",
                           command=function(...)tkxview(txt2,...)))
    Try(txt2 <- tktext(tt2,height=20,bg="white",
    yscrollcommand=function(...)tkset(scr,...),
    xscrollcommand=function(...)tkset(xscr,...),
    wrap="none",width=100,font=.affylmGUIglobals$affylmGUIfontCourier))

    Try(copyText2 <- function() .Tcl(paste("event","generate",.Tcl.args(.Tk.ID(txt2),"<<Copy>>"))))

    Try(editPopupMenu2 <- tkmenu(txt2, tearoff=FALSE))
    Try(tkadd(editPopupMenu2, "command", label="Copy <Ctrl-C>",
    command=copyText2)) # ) # ,font=affylmGUIfontMenu))

    RightClick2 <- function(x,y) # x and y are the mouse coordinates
    {
     Try(rootx <- as.integer(tkwinfo("rootx",txt2)))
     Try(rooty <- as.integer(tkwinfo("rooty",txt2)))
     Try(xTxt <- as.integer(x)+rootx)
     Try(yTxt <- as.integer(y)+rooty)
     Try(.Tcl(paste("tk_popup",.Tcl.args(editPopupMenu2,xTxt,yTxt))))
    }
    Try(tkbind(txt2, "<Button-3>",RightClick2))

    Try(tkpack(scr, side="right", fill="y"))
    Try(tkpack(xscr, side="bottom", fill="x"))
    Try(tkpack(txt2, side="left", fill="both", expand="yes"))

    Try(chn <- tkopen("tmpEvalRcodeResults", "r"))
    Try(tkinsert(txt2, "0.0", tclvalue(tkread(chn))))
    Try(tkclose(chn))
    Try(tkfocus(tt2))
    SaveTextResults <- function()
    {
      Try(fileName<- tclvalue(tkgetSaveFile(initialfile="RcodeResults.txt",filetypes="{{Text Files} {.txt}} {{All files} *}")))
      Try(if (!nchar(fileName))        return())

      if (nchar(fileName)==0) return()
      Try(len <- nchar(fileName))
      if (len<=4)
        Try( fileName <- paste(fileName,".txt",sep=""))
      else if (substring(fileName,len-3,len)!=".txt")
      Try(fileName <- paste(fileName,".txt",sep=""))    
      Try(chn <- tkopen(fileName,"w"))
      Try(tkputs(chn, tclvalue(tkget(txt2,"0.0","end"))))
      Try(tkclose(chn))
    }

    Try(topMenu2 <- tkmenu(tt2))
    Try(tkconfigure(tt2, menu=topMenu2))
    Try(fileMenu2 <- tkmenu(topMenu2, tearoff=FALSE))
    Try(editMenu2 <- tkmenu(topMenu2, tearoff=FALSE))

    Try(tkadd(fileMenu2, "command", label="Save As",
    command=SaveTextResults)) # ) # ,font=affylmGUIfontMenu))
    Try(tkadd(fileMenu2, "command", label="Close",
    command=function() tkdestroy(tt2))) # ) # ,font=affylmGUIfontMenu))
    Try(tkadd(topMenu2, "cascade", label="File",
    menu=fileMenu2)) # ) # ,font=affylmGUIfontMenu))

    Try(tkadd(editMenu2, "command", label="Copy <Ctrl-C>",
    command=copyText2)) # ) # ,font=affylmGUIfontMenu))
    Try(tkadd(topMenu2, "cascade", label="Edit",
    menu=editMenu2)) # ) # ,font=affylmGUIfontMenu))

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

  Try(runTextOnly <- function() runOverall("runTextOnly"))
  Try(runGraphicsOnly <- function() runOverall("runGraphicsOnly"))
  Try(runTextAndGraphics <- function() runOverall("runTextAndGraphics"))

  MakeaffylmGUIMenu <- function()
  {
    Try(code <- tclvalue(tkget(txt,"0.0","end")))
    Try(codeGraph <- paste("assign(\"plotFunction\",function () {\nopar<-par(bg=\"white\")\nTry({\n",code,"\n})\n\ntempGraphPar <- par(opar)\n},affylmGUIenvironment)\n",sep=""))
    Try(menuNameObject <- GetMenuName())
    Try(if (length(menuNameObject)==0) return())    
    Try(addMenuItem(codeGraph,menuNameObject$MenuName,newMenu=TRUE,menuPosition="end",
      menuNameObject$MenuItemName,newMenuItem=TRUE,menuItemPosition="end",
            outputHasGraphics=TRUE))  
  }

  Try(HTMLhelp <- function() help.start())

  Try(topMenu <- tkmenu(ttEvalRcode ))
  Try(tkconfigure(ttEvalRcode , menu=topMenu))
  Try(fileMenu <- tkmenu(topMenu, tearoff=FALSE))
  Try(runMenu <- tkmenu(topMenu, tearoff=FALSE))
  Try(editMenu <- tkmenu(topMenu, tearoff=FALSE))
  Try(helpMenu <- tkmenu(topMenu, tearoff=FALSE))
  Try(tkadd(fileMenu, "command", label="Open",
  command=OpenRSourceFile)) 
  Try(tkadd(fileMenu, "command", label="Save As",
  command=SaveRSourceFile)) 
  Try(tkadd(fileMenu, "command", label="Close",
  command=function() tkdestroy(ttEvalRcode ))) 
  Try(tkadd(topMenu, "cascade", label="File",
  menu=fileMenu)) 
  Try(tkadd(editMenu, "command", label="Cut <Ctrl-X>",
  command=cutText))
  Try(tkadd(editMenu, "command", label="Copy <Ctrl-C>",
  command=copyText)) 
  Try(tkadd(editMenu, "command", label="Paste <Ctrl-V>",
  command=pasteText)) 
  Try(tkadd(topMenu, "cascade", label="Edit",
  menu=editMenu)) 
  Try(tkadd(runMenu,"command",label="Show Text Results only",
  command=runTextOnly)) 
  Try(tkadd(runMenu,"command",label="Show Graphical Results only",
  command=runGraphicsOnly)) 
  Try(tkadd(runMenu,"command",label="Show Text and Graphics",
  command=runTextAndGraphics)) 
  Try(tkadd(topMenu, "cascade", label="Run",
  menu=runMenu)) 
  
  Try(tkadd(helpMenu,"command",label="HTML Help",
  command=HTMLhelp)) 
  Try(tkadd(topMenu,"cascade",label="Help",
  menu=helpMenu)) 
}

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(.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(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(RawAffyData@exprs))
  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)
}



GetlimmaDataSetName <- function()
{
  Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
  Try(ttGetlimmaDataSetName<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttGetlimmaDataSetName))
  Try(tkgrab.set(ttGetlimmaDataSetName))
  Try(tkfocus(ttGetlimmaDataSetName))
  Try(tkwm.title(ttGetlimmaDataSetName,"Data Set Name"))
  Try(tkgrid(tklabel(ttGetlimmaDataSetName,text="    ")))
  if (limmaDataSetNameText=="Untitled")
      Try(limmaDataSetNameText <- "")
  Try(Local.limmaDataSetName <- tclVar(init=limmaDataSetNameText))
  Try(entry.limmaDataSetName <-tkentry(ttGetlimmaDataSetName,width="20",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.limmaDataSetName,bg="white"))
  Try(tkgrid(tklabel(ttGetlimmaDataSetName,text="Please enter a name for this data set.",font=.affylmGUIglobals$affylmGUIfont2)))
  Try(tkgrid(entry.limmaDataSetName))
  onOK <- function()
  {    
      Try(limmaDataSetNameText <- tclvalue(Local.limmaDataSetName))
      if (nchar(limmaDataSetNameText)==0)
        limmaDataSetNameText <- "Untitled"
#      Try(tkwm.title(.affylmGUIglobals$ttMain,paste("affylmGUI -",limmaDataSetNameText)))
      Try(assign("limmaDataSetNameText",limmaDataSetNameText,affylmGUIenvironment))
      Try(tclvalue(.affylmGUIglobals$limmaDataSetNameTcl) <- limmaDataSetNameText)
      Try(tkgrab.release(ttGetlimmaDataSetName));Try(tkdestroy(ttGetlimmaDataSetName));Try(tkfocus(.affylmGUIglobals$ttMain))
  }
  Try(OK.but <-tkbutton(ttGetlimmaDataSetName,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttGetlimmaDataSetName,text="    ")))
  Try(tkgrid(OK.but))
  Try(tkgrid.configure(OK.but))
  Try(tkgrid(tklabel(ttGetlimmaDataSetName,text="       ")))
  Try(tkfocus(entry.limmaDataSetName))
  Try(tkbind(entry.limmaDataSetName, "<Return>",onOK))
  Try(tkbind(ttGetlimmaDataSetName, "<Destroy>", function(){Try(tkgrab.release(ttGetlimmaDataSetName));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
  Try(tkwait.window(ttGetlimmaDataSetName))
  Try(tkfocus(.affylmGUIglobals$ttMain))
  return (1)
}

GetParameterizationName <- function()
{
  Try(ttGetParameterizationName<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttGetParameterizationName))
  Try(tkgrab.set(ttGetParameterizationName))
  Try(tkwm.title(ttGetParameterizationName,"Parameterization Name"))
  Try(tkgrid(tklabel(ttGetParameterizationName,text="    ")))
  Try(Local.ParameterizationName <- tclVar(init=""))
  Try(entry.ParameterizationName <-tkentry(ttGetParameterizationName,width="20",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.ParameterizationName,bg="white"))
  Try(tkgrid(tklabel(ttGetParameterizationName,text="Please enter a name for this parameterization.",font=.affylmGUIglobals$affylmGUIfont2),columnspan=2))
  Try(tkgrid(entry.ParameterizationName,columnspan=2))

  ReturnVal <- "GetParameterizationName.CANCEL"
  onOK <- function()
  {
      Try(ParameterizationNameText <- tclvalue(Local.ParameterizationName))
      Try(tkgrab.release(ttGetParameterizationName));Try(tkdestroy(ttGetParameterizationName));Try(tkfocus(.affylmGUIglobals$ttMain))
      ReturnVal <<- ParameterizationNameText
  }
  onCancel <- function()
  {
      Try(tkgrab.release(ttGetParameterizationName));Try(tkdestroy(ttGetParameterizationName));Try(tkfocus(.affylmGUIglobals$ttMain))
      ReturnVal <<- "GetParameterizationName.CANCEL"
  }
  Try(OK.but <-tkbutton(ttGetParameterizationName,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <-tkbutton(ttGetParameterizationName,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttGetParameterizationName,text="    ")))
  Try(tkgrid(OK.but,Cancel.but))
  Try(tkgrid.configure(OK.but,sticky="e"))
  Try(tkgrid.configure(Cancel.but,sticky="w"))
  Try(tkgrid(tklabel(ttGetParameterizationName,text="       ")))
  Try(tkfocus(entry.ParameterizationName))
  Try(tkbind(entry.ParameterizationName, "<Return>",onOK))
  Try(tkbind(ttGetParameterizationName, "<Destroy>", function(){Try(tkgrab.release(ttGetParameterizationName));Try(tkfocus(.affylmGUIglobals$ttMain));Try(return("GetParameterizationName.CANCEL"))}))
  Try(tkwait.window(ttGetParameterizationName))
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(return (ReturnVal))
}

GetContrastParameterizationName <- function()
{
  Try(ttGetContrastParameterizationName<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttGetContrastParameterizationName))
  Try(tkgrab.set(ttGetContrastParameterizationName))
  Try(tkwm.title(ttGetContrastParameterizationName,"Contrasts Name"))
  Try(tkgrid(tklabel(ttGetContrastParameterizationName,text="    ")))
  Try(Local.ContrastParameterizationName <- tclVar(init=""))
  Try(entry.ContrastParameterizationName <-tkentry(ttGetContrastParameterizationName,width="20",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.ContrastParameterizationName,bg="white"))
  Try(tkgrid(tklabel(ttGetContrastParameterizationName,text="Please enter a name for this set of contrasts.",font=.affylmGUIglobals$affylmGUIfont2),columnspan=2))
  Try(tkgrid(entry.ContrastParameterizationName,columnspan=2))

  ReturnVal <- "GetContrastParameterizationName.CANCEL"
  onOK <- function()
  {
      Try(ContrastParameterizationNameText <- tclvalue(Local.ContrastParameterizationName))
      Try(tkgrab.release(ttGetContrastParameterizationName));Try(tkdestroy(ttGetContrastParameterizationName));Try(tkfocus(.affylmGUIglobals$ttMain))
      ReturnVal <<- ContrastParameterizationNameText
  }
  onCancel <- function()
  {
      Try(tkgrab.release(ttGetContrastParameterizationName));Try(tkdestroy(ttGetContrastParameterizationName));Try(tkfocus(.affylmGUIglobals$ttMain))
      ReturnVal <<- "GetContrastParameterizationName.CANCEL"
  }
  Try(OK.but <-tkbutton(ttGetContrastParameterizationName,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <-tkbutton(ttGetContrastParameterizationName,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttGetContrastParameterizationName,text="    ")))
  Try(tkgrid(OK.but,Cancel.but))
  Try(tkgrid.configure(OK.but,sticky="e"))
  Try(tkgrid.configure(Cancel.but,sticky="w"))
  Try(tkgrid(tklabel(ttGetContrastParameterizationName,text="       ")))
  Try(tkfocus(entry.ContrastParameterizationName))
  Try(tkbind(entry.ContrastParameterizationName, "<Return>",onOK))
  Try(tkbind(ttGetContrastParameterizationName, "<Destroy>", function(){Try(tkgrab.release(ttGetContrastParameterizationName));Try(tkfocus(.affylmGUIglobals$ttMain));Try(return("GetContrastParameterizationName.CANCEL"))}))
  Try(tkwait.window(ttGetContrastParameterizationName))
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(return (ReturnVal))
}



NewLimmaFile <- function()
{
  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 ",LimmaFileName,"?",sep=""),
            icon="question",type="yesnocancel",default="yes"))
      if (tclvalue(mbVal)=="yes")
          Try(SaveLimmaFile())
      if (tclvalue(mbVal)=="cancel")
      {
          Try(tkfocus(.affylmGUIglobals$ttMain))
          return()
      }
      Try(limmaDataSetNameText <- "Untitled")
  }
#  Try(tkmessageBox(title="Working Directory",message="After clicking OK, please select a working directory.",type="ok"))
  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(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))

  Try(if (NumParameters>0)
    Try(for (i in (1:NumParameters))
      Try(tkdelete(.affylmGUIglobals$mainTree,paste("Parameters.Status.",i,sep=""))))
  else
      Try(tkdelete(.affylmGUIglobals$mainTree,"Parameters.Status.1")))
  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))
    }
  Try(initGlobals())
  Try(LimmaFileName <- get("LimmaFileName",affylmGUIenvironment))
  Try(if (LimmaFileName=="Untitled" && limmaDataSetNameText!="Untitled") LimmaFileName <- limmaDataSetNameText) # Local assignment only  
  Try(tkwm.title(.affylmGUIglobals$ttMain,paste("affylmGUI -",LimmaFileName)))
  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))
}

chooseDir <- function()
{
	Try(wd <- tclVar(getwd()))
	Try(ttChooseDir <- tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.title(ttChooseDir,"Choose working directory"))
	Try(tkwm.deiconify(ttChooseDir))
	Try(tkgrab.set(ttChooseDir))
	Try(tkgrid(tklabel(ttChooseDir,text="    ")))
	Try(label1 <- tklabel(ttChooseDir,text="Choose working directory (containing input files):",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(tclvalue(wd))) initialdir<-gsub("/","\\\\",tclvalue(wd)) else initialdir<-gsub("/","\\\\",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(ReturnVal <- "")
	Try(onOK <- function() {Try(DirChosen <- tclvalue(wd));Try(tkgrab.release(ttChooseDir));Try(tkdestroy(ttChooseDir)); Try(ReturnVal <<- DirChosen)})
	Try(onCancel <- function() {Try(tkgrab.release(ttChooseDir));Try(tkdestroy(ttChooseDir))})
	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))
	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))
	return(ReturnVal)	
}


SetWD <- function()
{
  WD <- chooseDir()
  if (!nchar(WD)) 
  {
      tkfocus(.affylmGUIglobals$ttMain)
      return()
  }
  Try(setwd(WD))
  tkfocus(.affylmGUIglobals$ttMain)
  return(WD)
}

onExit <- function()
{
  Try(limmaDataSetNameText <- get("limmaDataSetNameText",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="Exit affylmGUI",
            message=paste("Save changes to ",LimmaFileName,"?",sep=""),
            icon="question",type="yesnocancel",default="yes"))
      if (tclvalue(mbVal)=="yes")
          Try(SaveLimmaFile())
      if (tclvalue(mbVal)=="cancel")
          return()
  }
  Try(assign(".JustAskedWhetherToSave",TRUE,.GlobalEnv))
#  try(tkdestroy(.affylmGUIglobals$ttMain),silent=TRUE)
  try(tkdestroy(.affylmGUIglobals$ttMain),silent=TRUE)
}

ChooseContrastParameterization <- function()
{
  Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
  Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
  Try(if (NumContrastParameterizations==0)
  {
    Try(tkmessageBox(title="Choose Contrasts Parameterization",message="There are no contrasts parameterizations available.",type="ok",icon="error"))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    return()  
  })      
  Try(ContrastParameterizationNamesVec <- get("ContrastParameterizationNamesVec",envir=affylmGUIenvironment))
  
  ttChooseContrastParameterization<-tktoplevel(.affylmGUIglobals$ttMain)
  tkwm.deiconify(ttChooseContrastParameterization)
  tkgrab.set(ttChooseContrastParameterization)  
  tkfocus(ttChooseContrastParameterization)
  tkwm.title(ttChooseContrastParameterization,"Choose a Contrasts Parameterization")
  scr <- tkscrollbar(ttChooseContrastParameterization, repeatinterval=5,
                       command=function(...)tkyview(tl,...))
  ## Safest to make sure scr exists before setting yscrollcommand
  tl<-tklistbox(ttChooseContrastParameterization,height=4,selectmode="single",yscrollcommand=function(...)tkset(scr,...),background="white",font=.affylmGUIglobals$affylmGUIfont2)   
  lbl2<-tklabel(ttChooseContrastParameterization,text="Which contrasts parameterization is this for?",font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(tklabel(ttChooseContrastParameterization,text="       "),row=0,column=1,columnspan=1)
  tkgrid(tklabel(ttChooseContrastParameterization,text="       "),row=0,column=4,columnspan=1)
  tkgrid(lbl2,row=1,column=2,columnspan=2,rowspan=1);
  tkgrid.configure(lbl2,sticky="w")
  tkgrid(tklabel(ttChooseContrastParameterization,text="         "),row=2,column=1)
  tkgrid(tl,row=2,column=2,columnspan=2,rowspan=4,sticky="ew")
  tkgrid(scr,row=2,column=3,columnspan=1,rowspan=4,sticky="wns")
  if (NumContrastParameterizations>0)
    for (i in (1:NumContrastParameterizations))
       tkinsert(tl,"end",ContrastParameterizationNamesVec[i])
  tkselection.set(tl,0)

  ReturnVal <- 0
  onOK <- function()
  {
      Try(contrastParameterizationIndex <- as.numeric(tclvalue(tkcurselection(tl)))+1)
      Try(tkgrab.release(ttChooseContrastParameterization));Try(tkdestroy(ttChooseContrastParameterization));Try(tkfocus(.affylmGUIglobals$ttMain))
      ReturnVal <<- contrastParameterizationIndex
  }
  onCancel <- function() {Try(tkgrab.release(ttChooseContrastParameterization));Try(tkdestroy(ttChooseContrastParameterization));Try(tkfocus(.affylmGUIglobals$ttMain));ReturnVal <<- 0}
  OK.but <-tkbutton(ttChooseContrastParameterization,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  Cancel.but <-tkbutton(ttChooseContrastParameterization,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(tklabel(ttChooseContrastParameterization,text="    "))
  tkgrid(tklabel(ttChooseContrastParameterization,text="    "),tklabel(ttChooseContrastParameterization,text="    "),OK.but,Cancel.but)
  tkgrid.configure(OK.but,    sticky="e")
  tkgrid.configure(Cancel.but,sticky="w")
  
  tkgrid(tklabel(ttChooseContrastParameterization,text="    "))
  Try(tkfocus(ttChooseContrastParameterization))
  Try(tkbind(ttChooseContrastParameterization, "<Destroy>", function() {Try(tkgrab.release(ttChooseContrastParameterization));Try(tkfocus(.affylmGUIglobals$ttMain))}))
  Try(tkwait.window(ttChooseContrastParameterization))

  return (ReturnVal)
}

DeleteContrastParameterization <- function()
{
  Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
  Try(ContrastParameterizationNamesVec <- get("ContrastParameterizationNamesVec",envir=affylmGUIenvironment))
  Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
  Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
  
  Try(if (NumContrastParameterizations==0)
  {
    Try(tkmessageBox(title="Delete Contrasts Parameterization",message="There are no contrast parameterizations loaded.  Select \"Create New Parameterization\" or \"Compute Linear Model Fit\" from the \"Linear Model\" menu.",type="ok",icon="error"))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    return()  
  })  
  Try(contrastParameterizationIndex <- ChooseContrastParameterization())
  Try(if (contrastParameterizationIndex==0)    return())
  Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
  Try(ContrastParameterizationNameNode<- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
  
  Try(tkdelete(.affylmGUIglobals$ContrastParameterizationTREE,ContrastParameterizationNameNode))
  Try(ContrastParameterizationList <- deleteItemFromList(ContrastParameterizationList,
                            ContrastParameterizationNameNode))
  Try(tempVec <- c())
  Try(if (NumContrastParameterizations>0)
    Try(for (i in (1:NumContrastParameterizations))
    {
      Try(if (i!=.affylmGUIglobals$ContrastParameterizationTREEIndex)
          Try(tempVec <- c(tempVec,ContrastParameterizationTREEIndexVec[i])))
    }))
  Try(ContrastParameterizationTREEIndexVec <- tempVec)


  Try(tempVec <- c())
  Try(if (NumContrastParameterizations>0)
    Try(for (i in (1:NumContrastParameterizations))
    {
      Try(if (i!=.affylmGUIglobals$ContrastParameterizationTREEIndex)
          Try(tempVec <- c(tempVec,ContrastParameterizationNamesVec[i])))
    }))
  Try(ContrastParameterizationNamesVec <- tempVec)
  
  Try(NumContrastParameterizations <- NumContrastParameterizations - 1)        
  Try(ContrastParameterizationList[[ContrastParameterizationNameNode]]$NumContrastParameterizations <- NumContrastParameterizations)  
#  Try(if (ContrastParameterizationList[[ContrastParameterizationNameNode]]$NumContrastParameterizations==0)
#    Try(tkinsert(.affylmGUIglobals$ContrastParameterizationTREE,"0","root",paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,".1",sep=""),text="none",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(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(NumContrastsInContrastParameterization <- length(ContrastsNames))
#      Try(for (j in (1:NumContrastsInContrastParameterization))
#        Try(tkinsert(.affylmGUIglobals$ContrastParameterizationTREE,"end",ContrastParameterizationNameNode,paste("Contrasts.",contrastParameterizationIndex,".",.affylmGUIglobals$ContrastParameterizationTREEIndex,".",j,sep=""),text=ContrastsNames[j],font=.affylmGUIglobals$affylmGUIfontTree)))  
    }
  }
  else
    Try(tkinsert(.affylmGUIglobals$mainTree,"end","ContrastParameterizations","ContrastParameterizations.Status.1" ,text="None",font=.affylmGUIglobals$affylmGUIfontTree)))
  Try(assign("ContrastParameterizationList",ContrastParameterizationList,affylmGUIenvironment))
  Try(assign("ContrastParameterizationTREEIndexVec",ContrastParameterizationTREEIndexVec,affylmGUIenvironment))
  Try(assign("NumContrastParameterizations",NumContrastParameterizations,affylmGUIenvironment))
  Try(assign("ContrastParameterizationNamesVec",ContrastParameterizationNamesVec,affylmGUIenvironment))  
}


OpenLimmaFile <- function()
{
  Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
  Try(LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment))
  Try(tempLimmaFileName <- tclvalue(tkgetOpenFile(filetypes="{{Limma Files} {.lma}} {{All files} *}")))
  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 ",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(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(tkwm.title(.affylmGUIglobals$ttMain,paste("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"))  
  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(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 (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)))

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

}

SaveLimmaFile <- function()
{
  LimmaFileName <- get("LimmaFileName",envir=affylmGUIenvironment)
  if (LimmaFileName=="Untitled")
  {
    SaveAsLimmaFile()
    try(tkfocus(.affylmGUIglobals$ttMain),silent=TRUE)
    return()
  }
  # Don't give an error if main window has been destroyed.
  try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"),silent=TRUE)  
#  tkmessageBox(message="About to save Limma File! (0)")  
  Try(save(list = ls(envir=affylmGUIenvironment), file=LimmaFileName, envir=affylmGUIenvironment))  
#  tkmessageBox(message="Limma File Saved! (1)")  
  try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"),silent=TRUE)
  try(tkfocus(.affylmGUIglobals$ttMain),silent=TRUE)
#  tkmessageBox(message="Limma File Saved! (2)")    
}    

SaveAsLimmaFile <- function()
{
  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))
  # .affylmGUIglobals$ttMain may have been destroyed
  e <- try(tkfocus(.affylmGUIglobals$ttMain),silent=TRUE)
  if (!inherits(e, "try-error"))
    Try(tkwm.title(.affylmGUIglobals$ttMain,paste("affylmGUI -",LimmaFileName)))
  try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"),silent=TRUE)    
  Try(save(list = ls(envir=affylmGUIenvironment), file=LimmaFileName, envir=affylmGUIenvironment))    
  try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"),silent=TRUE)
  try(tkfocus(.affylmGUIglobals$ttMain),silent=TRUE)
}

AboutaffylmGUI <- function()
{
    Try(tkmessageBox(title="About affylmGUI",message=paste("This is affylmGUI Version ",getPackageVersion("affylmGUI"),
                              ", using limma Version ",getPackageVersion("limma"),".  The limma package was developed by Gordon Smyth and the Graphical User Interface (GUI) was developed by James Wettenhall.",sep=""),type="ok",icon="info"))
}


ChooseCDF <- function()
{  
  ttChooseCDF<-tktoplevel(.affylmGUIglobals$ttMain)
  tkwm.deiconify(ttChooseCDF)
  tkgrab.set(ttChooseCDF)  
  tkfocus(ttChooseCDF)
  tkwm.title(ttChooseCDF,"Choose a CDF")
  scr <- tkscrollbar(ttChooseCDF, repeatinterval=5,
                       command=function(...)tkyview(tl,...))
  ## Safest to make sure scr exists before setting yscrollcommand
  tl<-tklistbox(ttChooseCDF,height=4,selectmode="single",yscrollcommand=function(...)tkset(scr,...),background="white",font=.affylmGUIglobals$affylmGUIfont2)   
  lbl2<-tklabel(ttChooseCDF,text="Choose a Chip Definition File (CDF)",font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(tklabel(ttChooseCDF,text="       "),row=0,column=1,columnspan=1)
  tkgrid(tklabel(ttChooseCDF,text="       "),row=0,column=4,columnspan=1)
  tkgrid(lbl2,row=1,column=2,columnspan=2,rowspan=1);
  tkgrid.configure(lbl2,sticky="w")
  tkgrid(tklabel(ttChooseCDF,text="         "),row=2,column=1)
  tkgrid(tl,row=2,column=2,columnspan=2,rowspan=4,sticky="ew")
  tkgrid(scr,row=2,column=4,columnspan=1,rowspan=4,sticky="wns")

  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  Require("reposTools")
  Try(cdfPackages <- getReposEntry("http://www.bioconductor.org/data/cdfenvs/repos"))
  Try(cdfDataFrame <- cdfPackages@repdatadesc@repdatadesc)
  Try(len <- nrow(cdfDataFrame))
  Try(for (i in (1:len)) tkinsert(tl,"end",paste(cdfDataFrame[i,"Package"],cdfDataFrame[i,"Version"][[1]])))
  tkselection.set(tl,0)
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  
  ReturnVal <- ""
  onOK <- function()
  {
      Try(cdfIndex <- as.numeric(tclvalue(tkcurselection(tl)))+1)
      Try(tkgrab.release(ttChooseCDF));Try(tkdestroy(ttChooseCDF));Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(ReturnVal <<- cdfDataFrame[cdfIndex,"Package"])
  }
  onCancel <- function() {Try(tkgrab.release(ttChooseCDF));Try(tkdestroy(ttChooseCDF));Try(tkfocus(.affylmGUIglobals$ttMain));ReturnVal <<- ""}
  OK.but <-tkbutton(ttChooseCDF,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  Cancel.but <-tkbutton(ttChooseCDF,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(tklabel(ttChooseCDF,text="    "))
  tkgrid(tklabel(ttChooseCDF,text="    "),tklabel(ttChooseCDF,text="    "),OK.but,Cancel.but)
  tkgrid.configure(OK.but,    sticky="e")
  tkgrid.configure(Cancel.but,sticky="w")
  Try(tkbind(OK.but, "<Return>",onOK))  
  Try(tkbind(tl, "<Return>",onOK))    
  Try(tkbind(Cancel.but, "<Return>",onCancel))    
  tkgrid(tklabel(ttChooseCDF,text="    "))
  Try(tkfocus(ttChooseCDF))
  Try(tkbind(ttChooseCDF, "<Destroy>", function() {Try(tkgrab.release(ttChooseCDF));Try(tkfocus(.affylmGUIglobals$ttMain))}))
  Try(tkwait.window(ttChooseCDF))

  return (ReturnVal)
}

GetNormalizationMethod <- function()
{
  Try(tkmessageBox(title="Normalization Method",message="Currently the only method available is rma."))
}

NormalizeNow <- function()
{
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(if (ArraysLoaded==FALSE)
  {
    Try(tkmessageBox(title="Normalization",message="Error: No arrays have been loaded.",
        icon="error",default="ok"))
    return()
  })
  Require("affy")
  Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))
  
  Try(NormalizationMethod <- GetNormalizationMethod())
  Try(if (NormalizationMethod=="") return())
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(if (NormalizationMethod=="RMA")
  {
    Try(NormalizedAffyData <- rma(RawAffyData))
    Try(assign("NormMethod","RMA",affylmGUIenvironment))
  }
  else
  {
    Require("affyPLM")
    Try(Pset <- fitPLM(RawAffyData))
    Try(NormalizedAffyData <- new("exprSet"))
    Try(NormalizedAffyData@exprs <- coefs(Pset))
    Try(NormalizedAffyData@se.exprs <- se(Pset))    
    Try(NormalizedAffyData@phenoData <- phenoData(Pset))
    Try(NormalizedAffyData@description <- description(Pset))
    Try(NormalizedAffyData@annotation <- annotation(Pset))
    Try(NormalizedAffyData@notes <- notes(Pset))
    Try(assign("NormMethod","PLM",affylmGUIenvironment))    
    Try(assign("weightsPLM",Pset@weights,affylmGUIenvironment))
  })
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(assign("NormalizedAffyData.Available",TRUE,affylmGUIenvironment))
  Try(assign("NormalizedAffyData",NormalizedAffyData,affylmGUIenvironment))
  Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
  Try(if (NormalizationMethod=="RMA")
    Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Available (RMA)",font=.affylmGUIglobals$affylmGUIfontTree))    
  else
    Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Available (PLM)",font=.affylmGUIglobals$affylmGUIfontTree)))  
}

AboutNormalization <- function()
{
  Try(tkmessageBox(title="About Normalization",message="Currently the only method available is rma."))
}

GetNormalizationMethod <- function()
{
	Try(ttGetNormalizationMethod <- tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttGetNormalizationMethod))
  Try(tkgrab.set(ttGetNormalizationMethod))
  Try(tkfocus(ttGetNormalizationMethod))
  Try(tkwm.title(ttGetNormalizationMethod,"Normalization Method"))
	
	Try(tkgrid(tklabel(ttGetNormalizationMethod,text="    ")))
	Try(NormalizationMethodTcl <- tclVar("RMA"))
  Try(rb1 <- tkradiobutton(ttGetNormalizationMethod,text="RMA (Robust Multiarray Averaging)",variable=NormalizationMethodTcl,value="RMA",font=.affylmGUIglobals$affylmGUIfont2))
	Try(rb2 <- tkradiobutton(ttGetNormalizationMethod,text="Robust Probe-level Linear Model",variable=NormalizationMethodTcl,value="RPLM",font=.affylmGUIglobals$affylmGUIfont2))
	Try(tkgrid(tklabel(ttGetNormalizationMethod,text="    "),rb1))
	Try(tkgrid(tklabel(ttGetNormalizationMethod,text="    "),rb2))
	Try(tkgrid.configure(rb1,rb2,columnspan=2,sticky="w"))
	Try(tkgrid(tklabel(ttGetNormalizationMethod,text="    "),tklabel(ttGetNormalizationMethod,text="    ")))

	Try(ReturnVal <- "")
	Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGetNormalizationMethod));Try(tkdestroy(ttGetNormalizationMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})
	Try(onOK <- function() {Try(ReturnVal <<- tclvalue(NormalizationMethodTcl));Try(tkgrab.release(ttGetNormalizationMethod));Try(tkdestroy(ttGetNormalizationMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})

	Try(OK.but     <- tkbutton(ttGetNormalizationMethod,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	Try(Cancel.but <- tkbutton(ttGetNormalizationMethod,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

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

	Try(tkbind(ttGetNormalizationMethod,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetNormalizationMethod));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkbind(OK.but, "<Return>",onOK))
  Try(tkbind(Cancel.but, "<Return>",onCancel))      

	Try(tkwait.window(ttGetNormalizationMethod))

	return (ReturnVal)
}

ExportNormalizedExpressionValues <- function()
{
  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(FileName <- tclvalue(tkgetSaveFile(initialfile=paste(limmaDataSetNameText,"_exprs.txt",sep=""),filetypes="{{Tab-Delimited Text Files} {.txt}} {{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")
				Try(FileName <- paste(FileName,".txt",sep=""))
  Try(write.table(NormalizedAffyData@exprs,file=FileName,sep="\t",quote=FALSE,col.names=NA))

}

ImageArrayPlot <- function()
{
# Late Nov, 2003.  There's still the problem that tkrplot uses too much memory on my Windows machine for this
#                  type of image plot, but the Tk Img extension does not seem to be a good platform-independent
#                  solution as it is hard to install a working version in Linux, so the current solution is to
#                  ask the user whether to plot the image in a Tk window or within R.
# Nov, 2003.  The Tcl/Tk Img extension is not easy to install in Linux (doesn't seem to be compatible with the
#             latest Tcl/Tk source (8.4.x) ) so I'm going to try tkrplot again.
# Oct, 2003. Unfortunately this doesn't work using the standard tkrplot method because the images are too large.
# So it requires the Img Tcl/Tk extension.
  Try(SlideNamesVec  <- get("SlideNamesVec", envir=affylmGUIenvironment)) 
  Try(LocalHScale <- .affylmGUIglobals$Myhscale)
  Try(LocalVScale <- .affylmGUIglobals$Myvscale)   
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(RawAffyData <- get("RawAffyData", envir=affylmGUIenvironment)) 
  Try(if (ArraysLoaded==FALSE)
  {
    Try(tkmessageBox(title="Image Array Plot",message="Error: No arrays have been loaded.",
        icon="error",default="ok"))
    return()
  })
  Try(slide <- GetSlideNum())
  Try(if (slide==0) return())
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))

#  Try(jpeg(filename="temp.jpg"))
  Try(plotFunction <- function() 
  {
    Try(opar<-par(bg="white"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
    Try(image(1:ncol(RawAffyData),1:nrow(RawAffyData),log2(matrix(intensity(RawAffyData)[,slide],nrow=nrow(RawAffyData))),col=gray(c(0:64)/64),    
      main=plotTitle,xlab=xLabel,ylab=yLabel))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    Try(tmp<-par(opar))
  })
#  Try(dev.off())
#  Try(tt <- tktoplevel(.affylmGUIglobals$ttMain))
#  Try(tkwm.title(tt,paste("Image Plot for",colnames(RawAffyData@exprs)[slide])))
#  TclRequire("Img")
#  Try(image1 <- tclVar())
#  Try(tkcmd("image","create","photo",image1,file="temp.jpg"))
#  Try(img <- tklabel(tt,image=image1))
#  Try(tkpack(img))
  Try(plotTitle<-SlideNamesVec[slide])
  Try(plotLabels <- GetPlotLabels(plotTitle,"",""))
  Try(if (length(plotLabels)==0) return())
  Try(plotTitle <- plotLabels$plotTitle)
  Try(xLabel    <- plotLabels$xLabel)
  Try(yLabel    <- plotLabels$yLabel)
  
  Try(WhetherToUseTkrplot <- tclvalue(tkmessageBox(title="Where To Plot Array Image",type="yesnocancel",
    message="Plot this image in R rather than a new (Tk) window? (Requires less memory.)",icon="question")))
  Try(if (WhetherToUseTkrplot=="cancel") 
  {
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    return()
  })
  Try(if (WhetherToUseTkrplot=="yes")
    plotFunction()
  else
  {
    Require("tkrplot")  
    Try(ttGraph<-tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.withdraw(ttGraph))
    Try(tkwm.title(ttGraph,plotTitle))
    Try(imgLimmaGUI<-tkrplot(ttGraph,plotFunction,hscale=LocalHScale,vscale=LocalVScale))
    Try(tkwm.title(ttGraph,paste("Image Plot for",SlideNamesVec[slide])))
    SetupPlotKeyBindings(tt=ttGraph,img=imgLimmaGUI)
    SetupPlotMenus(tt=ttGraph,initialfile="",plotFunction,img=imgLimmaGUI)  
    Try(tkgrid(imgLimmaGUI))
    Try(if (as.numeric(tclvalue(tkwinfo("reqheight",imgLimmaGUI)))<10)  # Nothing plotted.
      Try(tkdestroy(ttGraph))
    else
    {
      Try(tkwm.deiconify(ttGraph))
      Try(tkfocus(imgLimmaGUI))   
    })

    CopyToClip <- function() Try(tkrreplot(imgLimmaGUI))  
  })
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}

GetWhichProbes <- function(includeBoth=FALSE)
{
	Try(ttGetWhichProbes <- tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttGetWhichProbes))
  Try(tkgrab.set(ttGetWhichProbes))
  Try(tkfocus(ttGetWhichProbes))
  Try(tkwm.title(ttGetWhichProbes,"Probe Set"))
	
	Try(tkgrid(tklabel(ttGetWhichProbes,text="    ")))
	Try(whichProbesTcl <- tclVar("pm"))
  Try(rb1 <- tkradiobutton(ttGetWhichProbes,text="PM probes",variable=whichProbesTcl,value="pm",font=.affylmGUIglobals$affylmGUIfont2))
	Try(rb2 <- tkradiobutton(ttGetWhichProbes,text="MM probes",variable=whichProbesTcl,value="mm",font=.affylmGUIglobals$affylmGUIfont2))
	Try(if (includeBoth==TRUE)
	  Try(rb3 <- tkradiobutton(ttGetWhichProbes,text="Both",variable=whichProbesTcl,value="both",font=.affylmGUIglobals$affylmGUIfont2)))
	Try(tkgrid(tklabel(ttGetWhichProbes,text="    "),rb1))
	Try(tkgrid(tklabel(ttGetWhichProbes,text="    "),rb2))
	Try(if (includeBoth==TRUE)	
  	Try(tkgrid(tklabel(ttGetWhichProbes,text="    "),rb3)))
  Try(if (includeBoth==TRUE)
  	Try(tkgrid.configure(rb1,rb2,rb3,columnspan=2,sticky="w"))
  else
  	Try(tkgrid.configure(rb1,rb2,columnspan=2,sticky="w")))
	Try(tkgrid(tklabel(ttGetWhichProbes,text="    "),tklabel(ttGetWhichProbes,text="    ")))

	Try(ReturnVal <- "")
	Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGetWhichProbes));Try(tkdestroy(ttGetWhichProbes));Try(tkfocus(.affylmGUIglobals$ttMain))})
	Try(onOK <- function() {Try(ReturnVal <<- tclvalue(whichProbesTcl));Try(tkgrab.release(ttGetWhichProbes));Try(tkdestroy(ttGetWhichProbes));Try(tkfocus(.affylmGUIglobals$ttMain))})

	Try(OK.but     <- tkbutton(ttGetWhichProbes,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	Try(Cancel.but <- tkbutton(ttGetWhichProbes,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

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

	Try(tkbind(ttGetWhichProbes,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetWhichProbes));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkbind(OK.but, "<Return>",onOK))
  Try(tkbind(Cancel.but, "<Return>",onCancel))      

	Try(tkwait.window(ttGetWhichProbes))

	return (ReturnVal)
}


IntensityHistogram <- function()
{
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(RawAffyData <- get("RawAffyData", envir=affylmGUIenvironment)) 
  Try(LocalHScale <- .affylmGUIglobals$Myhscale)
  Try(LocalVScale <- .affylmGUIglobals$Myvscale)   
  Try(SlideNamesVec  <- get("SlideNamesVec", envir=affylmGUIenvironment)) 
  Try(if (ArraysLoaded==FALSE)
  {
    Try(tkmessageBox(title="Intensity Histogram",message="Error: No arrays have been loaded.",icon="error",default="ok"))
    return()
  })  
  Try(slide <- GetSlideNum())
  Try(if (slide==0) return())
  
  Try(whichProbes <- GetWhichProbes())
  Try(if (whichProbes=="") return())
  
  Try(plotFunction <- function() 
  {
    Try(opar<-par(bg="white"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
    Try(if (whichProbes=="pm")
      Try(hist(log2(pm(RawAffyData[slide])),breaks=100,col="blue",main=plotTitle,xlab=xLabel,ylab=yLabel)))
    Try(if (whichProbes=="mm")
      Try(hist(log2(mm(RawAffyData[slide])),breaks=100,col="blue",main=plotTitle,xlab=xLabel,ylab=yLabel)))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    Try(tmp<-par(opar))
  })
  Try(if (whichProbes=="pm")
  {
    Try(plotTitle<-paste("PM Intensity distribution for",SlideNamesVec[slide]))
    Try(xLabel <- "log2(PM Intensity)")
  })    
  Try(if (whichProbes=="mm")
  {
    Try(plotTitle<-paste("MM Intensity distribution for",SlideNamesVec[slide]))
    Try(xLabel <- "log2(MM Intensity)")  
  })        
  Try(plotLabels <- GetPlotLabels(plotTitle,xLabel,"Frequency"))
  Try(if (length(plotLabels)==0) return())
  Try(plotTitle <- plotLabels$plotTitle)
  Try(xLabel    <- plotLabels$xLabel)
  Try(yLabel    <- plotLabels$yLabel)
  Require("tkrplot")  
  Try(ttGraph<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.withdraw(ttGraph))
  Try(tkwm.title(ttGraph,plotTitle))
  Try(imgLimmaGUI<-tkrplot(ttGraph,plotFunction,hscale=LocalHScale,vscale=LocalVScale))
  Try(tkwm.title(ttGraph,plotTitle))
  SetupPlotKeyBindings(tt=ttGraph,img=imgLimmaGUI)
  SetupPlotMenus(tt=ttGraph,initialfile="",plotFunction,img=imgLimmaGUI)  
  Try(tkgrid(imgLimmaGUI))
  Try(if (as.numeric(tclvalue(tkwinfo("reqheight",imgLimmaGUI)))<10)  # Nothing plotted.
    Try(tkdestroy(ttGraph))
  else
  {
    Try(tkwm.deiconify(ttGraph))
    Try(tkfocus(imgLimmaGUI))   
  })

  CopyToClip <- function() Try(tkrreplot(imgLimmaGUI))  
}


DensityPlot <- function()
{
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(RawAffyData <- get("RawAffyData", envir=affylmGUIenvironment)) 
  Try(LocalHScale <- .affylmGUIglobals$Myhscale)
  Try(LocalVScale <- .affylmGUIglobals$Myvscale)   
  Try(SlideNamesVec  <- get("SlideNamesVec", envir=affylmGUIenvironment)) 
  Try(if (ArraysLoaded==FALSE)
  {
    Try(tkmessageBox(title="Intensity Histogram",message="Error: No arrays have been loaded.",icon="error",default="ok"))
    return()
  })  
  Try(slide <- GetSlideNum())
  Try(if (slide==0) return())
  
  Try(whichProbes <- GetWhichProbes(includeBoth=TRUE))
  Try(if (whichProbes=="") return())
  
  Try(plotFunction <- function() 
  {
    Try(opar<-par(bg="white"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))  
    Try(plotDensity.AffyBatch(RawAffyData[slide],which=whichProbes,main=plotTitle,xlab=xLabel,ylab=yLabel))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    Try(tmp<-par(opar))
  })
  Try(yLabel <- "Density")
  Try(if (whichProbes=="both")
  {
    Try(plotTitle<-paste("Intensity distribution for",SlideNamesVec[slide]))    
    Try(xLabel <- "log2(Intensity)")
  })
  Try(if (whichProbes=="pm")
  {
    Try(plotTitle<-paste("PM Intensity distribution for",SlideNamesVec[slide]))
    Try(xLabel <- "log2(PM Intensity)")
  })    
  Try(if (whichProbes=="mm")
  {
    Try(plotTitle<-paste("MM Intensity distribution for",SlideNamesVec[slide]))
    Try(xLabel <- "log2(MM Intensity)")  
  })        
  Try(plotLabels <- GetPlotLabels(plotTitle,xLabel,"Density"))
  Try(if (length(plotLabels)==0) return())
  Try(plotTitle <- plotLabels$plotTitle)
  Try(xLabel    <- plotLabels$xLabel)
  Try(yLabel    <- plotLabels$yLabel)
  Require("tkrplot")  
  Try(ttGraph<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.withdraw(ttGraph))
  Try(tkwm.title(ttGraph,plotTitle))
  Try(imgLimmaGUI<-tkrplot(ttGraph,plotFunction,hscale=LocalHScale,vscale=LocalVScale))
  Try(tkwm.title(ttGraph,plotTitle))
  SetupPlotKeyBindings(tt=ttGraph,img=imgLimmaGUI)
  SetupPlotMenus(tt=ttGraph,initialfile="",plotFunction,img=imgLimmaGUI)  
  Try(tkgrid(imgLimmaGUI))
  Try(if (as.numeric(tclvalue(tkwinfo("reqheight",imgLimmaGUI)))<10)  # Nothing plotted.
    Try(tkdestroy(ttGraph))
  else
  {
    Try(tkwm.deiconify(ttGraph))
    Try(tkfocus(imgLimmaGUI))   
  })

  CopyToClip <- function() Try(tkrreplot(imgLimmaGUI))  
}


RawIntensityBoxPlot <- function()
{
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(RawAffyData <- get("RawAffyData", envir=affylmGUIenvironment)) 
  Try(SlideNamesVec  <- get("SlideNamesVec", envir=affylmGUIenvironment)) 
  Try(LocalHScale <- .affylmGUIglobals$Myhscale)
  Try(LocalVScale <- .affylmGUIglobals$Myvscale)   
  Try(if (ArraysLoaded==FALSE)
  {
    Try(tkmessageBox(title="Density Plot",message="Error: No arrays have been loaded.",icon="error",default="ok"))
    return()
  })  
  Try(plotFunction <- function() 
  {
    Try(opar<-par(bg="white",cex=0.7))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
    Try(boxplot(RawAffyData,col="red",las=2,names=SlideNamesVec))
    Try(title(plotTitle))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    Try(tmp<-par(opar))
  }) 
  Try(plotTitle <- "Raw intensity distribution for each array")
  Try(plotTitleList <- GetPlotTitle(plotTitle)) 
  Try(if (length(plotTitleList)==0) return())
  Try(plotTitle <- plotTitleList$plotTitle)    
  Require("tkrplot")  
  Try(ttGraph<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.withdraw(ttGraph))
  Try(tkwm.title(ttGraph,plotTitle))
  Try(imgLimmaGUI<-tkrplot(ttGraph,plotFunction,hscale=LocalHScale,vscale=LocalVScale))
  Try(tkwm.title(ttGraph,plotTitle))
  SetupPlotKeyBindings(tt=ttGraph,img=imgLimmaGUI)
  SetupPlotMenus(tt=ttGraph,initialfile="",plotFunction,img=imgLimmaGUI)  
  Try(tkgrid(imgLimmaGUI))
  Try(if (as.numeric(tclvalue(tkwinfo("reqheight",imgLimmaGUI)))<10)  # Nothing plotted.
    Try(tkdestroy(ttGraph))
  else
  {
    Try(tkwm.deiconify(ttGraph))
    Try(tkfocus(imgLimmaGUI))   
  })

  CopyToClip <- function() Try(tkrreplot(imgLimmaGUI))  
}


NormalizedIntensityBoxPlot <- function()
{
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(SlideNamesVec  <- get("SlideNamesVec", envir=affylmGUIenvironment)) 
  Try(if (ArraysLoaded==FALSE)
  {
    Try(tkmessageBox(title="Normalized Intensity Box Plot",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="Normalized Intensity Box Plot",message="An error occured while trying to normalize the data.")
    return()
  
  })
  Try(NormalizedAffyData <- get("NormalizedAffyData", envir=affylmGUIenvironment)) 
  Try(LocalHScale <- .affylmGUIglobals$Myhscale)
  Try(LocalVScale <- .affylmGUIglobals$Myvscale)   
  Try(if (ArraysLoaded==FALSE)
  {
    Try(tkmessageBox(title="Normalized Intensity Box Plot",message="Error: No arrays have been loaded.",icon="error",default="ok"))
    return()
  })  
  Try(plotFunction <- function() 
  {
    Try(opar<-par(bg="white",cex=0.7))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
    Try(boxplot(data.frame(exprs(NormalizedAffyData)),col="blue",las=2,names=SlideNamesVec))
    Try(title(plotTitle))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    Try(tmp<-par(opar))
  }) 
  Try(plotTitle<-"Normalized intensity distribution for each array")
  Try(plotTitleList <- GetPlotTitle(plotTitle)) 
  Try(if (length(plotTitleList)==0) return())
  Try(plotTitle <- plotTitleList$plotTitle)    
  Require("tkrplot")  
  Try(ttGraph<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.withdraw(ttGraph))
  Try(tkwm.title(ttGraph,plotTitle))
  Try(imgLimmaGUI<-tkrplot(ttGraph,plotFunction,hscale=LocalHScale,vscale=LocalVScale))
  Try(tkwm.title(ttGraph,plotTitle))
  SetupPlotKeyBindings(tt=ttGraph,img=imgLimmaGUI)
  SetupPlotMenus(tt=ttGraph,initialfile="",plotFunction,img=imgLimmaGUI)  
  Try(tkgrid(imgLimmaGUI))
  Try(if (as.numeric(tclvalue(tkwinfo("reqheight",imgLimmaGUI)))<10)  # Nothing plotted.
    Try(tkdestroy(ttGraph))
  else
  {
    Try(tkwm.deiconify(ttGraph))
    Try(tkfocus(imgLimmaGUI))   
  })

  CopyToClip <- function() Try(tkrreplot(imgLimmaGUI))  
}

#HeatMap <- function()
#{
#  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
#  Try(RawAffyData <- get("RawAffyData", envir=affylmGUIenvironment)) 
#  Try(NormalizedAffyData <- get("NormalizedAffyData", envir=affylmGUIenvironment)) 
#  Try(LocalHScale <- .affylmGUIglobals$Myhscale)
#  Try(LocalVScale <- .affylmGUIglobals$Myvscale)   
#  Try(if (ArraysLoaded==FALSE)
#  {
#    Try(tkmessageBox(title="Heat Map",message="Error: No arrays have been loaded.",icon="error",default="ok"))
#    return()
#  })  
#  Try(plotFunction <- function() 
#  {
#    Try(opar<-par(bg="white"))
#    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
#    Try(low  <- col2rgb("green")/256)
#    Try(high <- col2rgb("red")/256)
#    Try(ncolors<-256)
#    Try(col <- rgb(seq(low[1], high[1], len = ncolors), seq(low[2], 
#            high[2], len = ncolors), seq(low[3], high[3], len = ncolors)))
#    Try(require(mva))
#    Try(rsd <- apply(exprs(NormalizedAffyData),1,sd))
#    Try(sel <- order(rsd, decreasing = TRUE)[1:50])
#    Try(tmp <- exprs(NormalizedAffyData)[sel,])
#    Try(colnames(tmp) <- SlideNamesVec)
#    Try(heatmap(tmp,col=col))
#    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
#    Try(tmp<-par(opar))
#  })
#  Try(plotTitle<-"Heat Map")
#  Require("tkrplot")  
#  Try(ttGraph<-tktoplevel(.affylmGUIglobals$ttMain))
#  Try(tkwm.withdraw(ttGraph))
#  Try(tkwm.title(ttGraph,plotTitle))
#  Try(imgLimmaGUI<-tkrplot(ttGraph,plotFunction,hscale=LocalHScale,vscale=LocalVScale))
#  Try(tkwm.title(ttGraph,plotTitle))
#  SetupPlotKeyBindings(tt=ttGraph,img=imgLimmaGUI)
#  SetupPlotMenus(tt=ttGraph,initialfile="",plotFunction,img=imgLimmaGUI)  
#  Try(tkgrid(imgLimmaGUI))
#  Try(if (as.numeric(tclvalue(tkwinfo("reqheight",imgLimmaGUI)))<10)  # Nothing plotted.
#    Try(tkdestroy(ttGraph))
#  else
#  {
#    Try(tkwm.deiconify(ttGraph))
#    Try(tkfocus(imgLimmaGUI))   
#  })
#
#  CopyToClip <- function() Try(tkrreplot(imgLimmaGUI))  
#}


# The idea of having this function below came about from allowing customized menu items.
# Perhaps one reason it is not widely used is that the code specific to one particular 
# plotting function may include asking the user a question via dialog box, but we may
# not want this question to be asked again if they select "Copy" to clipboard or "Save"
# i.e. replot
generalPlotFunction <- function(code="",WindowTitle="")
{

  Try(plotTitle <- WindowTitle)
  Try(ttGraph<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.withdraw(ttGraph))
  Try(tkwm.title(ttGraph,plotTitle))

  Try(e1 <- try(parse(text=code)))
  if (inherits(e1, "try-error")) 
  {
    Try(tkmessageBox(message="Syntax error",icon="error"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    return()
  }
  e2 <- try(print(eval(e1,envir=affylmGUIenvironment)))
  if (inherits(e2, "try-error"))
  {
    Try(tkmessageBox(message="An error occured while trying to plot the graph(s) for your R code",icon="error"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    return()            
  }
  Require("tkrplot")

  Try(plotFunction <- get("plotFunction",envir=affylmGUIenvironment))
  Try(imgLimmaGUI<-tkrplot(ttGraph,plotFunction,hscale=1,vscale=1))
  Try(tkwm.title(ttGraph,plotTitle))
  SetupPlotKeyBindings(tt=ttGraph,img=imgLimmaGUI)
  SetupPlotMenus(tt=ttGraph,initialfile="",plotFunction,img=imgLimmaGUI)  

  Try(tkgrid(imgLimmaGUI))
  Try(if (as.numeric(tclvalue(tkwinfo("reqheight",imgLimmaGUI)))<10)  # Nothing plotted.
    Try(tkdestroy(ttGraph))
  else
  {
    Try(tkwm.deiconify(ttGraph))
    Try(tkfocus(imgLimmaGUI))   
  })

  CopyToClip <- function()
  {
    Try(tkrreplot(imgLimmaGUI))
  }
}


GetPlotLabels <- function(plottitle="",xlabel="",ylabel="")
{
  Try(ttGetPlotLabels<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttGetPlotLabels))
  Try(tkgrab.set(ttGetPlotLabels))
  Try(tkfocus(ttGetPlotLabels)  )
  Try(tkwm.title(ttGetPlotLabels,"Plot title and axis labels"))
  Try(tkgrid(tklabel(ttGetPlotLabels,text="    ")))
  Try(TitleTcl <- tclVar(init=plottitle))
  Try(entry.Title<-tkentry(ttGetPlotLabels,width="40",font=.affylmGUIglobals$affylmGUIfont2,textvariable=TitleTcl,bg="white"))
  Try(tkgrid(tklabel(ttGetPlotLabels,text="Plot Title : ",font=.affylmGUIglobals$affylmGUIfont2),entry.Title))
  Try(tkgrid(tklabel(ttGetPlotLabels,text="    ")))
  Try(xLabelTcl <- tclVar(init=xlabel))
  Try(entry.xLabel<-tkentry(ttGetPlotLabels,width="40",font=.affylmGUIglobals$affylmGUIfont2,textvariable=xLabelTcl,bg="white"))
  Try(tkgrid(tklabel(ttGetPlotLabels,text="X Axis Label : ",font=.affylmGUIglobals$affylmGUIfont2),entry.xLabel))
  Try(tkgrid(tklabel(ttGetPlotLabels,text="    ")))
  Try(yLabelTcl <- tclVar(init=ylabel))
  Try(entry.yLabel<-tkentry(ttGetPlotLabels,width="40",font=.affylmGUIglobals$affylmGUIfont2,textvariable=yLabelTcl,bg="white"))
  Try(tkgrid(tklabel(ttGetPlotLabels,text="Y Axis Label :   ",font=.affylmGUIglobals$affylmGUIfont2),entry.yLabel))
  Try(tkgrid(tklabel(ttGetPlotLabels,text="    ")))

  Try(tkgrid.configure(entry.Title,entry.xLabel,entry.yLabel,columnspan=2))
  Try(ReturnVal <- list())
  Try(onOK <- function()
  {
      Try(plotTitle <- tclvalue(TitleTcl))
      Try(xLabel <- tclvalue(xLabelTcl))
      Try(yLabel <- tclvalue(yLabelTcl))
      Try(Try(tkgrab.release(ttGetPlotLabels)))
      Try(tkdestroy(ttGetPlotLabels))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(ReturnVal <<- list(plotTitle=plotTitle,xLabel=xLabel,yLabel=yLabel))
  })
  onCancel <- function() {Try(tkgrab.release(ttGetPlotLabels));Try(tkdestroy(ttGetPlotLabels));Try(tkfocus(.affylmGUIglobals$ttMain));ReturnVal <<- list()}
  OK.but <-tkbutton(ttGetPlotLabels,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  Cancel.but <-tkbutton(ttGetPlotLabels,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
  Try(tkgrid(tklabel(ttGetPlotLabels,text="    "),OK.but,Cancel.but))
  Try(tkgrid(tklabel(ttGetPlotLabels,text="    ")))
  Try(tkbind(ttGetPlotLabels, "<Destroy>", function() {Try(tkgrab.release(ttGetPlotLabels));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkfocus(ttGetPlotLabels))
  Try(tkwait.window(ttGetPlotLabels))

  return (ReturnVal)
}

GetPlotTitle <- function(plottitle="")
{
  ttGetPlotTitle<-tktoplevel(.affylmGUIglobals$ttMain)
  tkwm.deiconify(ttGetPlotTitle)
  tkgrab.set(ttGetPlotTitle)
  tkfocus(ttGetPlotTitle)  
  tkwm.title(ttGetPlotTitle,"Plot title")
  tkgrid(tklabel(ttGetPlotTitle,text="    "))
  TitleTcl <- tclVar(init=plottitle)
  entry.Title<-tkentry(ttGetPlotTitle,width="40",font=.affylmGUIglobals$affylmGUIfont2,textvariable=TitleTcl,bg="white")
  tkgrid(tklabel(ttGetPlotTitle,text="Plot Title : ",font=.affylmGUIglobals$affylmGUIfont2),entry.Title)
  tkgrid(tklabel(ttGetPlotTitle,text="    "))

  tkgrid.configure(entry.Title,columnspan=2)
  ReturnVal <- list()
  onOK <- function()
  {
      plotTitle <- tclvalue(TitleTcl)
      Try(tkgrab.release(ttGetPlotTitle))
      Try(tkdestroy(ttGetPlotTitle))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      ReturnVal <<- list(plotTitle=plotTitle)
  }
  onCancel <- function() {Try(tkgrab.release(ttGetPlotTitle));Try(tkdestroy(ttGetPlotTitle));Try(tkfocus(.affylmGUIglobals$ttMain));ReturnVal <<- list()}
  OK.but <-tkbutton(ttGetPlotTitle,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  Cancel.but <-tkbutton(ttGetPlotTitle,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(tklabel(ttGetPlotTitle,text="    "),OK.but,Cancel.but)
  tkgrid(tklabel(ttGetPlotTitle,text="    "))
  Try(tkbind(entry.Title, "<Return>",onOK))  
  Try(tkbind(ttGetPlotTitle, "<Destroy>", function() {Try(tkgrab.release(ttGetPlotTitle));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkfocus(ttGetPlotTitle))  
  Try(tkwait.window(ttGetPlotTitle))

  return (ReturnVal)
}


GetPlotSize <- function()
{
  Try(Myhscale <- .affylmGUIglobals$Myhscale)
  Try(Myvscale <- .affylmGUIglobals$Myvscale)
  ttGetPlotSize<-tktoplevel(.affylmGUIglobals$ttMain)
  tkwm.deiconify(ttGetPlotSize)
  tkgrab.set(ttGetPlotSize)
  tkfocus(ttGetPlotSize)  
  tkwm.title(ttGetPlotSize,"Plot size")
  tkgrid(tklabel(ttGetPlotSize,text="    "))
  tkgrid(tklabel(ttGetPlotSize,text="If desired, you may adjust the horizontal and vertical size of the plot.",font=.affylmGUIglobals$affylmGUIfont2),columnspan=2)
  tkgrid(tklabel(ttGetPlotSize,text="    "))
  HScaleTcl <- tclVar(paste(Myhscale))
  entry.HScale<-tkentry(ttGetPlotSize,width="20",font=.affylmGUIglobals$affylmGUIfont2,textvariable=HScaleTcl,bg="white")
  tkgrid(tklabel(ttGetPlotSize,text="Horizontal Scaling Factor : ",font=.affylmGUIglobals$affylmGUIfont2),entry.HScale,sticky="w")
  tkgrid(tklabel(ttGetPlotSize,text="    "))
  VScaleTcl <- tclVar(paste(Myvscale))
  entry.VScale<-tkentry(ttGetPlotSize,width="20",font=.affylmGUIglobals$affylmGUIfont2,textvariable=VScaleTcl,bg="white")
  tkgrid(tklabel(ttGetPlotSize,text="Vertical Scaling Factor :   ",font=.affylmGUIglobals$affylmGUIfont2),entry.VScale,sticky="w")
  tkgrid(tklabel(ttGetPlotSize,text="    "))
  ReturnVal <- 0
  HScale <- 0
  VScale <- 0
  onOK <- function()
  {
      HScale <<- as.numeric(tclvalue(HScaleTcl))
      VScale <<- as.numeric(tclvalue(VScaleTcl))
      Try(tkgrab.release(ttGetPlotSize))
      Try(tkdestroy(ttGetPlotSize))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      ReturnVal <<- list(HScale=HScale,VScale=VScale)
  }
  onCancel <- function() {Try(tkgrab.release(ttGetPlotSize));Try(tkdestroy(ttGetPlotSize));Try(tkfocus(.affylmGUIglobals$ttMain));ReturnVal <<- list()}
  OK.but <-tkbutton(ttGetPlotSize,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  Cancel.but <-tkbutton(ttGetPlotSize,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(OK.but,Cancel.but)
  tkgrid(tklabel(ttGetPlotSize,text="    "))
  Try(tkfocus(ttGetPlotSize))
  Try(tkbind(ttGetPlotSize, "<Destroy>", function() {Try(tkgrab.release(ttGetPlotSize));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkbind(entry.HScale, "<Return>",function() tkfocus(entry.VScale))) 
  Try(tkbind(entry.VScale, "<Return>", onOK))
  Try(tkwait.window(ttGetPlotSize))

  return (ReturnVal)
}

SaveGraphAsJpeg <- function(initialfile,plotFunction)
{
  Try(jpegFileName <- tclvalue(tkgetSaveFile(initialfile=initialfile,filetypes="{{JPEG Files} {.jpg .jpeg}} {{All files} *}"))  )
  if (!nchar(jpegFileName)) 
    return()
  Try(len <- nchar(jpegFileName))
  if (len<4)
      Try(jpegFileName <- paste(jpegFileName,".jpg",sep=""))
  else if   ((tolower(substring(jpegFileName,len-3,len))!=".jpg") &&
  (len<5 || (tolower(substring(jpegFileName,len-4,len))!=".jpeg")))
        Try(jpegFileName <- paste(jpegFileName,".jpg",sep=""))

  Try(if (exists("X11", env=.GlobalEnv) && Sys.info()["sysname"] != "Windows" && Sys.info()["sysname"] != "Darwin")  
  {
    Try(jpegParams <- GetJpegOrPngX11Params(graphFileType="JPEG"))  
    Try(bitmap(file=jpegFileName,bg=jpegParams$bg,res=jpegParams$res,type="jpeg"))
  }
  else
  {
    Try(jpegParams <- GetJpegOrPngParams(graphFileType="JPEG"))
    if (length(jpegParams)==0) return()
    Try(jpeg(file=jpegFileName,width=jpegParams$width,height=jpegParams$height,pointsize=jpegParams$pointsize,bg=jpegParams$bg))
  })
  Try(plotFunction())
  Try(dev.off())
}

SaveGraphAsPNG <- function(initialfile,plotFunction)
{
  Try(pngFileName <- tclvalue(tkgetSaveFile(initialfile=initialfile,filetypes="{{PNG Files} {.png}} {{All files} *}"))  )
  if (!nchar(pngFileName)) 
    return()
  Try(len <- nchar(pngFileName))
  if (len<4)
      Try(pngFileName <- paste(pngFileName,".png",sep=""))
  else if   ((tolower(substring(pngFileName,len-3,len))!=".png"))
        Try(pngFileName <- paste(pngFileName,".png",sep=""))

  Try(if (exists("X11", env=.GlobalEnv) && Sys.info()["sysname"] != "Windows" && Sys.info()["sysname"] != "Darwin")  
  {
    Try(pngParams <- GetJpegOrPngX11Params(graphFileType="PNG"))  
    Try(bitmap(file=pngFileName,bg=pngParams$bg,res=pngParams$res))
  }
  else
  {
    Try(pngParams <- GetJpegOrPngParams(graphFileType="PNG"))
    if (length(pngParams)==0) return()
    Try(png(file=pngFileName,width=pngParams$width,height=pngParams$height,pointsize=pngParams$pointsize,bg=pngParams$bg))
  })
  Try(plotFunction())
  Try(dev.off())
}

SaveGraphAsPostscript <- function(initialfile,plotFunction)
{
  Try(psFileName <- tclvalue(tkgetSaveFile(initialfile=initialfile,filetypes="{{Postscript Files} {.ps .eps}} {{All files} *}"))  )
  if (!nchar(psFileName)) 
    return()
  Try(len <- nchar(psFileName))
  if (len<2)
      Try(psFileName <- paste(psFileName,".ps",sep=""))
  else if   ((tolower(substring(psFileName,len-2,len))!=".ps"))
        Try(psFileName <- paste(psFileName,".ps",sep=""))

  Try(postscript(file=psFileName,title=substring(psFileName,1,nchar(psFileName)-3)))
  Try(plotFunction())
  Try(dev.off())
}

SaveGraphAsPDF <- function(initialfile,plotFunction)
{
  Try(pdfFileName <- tclvalue(tkgetSaveFile(initialfile=initialfile,filetypes="{{PDF Files} {.pdf}} {{All files} *}"))  )
  if (!nchar(pdfFileName)) 
    return()
  Try(len <- nchar(pdfFileName))
  if (len<2)
      Try(pdfFileName <- paste(pdfFileName,".pdf",sep=""))
  else if   ((tolower(substring(pdfFileName,len-3,len))!=".pdf"))
        Try(pdfFileName <- paste(pdfFileName,".pdf",sep=""))

  Try(pdf(file=pdfFileName,title=substring(pdfFileName,1,nchar(pdfFileName)-4)))
  Try(plotFunction())
  Try(dev.off())
}


Resize <- function(img,plotFunction)
{
  Try(PlotSize <- GetPlotSize())
  Try(if (length(PlotSize)==0)      return())
  Try(LocalHScale <<- PlotSize$HScale)
  Try(LocalVScale <<- PlotSize$VScale)
  Try(tkconfigure(img,cursor="watch"))    
  Try(tkfocus(img))  
  Try(tkrreplot(img,fun=plotFunction,hscale=LocalHScale,vscale=LocalVScale))
  Try(tkconfigure(img,cursor="arrow"))        
}

CopyGraph <- function(img) Try(tkrreplot(img))  

SetupPlotKeyBindings <- function(tt,img)
{
  Try(tkbind(tt, "<Control-C>", function() CopyGraph(img)))  
  Try(tkbind(tt, "<Control-c>", function() CopyGraph(img)))  
}  

SetupPlotMenus <- function(tt,initialfile,plotFunction,img)
{
  Try(topMenu <- tkmenu(tt))
  Try(tkconfigure(tt, menu=topMenu))
  Try(fileMenu <- tkmenu(topMenu, tearoff=FALSE))
  Try(editMenu <- tkmenu(topMenu, tearoff=FALSE))
  Try(resizeMenu <- tkmenu(topMenu, tearoff=FALSE))  

  Try(tkadd(fileMenu, "command", label="Save As PNG",command=function() SaveGraphAsPNG(initialfile=initialfile,plotFunction=plotFunction))) # ) # ,font=limmaGUIfontMenu))
  Try(tkadd(fileMenu, "command", label="Save As JPEG",command=function() SaveGraphAsJpeg(initialfile=initialfile,plotFunction=plotFunction))) # ) # ,font=limmaGUIfontMenu))  
  Try(tkadd(fileMenu, "command", label="Save As Postscript",command=function() SaveGraphAsPostscript(initialfile=initialfile,plotFunction=plotFunction))) # ) # ,font=limmaGUIfontMenu))
  Try(tkadd(fileMenu, "command", label="Save As PDF",command=function() SaveGraphAsPDF(initialfile=initialfile,plotFunction=plotFunction))) # ) # ,font=limmaGUIfontMenu))    
  Try(tkadd(fileMenu, "separator"))
  Try(tkadd(fileMenu, "command", label="Close",command=function() tkdestroy(tt))) # ) # ,font=limmaGUIfontMenu))
  Try(tkadd(topMenu, "cascade", label="File",menu=fileMenu)) # ) # ,font=limmaGUIfontMenu))

  Try(tkadd(editMenu, "command", label="Copy <Ctrl-C>",command=function() CopyGraph(img=img))) # ) # ,font=limmaGUIfontMenu))
  Try(tkadd(topMenu, "cascade", label="Edit", menu=editMenu)) # ) # ,font=limmaGUIfontMenu))

  Try(tkadd(resizeMenu, "command", label="Resize Window",command=function() Resize(img=img,plotFunction=plotFunction))) # ) # ,font=limmaGUIfontMenu))
  Try(tkadd(topMenu, "cascade", label="Resize", menu=resizeMenu)) # ) # ,font=limmaGUIfontMenu))
  return (list(topMenu=topMenu,fileMenu=fileMenu,editMenu=editMenu,resizeMenu=resizeMenu))
}

GetJpegOrPngParams <- function(graphFileType)
{
  ttGetJpegOrPngParams<-tktoplevel(.affylmGUIglobals$ttMain)
  tkwm.deiconify(ttGetJpegOrPngParams)
  tkgrab.set(ttGetJpegOrPngParams)
  tkfocus(ttGetJpegOrPngParams)  
  tkwm.title(ttGetJpegOrPngParams,paste(graphFileType,"Image Parameters"))
  tkgrid(tklabel(ttGetJpegOrPngParams,text="    "))
  tkgrid(tklabel(ttGetJpegOrPngParams,text=paste(graphFileType,"Image Parameters"),font=.affylmGUIglobals$affylmGUIfont2),columnspan=2)
  tkgrid(tklabel(ttGetJpegOrPngParams,text="    "))
  WidthTcl <- tclVar(paste(600))
  entry.Width<-tkentry(ttGetJpegOrPngParams,width="10",font=.affylmGUIglobals$affylmGUIfont2,textvariable=WidthTcl,bg="white")
  tkgrid(tklabel(ttGetJpegOrPngParams,text="Width   ",font=.affylmGUIglobals$affylmGUIfont2),entry.Width,tklabel(ttGetJpegOrPngParams,text="    "),sticky="w")
  tkgrid(tklabel(ttGetJpegOrPngParams,text="    "))
  HeightTcl <- tclVar(paste(600))
  entry.Height<-tkentry(ttGetJpegOrPngParams,width="10",font=.affylmGUIglobals$affylmGUIfont2,textvariable=HeightTcl,bg="white")
  tkgrid(tklabel(ttGetJpegOrPngParams,text="Height    ",font=.affylmGUIglobals$affylmGUIfont2),entry.Height,tklabel(ttGetJpegOrPngParams,text="    "),sticky="w")
  tkgrid(tklabel(ttGetJpegOrPngParams,text="    "))
  BackgroundTcl <- tclVar("white")
  entry.Background<-tkentry(ttGetJpegOrPngParams,width="10",font=.affylmGUIglobals$affylmGUIfont2,textvariable=BackgroundTcl,bg="white")
  tkgrid(tklabel(ttGetJpegOrPngParams,text="Background    ",font=.affylmGUIglobals$affylmGUIfont2),entry.Background,tklabel(ttGetJpegOrPngParams,text="    "),sticky="w")
  tkgrid(tklabel(ttGetJpegOrPngParams,text="    "))
  PointSizeTcl <- tclVar(paste(12))
  entry.PointSize<-tkentry(ttGetJpegOrPngParams,width="10",font=.affylmGUIglobals$affylmGUIfont2,textvariable=PointSizeTcl,bg="white")
  tkgrid(tklabel(ttGetJpegOrPngParams,text="Font Size    ",font=.affylmGUIglobals$affylmGUIfont2),entry.PointSize,tklabel(ttGetJpegOrPngParams,text="    "),sticky="w")
  tkgrid(tklabel(ttGetJpegOrPngParams,text="    "))
    
  ReturnVal <- list()
  Width <- 600
  Height <- 600
  Background <- "white"
  PointSize <- 12
  
  onOK <- function()
  {
      Try(Width  <<- as.numeric(tclvalue(WidthTcl)))
      Try(Height <<- as.numeric(tclvalue(HeightTcl)))
      Try(Background <<- tclvalue(BackgroundTcl))
      Try(PointSize <<- as.numeric(tclvalue(PointSizeTcl)))      
      Try(tkgrab.release(ttGetJpegOrPngParams))
      Try(tkdestroy(ttGetJpegOrPngParams))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(ReturnVal <<- list(width=Width,height=Height,pointsize=PointSize,bg=Background))
  }
  onCancel <- function() {Try(tkgrab.release(ttGetJpegOrPngParams));Try(tkdestroy(ttGetJpegOrPngParams));Try(tkfocus(.affylmGUIglobals$ttMain));Try(ReturnVal <<- list())}
  OK.but <-tkbutton(ttGetJpegOrPngParams,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  Cancel.but <-tkbutton(ttGetJpegOrPngParams,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(OK.but,Cancel.but)
  tkgrid(tklabel(ttGetJpegOrPngParams,text="    "))
  Try(tkfocus(ttGetJpegOrPngParams))
  Try(tkbind(ttGetJpegOrPngParams, "<Destroy>", function() {Try(tkgrab.release(ttGetJpegOrPngParams));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkwait.window(ttGetJpegOrPngParams))

  return (ReturnVal)
}

GetJpegOrPngX11Params <- function(graphFileType)
{
  ttGetJpegOrPngX11Params<-tktoplevel(.affylmGUIglobals$ttMain)
  tkwm.deiconify(ttGetJpegOrPngX11Params)
  tkgrab.set(ttGetJpegOrPngX11Params)
  tkfocus(ttGetJpegOrPngX11Params)  
  tkwm.title(ttGetJpegOrPngX11Params,paste(graphFileType,"Image Parameters"))
  tkgrid(tklabel(ttGetJpegOrPngX11Params,text="    "))
  tkgrid(tklabel(ttGetJpegOrPngX11Params,text=paste(graphFileType,"Image Parameters"),font=.affylmGUIglobals$affylmGUIfont2),columnspan=2)
  tkgrid(tklabel(ttGetJpegOrPngX11Params,text="    "))
  BackgroundTcl <- tclVar("white")
  entry.Background<-tkentry(ttGetJpegOrPngX11Params,width="20",font=.affylmGUIglobals$affylmGUIfont2,textvariable=BackgroundTcl,bg="white")
  tkgrid(tklabel(ttGetJpegOrPngX11Params,text="Background    ",font=.affylmGUIglobals$affylmGUIfont2),entry.Background,sticky="w")
  tkgrid(tklabel(ttGetJpegOrPngX11Params,text="    "))
  ResolutionTcl <- tclVar("72")
  entry.Resolution<-tkentry(ttGetJpegOrPngX11Params,width="20",font=.affylmGUIglobals$affylmGUIfont2,textvariable=ResolutionTcl,bg="white")
  tkgrid(tklabel(ttGetJpegOrPngX11Params,text="Resolution    ",font=.affylmGUIglobals$affylmGUIfont2),entry.Resolution,sticky="w")
  tkgrid(tklabel(ttGetJpegOrPngX11Params,text="    "))
    
  ReturnVal <- list()
  Background <- "white"
  Resolution <- 72
  
  onOK <- function()
  {
      Try(Background <<- tclvalue(BackgroundTcl))
      Try(Resolution <<- as.numeric(tclvalue(ResolutionTcl)))
      Try(tkgrab.release(ttGetJpegOrPngX11Params))
      Try(tkdestroy(ttGetJpegOrPngX11Params))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(ReturnVal <<- list(bg=Background,res=Resolution))
  }
  onCancel <- function() {Try(tkgrab.release(ttGetJpegOrPngX11Params));Try(tkdestroy(ttGetJpegOrPngX11Params));Try(tkfocus(.affylmGUIglobals$ttMain));Try(ReturnVal <<- list())}
  OK.but <-tkbutton(ttGetJpegOrPngX11Params,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  Cancel.but <-tkbutton(ttGetJpegOrPngX11Params,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(OK.but,Cancel.but)
  tkgrid(tklabel(ttGetJpegOrPngX11Params,text="    "))
  Try(tkfocus(ttGetJpegOrPngX11Params))
  Try(tkbind(ttGetJpegOrPngX11Params, "<Destroy>", function() {Try(tkgrab.release(ttGetJpegOrPngX11Params));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkwait.window(ttGetJpegOrPngX11Params))

  return (ReturnVal)
}

VennDiagramPlot <- function()
{
  Try(limmaDataSetNameText <-  get("limmaDataSetNameText",envir=affylmGUIenvironment))
  Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
  Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
  Try(ContrastParameterizationNamesVec <- get("ContrastParameterizationNamesVec",envir=affylmGUIenvironment))  
  Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))    
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(design <- get("design", envir=affylmGUIenvironment))
  
  Try(if (ArraysLoaded==FALSE)
  {
      tkmessageBox(title="Venn Diagram",message="No arrays have been loaded.  Please try New or Open from the File menu.",type="ok",icon="error")
      Try(tkfocus(.affylmGUIglobals$ttMain))
      return()
  })

  Try(if (NumContrastParameterizations==0)
  {
    Try(tkmessageBox(title="Venn Diagram",message="There are no contrast parameterizations available.  Select \"Compute Contrasts\" from the \"Linear Model\" menu.",type="ok",icon="error"))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    return()  
  })  

  Try(contrastParameterizationIndex <- ChooseContrastParameterization())
  Try(if (contrastParameterizationIndex==0)    return())
  Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
  Try(ContrastNamesVec  <- colnames(as.matrix(ContrastParameterizationList[[contrastParameterizationIndex]]$contrastsMatrixInList$contrasts)))
  Try(ContrastParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))
    
  Try(fit <- (ContrastParameterizationList[[ContrastParameterizationNameNode]])$fit)

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

  Try(if (ebayesAvailable==FALSE)
  {
    Try(tkmessageBox(title="Venn diagram",message="For now, Venn diagrams are only available when empirical bayes statistics are available (requires replicate arrays).",icon="error"))
    return()
  })

#  Try(eb  <- (ContrastParameterizationList[[ContrastParameterizationNameNode]])$eb)
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch")) 
  Try(fit <- eBayes(fit))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))  
  
  Try(Contrasts <- GetMultipleContrasts(contrastParameterizationIndex))
  Try(NumContrastsSelected <- length(Contrasts$contrastIndices))
  Try(if (NumContrastsSelected==0)
    return())

  Try(include <- UpDownOrBoth())
  Try(if (include=="")
    return())

  Try(contrastsMatrix <- c())
  Try(tstats <- c())
  
  Try(NumParameters <- get("NumParameters" , envir=affylmGUIenvironment))      

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

  Try(for (i in (1:NumContrastsSelected))
  {
    Try(currentIndex <- Contrasts$contrastIndices[[i]])
    Try(tstat <- as.matrix((ContrastParameterizationList[[ContrastParameterizationNameNode]])$eb$t))
    Try(if (ncol(tstat)>1)
      tstat <- tstat[,currentIndex])

    Try(contrastsMatrix <- cbind(contrastsMatrix,as.matrix(rep(0,NumParameters))))
    Try(contrastsMatrix[currentIndex,ncol(contrastsMatrix)] <- 1)
    Try(ContrastName <- ContrastNamesVec[currentIndex])
    
    Try(if (length(tstats)==0) 
      Try(tstats <- as.matrix(tstat))
    else
    {
      Try(tstats <- cbind(tstats,  as.matrix(tstat)))
    })
    Try(colnames(tstats)[ncol(tstats)] <- ContrastName)
  })

  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow")) 
    
  plotVennDiagram <- function()
  {
    Try(opar<-par(bg="white"))
    Try(vennDiagramlimmaGUI(vc,include=include,names=as.vector(setNames),cex=0.85,mar=rep(1,4)))
    Try(TempGraphPar<-par(opar))
  }
  
  Try(LocalHScale <- .affylmGUIglobals$Myhscale*1.25)
  Try(LocalVScale <- .affylmGUIglobals$Myvscale*1.25)

  # FIXME: It'd be nice to list the one, two or three parameters.
  Try(plotTitle <- paste("Venn diagram for contrast parameterization",ContrastParameterizationNamesVec[contrastParameterizationIndex]))

  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch")) 
  Try(clas <- classifyTestsF(tstats,design=design,contrasts=contrastsMatrix))
  Try(vc   <- vennCounts(clas,include=include))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow")) 

  Try(if (NumContrastsSelected==1)
    Try(setNames <- GetSetNames(numSets=1,set1=colnames(vc)[1])))
  Try(if (NumContrastsSelected==2)
    Try(setNames <- GetSetNames(numSets=2,set1=colnames(vc)[1],set2=colnames(vc)[2])))
  Try(if (NumContrastsSelected==3)
    Try(setNames <- GetSetNames(numSets=3,set1=colnames(vc)[1],set2=colnames(vc)[2],set3=colnames(vc)[3])))

  Try(if (length(setNames)==0) return())

  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch")) 
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(ttVennDiagramPlot <- tktoplevel(.affylmGUIglobals$ttMain))  
  Try(tkwm.title(ttVennDiagramPlot,plotTitle))
  Try(Require("tkrplot"))
  Try(img <- tkrplot(ttVennDiagramPlot,plotVennDiagram,hscale=LocalHScale,vscale=LocalVScale))
  Try(SetupPlotKeyBindings(tt=ttVennDiagramPlot,img=img))
  Try(SetupPlotMenus(tt=ttVennDiagramPlot,initialfile=paste(limmaDataSetNameText,"VennDiagram",sep=""),
                 plotFunction=plotVennDiagram,img=img))
  
  Try(tkgrid(img))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow")) 

  Try(if (as.numeric(tclvalue(tkwinfo("reqheight",img)))<10)  # Nothing plotted.
    Try(tkdestroy(ttVennDiagramPlot))
  else  
    Try(tkfocus(ttVennDiagramPlot)))  
}


UpDownOrBoth <- function()
{
  Try(ttUpDownOrBoth <- tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.title(ttUpDownOrBoth,"D.E. Genes to Include in Venn Diagram"))
  Try(tkwm.deiconify(ttUpDownOrBoth))
  Try(tkgrab.set(ttUpDownOrBoth))
  Try(tkfocus(ttUpDownOrBoth))
  Try(tkgrid(tklabel(ttUpDownOrBoth,text="    ")))
  Try(tkgrid(tklabel(ttUpDownOrBoth,text="    "),tklabel(ttUpDownOrBoth,text="Which differentially expressed genes should be",font=.affylmGUIglobals$affylmGUIfont2),tklabel(ttUpDownOrBoth,text="    ")))
  Try(tkgrid(tklabel(ttUpDownOrBoth,text="    "),tklabel(ttUpDownOrBoth,text="included in the Venn diagram?",font=.affylmGUIglobals$affylmGUIfont2),tklabel(ttUpDownOrBoth,text="    ")))
  Try(tkgrid(tklabel(ttUpDownOrBoth,text="    ")))
  Try(UpDownOrBothTcl <- tclVar("both"))
  Try(frame1 <- tkframe(ttUpDownOrBoth,relief="groove",borderwidth="2"))
  Try(tkgrid(tkradiobutton(frame1,text="Up-regulated genes",variable=UpDownOrBothTcl,value="up",font=.affylmGUIglobals$affylmGUIfont2),sticky="w"))
  Try(tkgrid(tkradiobutton(frame1,text="Down-regulated genes",variable=UpDownOrBothTcl,value="down",font=.affylmGUIglobals$affylmGUIfont2),sticky="w"))
  Try(tkgrid(tkradiobutton(frame1,text="Both",variable=UpDownOrBothTcl,value="both",font=.affylmGUIglobals$affylmGUIfont2),sticky="w"))
  Try(tkgrid(tklabel(ttUpDownOrBoth,text="    "),frame1))
  Try(tkgrid(tklabel(ttUpDownOrBoth,text="    ")))
  Try(tkframeOKCancel <- tkframe(ttUpDownOrBoth))
  Try(ReturnVal <- "")
  Try(onOK <- function() { Try(ReturnVal <<- tclvalue(UpDownOrBothTcl)); Try(tkdestroy(ttUpDownOrBoth));Try(tkfocus(.affylmGUIglobals$ttMain))})
  Try(onCancel <- function() { Try(tkdestroy(ttUpDownOrBoth));Try(ReturnVal <- "")})
  Try(OK.but     <- tkbutton(tkframeOKCancel,text="   OK   ",command=onOK,    font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <- tkbutton(tkframeOKCancel,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(tkframeOKCancel,text="    "),columnspan=2))
  Try(tkgrid(OK.but,Cancel.but))
  Try(tkgrid.configure(OK.but,sticky="e"))
  Try(tkgrid.configure(Cancel.but,sticky="w"))  
  Try(tkgrid(tklabel(tkframeOKCancel,text="    "),columnspan=2))
  Try(tkgrid(tklabel(ttUpDownOrBoth,text="    "),tkframeOKCancel))
  
  Try(tkbind(ttUpDownOrBoth, "<Destroy>", function() {Try(tkgrab.release(ttUpDownOrBoth));Try(tkfocus(.affylmGUIglobals$ttMain))}))
  Try(tkwait.window(ttUpDownOrBoth))  
  
  return (ReturnVal)
}


vennDiagramlimmaGUI <- function(object,include="both",names,cex=1.5,mar=rep(1,4),...) {
# Plot Venn diagram
# Gordon Smyth and James Wettenhall
# 4 July 2003.  Last modified 23 September 2003.

  if(class(object) != "VennCounts") object <- vennCounts(object,include=include)
  nsets <- ncol(object)-1
  if(nsets > 3) stop("Can't plot Venn diagram for more than 3 sets")
  if(missing(names)) names <- colnames(object)[1:nsets]
  counts <- object[,"Counts"]
  theta <- 2*pi*(1:360)/360
  xcentres <- list(0,c(-1,1),c(-1,1,0))[[nsets]]
  ycentres <- list(0,c(0,0),c(1/sqrt(3),1/sqrt(3),-2/sqrt(3)))[[nsets]]
  r <- c(1.5,1.5,1.5)[nsets]
  xtext <- list(-1.2,c(-1.2,1.2),c(-1.2,1.2,0))[[nsets]]
  ytext <- list(1.8,c(1.8,1.8),c(2.4,2.4,-3))[[nsets]]
  opar <- par(mar=mar)
  plot(x=0,y=0,type="n",xlim=c(-4,4),ylim=c(-4,4),xlab="",ylab="",axes=FALSE,...)
  for(circle in 1:nsets) {
    lines(xcentres[circle]+r*cos(theta),ycentres[circle]+r*sin(theta))
    text(xtext[circle],ytext[circle],names[circle],cex=cex)
  }
  switch(nsets,
    {
      rect(-3,-2.5,3,2.5)
      text(2.3,-2.1,counts[1],cex=cex)
      text(0,0,counts[2],cex=cex)
    }, {
      rect(-3,-2.5,3,2.5)
        text(2.3,-2.1,counts[1],cex=cex)
      text(1.5,0.1,counts[2],cex=cex)
      text(-1.5,0.1,counts[3],cex=cex)
      text(0,0.1,counts[4],cex=cex)
    }, {
      rect(-3,-3.5,3,3.3)
      text(2.5,-3,counts[1],cex=cex)
      text(0,-1.7,counts[2],cex=cex)
      text(1.5,1,counts[3],cex=cex)
      text(.75,-.35,counts[4],cex=cex)
      text(-1.5,1,counts[5],cex=cex)
      text(-.75,-.35,counts[6],cex=cex)
      text(0,.9,counts[7],cex=cex)
      text(0,0,counts[8],cex=cex)
    }
  )
  par(opar)
  invisible()
}


HeatDiagramDialog <- function(parameterName)
{
  Try(ttHeatDiagramDialog <- tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.title(ttHeatDiagramDialog,"Heat Diagram Options"))
  Try(tkwm.deiconify(ttHeatDiagramDialog))
  Try(tkgrab.set(ttHeatDiagramDialog))
  Try(tkfocus(ttHeatDiagramDialog))  
  Try(tkframe1 <- tkframe(ttHeatDiagramDialog))
  Try(tkgrid(tklabel(tkframe1,text="    ")))
  Try(tkgrid(tklabel(tkframe1,text="    "),
             tklabel(tkframe1,text="The absolute value of the (moderated) t statistic will be used to plot",
               font=.affylmGUIglobals$affylmGUIfont2)))
  Try(tkgrid(tklabel(tkframe1,text="    "),
             tklabel(tkframe1,text=paste("the heat diagram, relative to parameter ",parameterName,".",sep=""),font=.affylmGUIglobals$affylmGUIfont2),
             tklabel(tkframe1,text="    ")))
  Try(tkgrid(tklabel(tkframe1,text="    ")))
  Try(primaryCutoffTcl <- tclVar("4"))  
  Try(otherCutoffTcl   <- tclVar("3"))
  Try(entry.primaryCutoff <- tkentry(tkframe1,textvariable=primaryCutoffTcl,bg="white",width=10,font=.affylmGUIglobals$affylmGUIfont2))
  Try(entry.otherCutoff   <- tkentry(tkframe1,textvariable=otherCutoffTcl,  bg="white",width=10,font=.affylmGUIglobals$affylmGUIfont2))  
  Try(tkgrid(tklabel(tkframe1,text="    "),tklabel(tkframe1,text=paste("D.E. cutoff for parameter ",
    parameterName,":   ",sep=""),font=.affylmGUIglobals$affylmGUIfont2),entry.primaryCutoff,tklabel(tkframe1,text="    ")))
  Try(tkgrid(tklabel(tkframe1,text="    "),tklabel(tkframe1,text=
    "D.E. cutoff for other parameters:   ",font=.affylmGUIglobals$affylmGUIfont2),entry.otherCutoff,tklabel(tkframe1,text="    ")))
  Try(tkgrid.configure(entry.primaryCutoff,sticky="w"))
  Try(tkgrid.configure(entry.otherCutoff,sticky="w"))  
  Try(tkgrid(tklabel(tkframe1,text="    ")))    
  Try(tkgrid(tkframe1))
  Try(tkframeOKCancel <- tkframe(ttHeatDiagramDialog))
  ReturnVal <- list()
  onOK <- function()
  {
    Try(primaryCutoffVal <- as.numeric(tclvalue(primaryCutoffTcl)))
    Try(otherCutoffVal   <- as.numeric(tclvalue(otherCutoffTcl)))
    Try(tkgrab.release(ttHeatDiagramDialog))
    Try(tkdestroy(ttHeatDiagramDialog))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(ReturnVal <<- list(primaryCutoff=primaryCutoffVal,otherCutoff=otherCutoffVal))
  }
  Try(onCancel <- function() {Try(tkgrab.release(ttHeatDiagramDialog));Try(tkdestroy(ttHeatDiagramDialog));Try(tkfocus(.affylmGUIglobals$ttMain));Try(ReturnVal <<- list())})
  Try(OK.but <-tkbutton(tkframeOKCancel,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <-tkbutton(tkframeOKCancel,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(OK.but,Cancel.but))
  Try(tkgrid(tklabel(tkframeOKCancel,text="    ")))
  Try(tkgrid(tkframeOKCancel))
  Try(tkfocus(entry.primaryCutoff))
  Try(tkbind(ttHeatDiagramDialog, "<Destroy>", function() {Try(tkgrab.release(ttHeatDiagramDialog));Try(tkfocus(.affylmGUIglobals$ttMain))}))
  Try(tkwait.window(ttHeatDiagramDialog))
  
  return (ReturnVal)
  
}


HeatDiagramPlot <- function()
{
  Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
  Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
  Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))  
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  
  Try(if (ArraysLoaded==FALSE)
  {
      Try(tkmessageBox(title="Heat Diagram",message="No arrays have been loaded.  Please try New or Open from the File menu.",type="ok",icon="error"))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      return()
  })
  
  Try(if (NumContrastParameterizations==0)
  {
    Try(tkmessageBox(title="Heat Diagram",message="There are no contrast parameterizations available.  Select \"Compute Contrasts\" from the \"Linear Model\" menu.",type="ok",icon="error"))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    return()  
  })  
  Try(contrastParameterizationIndex <- ChooseContrastParameterization())
  Try(if (contrastParameterizationIndex==0) return()) # Cancel
  
  Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
  Try(ContrastNamesVec  <- colnames(as.matrix(ContrastParameterizationList[[contrastParameterizationIndex]]$contrastsMatrixInList$contrasts)))
  Try(NumContrasts <- length(ContrastNamesVec))

  Try(GetContrastReturnVal <- GetContrast(contrastParameterizationIndex))
  Try(if (GetContrastReturnVal$contrastIndex==0) return()) # Cancel
  Try(contrast <- GetContrastReturnVal$contrastIndex)
  Try(ContrastParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))

  Try(fit <- (ContrastParameterizationList[[ContrastParameterizationNameNode]])$fit)

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

  Try(if (ebayesAvailable==FALSE)
  {
    Try(tkmessageBox(title="Heat diagram",message="For now, heat diagrams are only available when empirical bayes statistics are available (requires replicate arrays).",icon="error"))
    return()
  })


  Try(eb  <- (ContrastParameterizationList[[ContrastParameterizationNameNode]])$eb)
#  Try(fit <- eBayes(fit))


  Try(if (NumContrasts<=1)
  {
    Try(tkmessageBox(title="Heat Diagram",message="To plot a heat diagram, you need to have more than one contrast, i.e. more than two RNA types.",type="ok",icon="error"))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    return()  
  })  

  Try(HeatDiagramOptions <- HeatDiagramDialog(colnames(fit$coefficients)[1]))
  Try(if (length(HeatDiagramOptions)==0)
    return())
  Try(primaryCutoff <- HeatDiagramOptions$primaryCutoff)
  Try(otherCutoff   <- HeatDiagramOptions$otherCutoff)  
 
  Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))
  Try(cdfenv<-getCdfInfo(RawAffyData))
 
  Try(geneSymbols <- get("geneSymbols",envir=affylmGUIenvironment))
  Try(if (length(geneSymbols)==0)
  {
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))  
    Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))
    Try(dataName <- strsplit(cleancdfname(RawAffyData@cdfName),"cdf")[[1]])
    Require("reposTools")
    Try(annoPackages <- getReposEntry("http://www.bioconductor.org/data/metaData"))    
    Try(matchIndex <- match(dataName,annoPackages@repdatadesc@repdatadesc[,"Package"]))
    Try(if (!is.na(matchIndex)) 
    {
      Try(install.packages2(dataName,annoPackages))
      Require(dataName)
      Try(code2eval <- paste("Try(geneSymbols <- as.character(unlist(multiget(ls(envir=",dataName,"SYMBOL),env=",dataName,"SYMBOL))))",sep=""))
      Try(eval(parse(text=code2eval)))
      Try(assign("geneSymbols",geneSymbols,affylmGUIenvironment))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    })
  })

	Try(if (length(geneSymbols)>0)
		geneLabels <- geneSymbols
	else
		geneLabels <- ls(cdfenv))

  Try(contrastNames <- colnames(eb$t))
  Try(contrastNamesVec <- GetContrastNamesForHeatDiagram(numContrasts=length(contrastNames),ContrastNames=contrastNames))
  Try(if (length(contrastNamesVec)==0)
    return()
  else
    colnames(eb$t) <- contrastNamesVec) # Local assignment only.

  plotHD <- function() 
  {
    Try(opar<-par(bg="white"))
    Try(heatdiagram(abs(eb$t),fit$coefficients,primary=1,
      critical.primary=primaryCutoff,critical.other=otherCutoff,
      names=substr(geneLabels,1,20),main=plotTitle))
    Try(TempGraphPar<-par(opar))    
  }
  Try(LocalHScale <- .affylmGUIglobals$Myhscale*1.5)
  Try(LocalVScale <- .affylmGUIglobals$Myvscale*0.5)
   
  Try(plotTitle <- paste("Heat diagram relative to parameter",ContrastNamesVec[contrast]))

  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow")) 
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(plotTitleList <- GetPlotTitle(plotTitle)) 
  Try(if (length(plotTitleList)==0) return())
  Try(plotTitle <- plotTitleList$plotTitle)  

  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch")) 
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(ttHeatDiagramPlot <- tktoplevel(.affylmGUIglobals$ttMain))  
  tkwm.title(ttHeatDiagramPlot,plotTitle)
  Try(Require("tkrplot"))

  img <-tkrplot(ttHeatDiagramPlot,plotHD,hscale=LocalHScale,vscale=LocalVScale) 
  Try(SetupPlotKeyBindings(tt=ttHeatDiagramPlot,img=img))
  Try(SetupPlotMenus(tt=ttHeatDiagramPlot,initialfile=paste(limmaDataSetNameText,"HeatDiagram",sep=""),
                 plotFunction=plotHD,img=img))
  
  tkgrid(img)
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow")) 
  tkfocus(ttHeatDiagramPlot)
}

affyPlotMA <- function()
{
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(SlideNamesVec  <- get("SlideNamesVec", envir=affylmGUIenvironment)) 
  Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))  
  Try(if (ArraysLoaded==FALSE)
  {
    Try(tkmessageBox(title="M A Plot",message="Error: No arrays have been loaded.", icon="error",default="ok"))
    return()
  })
  Try(LocalHScale <- .affylmGUIglobals$Myhscale)
  Try(LocalVScale <- .affylmGUIglobals$Myvscale)   
  
  Try(SlideNums <- GetSlideNums())
  Try(if (length(SlideNums)==0) return())
  Try(slide1 <- SlideNums$slide1)
  Try(slide2 <- SlideNums$slide2)


  Try(WhetherToNormalize <- tclvalue(tkmessageBox(title="M A Plot",message="Use normalized data?",type="yesnocancel",icon="question")))
  Try(if (WhetherToNormalize=="cancel") return())
   
  Try(if (WhetherToNormalize=="yes")
  {
    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="M A Plot",message="An error occured while trying to normalize the data.")
      return()
  
    })
    Try(NormalizedAffyData <- get("NormalizedAffyData", envir=affylmGUIenvironment)) 
    
    Try(R <- exprs(NormalizedAffyData)[,slide1])  # Using cDNA notation (R for one channel/array, G for the other)
    Try(G <- exprs(NormalizedAffyData)[,slide2])  # Using cDNA notation (R for one channel/array, G for the other)
    pch <- 16
    cex <- 0.2
  }
  else
  {
    Try(R <- log2(RawAffyData@exprs[,slide1]))  # Using cDNA notation (R for one channel/array, G for the other)
    Try(G <- log2(RawAffyData@exprs[,slide2]))  # Using cDNA notation (R for one channel/array, G for the other)  
    pch <- "."
    cex <- 1
  })

  # R and G are already log2ed.
  M <- R - G
  A <- 0.5*(R+G)
  
  Try(plotFunction <- function() 
  {
    Try(opar<-par(bg="white"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
    Try(plot(A,M,pch=pch,cex=cex,xlab=xLabel,ylab=yLabel,main=plotTitle))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    Try(tmp<-par(opar))
  }) 
  Try(if (WhetherToNormalize=="yes")  
    Try(plotTitle<-paste("Normalized M A Plot (",SlideNamesVec[slide1]," vs ",SlideNamesVec[slide2],")",sep=""))
  else
    Try(plotTitle<-paste("Raw M A Plot (",SlideNamesVec[slide1]," vs ",SlideNamesVec[slide2],")",sep="")))
  Try(plotLabels <- GetPlotLabels(plotTitle,"A","M"))
  Try(if (length(plotLabels)==0) return())
  Try(plotTitle <- plotLabels$plotTitle)
  Try(xLabel    <- plotLabels$xLabel)
  Try(yLabel    <- plotLabels$yLabel)
    
  Require("tkrplot")  
  Try(ttGraph<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.withdraw(ttGraph))
  Try(tkwm.title(ttGraph,plotTitle))
  Try(imgLimmaGUI<-tkrplot(ttGraph,plotFunction,hscale=LocalHScale,vscale=LocalVScale))
  Try(tkwm.title(ttGraph,plotTitle))
  SetupPlotKeyBindings(tt=ttGraph,img=imgLimmaGUI)
  SetupPlotMenus(tt=ttGraph,initialfile="",plotFunction,img=imgLimmaGUI)  
  Try(tkgrid(imgLimmaGUI))
  Try(if (as.numeric(tclvalue(tkwinfo("reqheight",imgLimmaGUI)))<10)  # Nothing plotted.
    Try(tkdestroy(ttGraph))
  else
  {
    Try(tkwm.deiconify(ttGraph))
    Try(tkfocus(imgLimmaGUI))   
  })

  CopyToClip <- function() Try(tkrreplot(imgLimmaGUI))  
}


GetSlideNums <- function()
{
  Try(SlideNamesVec <- get("SlideNamesVec",envir=affylmGUIenvironment))  
  Try(if (min(nchar(gsub("[^0-9]","",SlideNamesVec))==nchar(SlideNamesVec))==TRUE)
    SlideNamesVec <- paste("Slide",SlideNamesVec))  
  Try(NumSlides <- get("NumSlides",envir=affylmGUIenvironment))
  ttGetSlideNum<-tktoplevel(.affylmGUIglobals$ttMain)
  tkwm.deiconify(ttGetSlideNum)
  tkgrab.set(ttGetSlideNum)
  tkfocus(ttGetSlideNum)
  tkwm.title(ttGetSlideNum,"Please Specify Slides To Compare")
  TclRequire("BWidget")  
  combo1<-tkwidget(ttGetSlideNum,"ComboBox",background="white",editable=FALSE,font=.affylmGUIglobals$affylmGUIfont2) 
  combo2<-tkwidget(ttGetSlideNum,"ComboBox",background="white",editable=FALSE,font=.affylmGUIglobals$affylmGUIfont2)   
  tkgrid(tklabel(ttGetSlideNum,text="    "))
  lbl2<-tklabel(ttGetSlideNum,text="Choose a pair of slides to compare",font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(tklabel(ttGetSlideNum,text="    "),lbl2,sticky="w")     
  tkgrid(tklabel(ttGetSlideNum,text="    "))
  tkgrid(tklabel(ttGetSlideNum,text="    "),combo1,tklabel(ttGetSlideNum,text="    "),combo2,tklabel(ttGetSlideNum,text="    "))

  tkgrid(tklabel(ttGetSlideNum,text="    "))
  tkconfigure(combo1,values=SlideNamesVec)
  tkconfigure(combo2,values=SlideNamesVec)    

  tkgrid(tklabel(ttGetSlideNum,text="    "))
  ReturnVal <- list()
  onOK <- function()
  {
      slidenum1 <- as.numeric(tclvalue(tkcmd(combo1,"getvalue")))+1
      slidenum2 <- as.numeric(tclvalue(tkcmd(combo2,"getvalue")))+1
      Try(tkgrab.release(ttGetSlideNum));Try(tkdestroy(ttGetSlideNum));Try(tkfocus(.affylmGUIglobals$ttMain))
      ReturnVal <<- list(slide1=slidenum1,slide2=slidenum2)
  }
  onCancel <- function() {Try(tkgrab.release(ttGetSlideNum));Try(tkdestroy(ttGetSlideNum));Try(tkfocus(.affylmGUIglobals$ttMain)); ReturnVal <<- list()}
  OK.but <-tkbutton(ttGetSlideNum,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  Cancel.but <-tkbutton(ttGetSlideNum,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
  tkgrid(tklabel(ttGetSlideNum,text="    "),OK.but,Cancel.but,tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "))
  tkgrid.configure(OK.but,sticky="e")
  tkgrid(tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "),
       tklabel(ttGetSlideNum,text="    "),tklabel(ttGetSlideNum,text="    "))
  Try(tkbind(OK.but, "<Return>",onOK))
  Try(tkbind(Cancel.but, "<Return>",onCancel))      
  Try(tkfocus(ttGetSlideNum))
  Try(tkbind(ttGetSlideNum, "<Destroy>", function() {Try(tkgrab.release(ttGetSlideNum));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkwait.window(ttGetSlideNum))

  return (ReturnVal)
}

affyPlotMAcontrast <- function()
{
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(SlideNamesVec  <- get("SlideNamesVec", envir=affylmGUIenvironment)) 
  Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))  
  Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
  Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
  Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
  
  Try(if (ArraysLoaded==FALSE)
  {
    Try(tkmessageBox(title="M A Plot",message="Error: No arrays have been loaded.", icon="error",default="ok"))
    return()
  })
  Try(LocalHScale <- .affylmGUIglobals$Myhscale)
  Try(LocalVScale <- .affylmGUIglobals$Myvscale)   

  Try(if (NumContrastParameterizations==0)
  {
    Try(tkmessageBox(title="M A Plot",message="There are no contrast parameterizations available.  Select \"Compute Contrasts\" from the \"Linear Model\" menu.",type="ok",icon="error"))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    return()  
  })  

  Try(contrastParameterizationIndex <- ChooseContrastParameterization())
  Try(if (contrastParameterizationIndex==0) return()) # Cancel
  
  Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
  Try(ContrastNamesVec  <- colnames(as.matrix(ContrastParameterizationList[[contrastParameterizationIndex]]$contrastsMatrixInList$contrasts)))
  Try(NumContrasts <- length(ContrastNamesVec))

  Try(GetContrastReturnVal <- GetContrast(contrastParameterizationIndex))
  Try(if (GetContrastReturnVal$contrastIndex==0) return()) # Cancel
  Try(contrast <- GetContrastReturnVal$contrastIndex)
  Try(ContrastParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))


  Try(GeneLabelsOptions <- GetGeneLabelsOptions())
  Try(if (length(GeneLabelsOptions)==0) return())
  Try(numDEgenesLabeled   <- GeneLabelsOptions$HowManyDEGeneLabels)
  Try(GeneLabelsMaxLength <- GeneLabelsOptions$GeneLabelsMaxLength)
  Try(IDorSymbol <- GeneLabelsOptions$IDorSymbol)

  Try(fit <- (ContrastParameterizationList[[ContrastParameterizationNameNode]])$fit)

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

  Try(if (ebayesAvailable==TRUE)
    Try(fit <- eBayes(fit)))

  Try(M <- fit$coefficients[,contrast])
  Try(A <- rowMeans(exprs(NormalizedAffyData)))
  Try(pch <- 16)
  Try(cex <- 0.2)

  Try(if (numDEgenesLabeled>0)
  {
    Try(if (NumContrasts>1) 
    {
      Try(if (ebayesAvailable==TRUE)
        Try(ord <- order(fit$lods[,contrast],decreasing=TRUE))
      else
        Try(ord <- order(abs(fit$coef[,contrast]),decreasing=TRUE)))
    }
    else 
    {
      Try(if (ebayesAvailable==TRUE)
        Try(ord <- order(fit$lods,decreasing=TRUE))
      else
        Try(ord <- order(abs(fit$coef),decreasing=TRUE)))
    })
    Try(topGenes <- ord[1:numDEgenesLabeled])
    
    Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))
    Try(cdfenv<-getCdfInfo(RawAffyData))
    
		Try(genelist <- data.frame(ID=I(ls(cdfenv))))

		Try(geneSymbols <- get("geneSymbols",envir=affylmGUIenvironment))
		Try(if (length(geneSymbols)==0)
		{
			Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))  
			Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))
			Try(dataName <- strsplit(cleancdfname(RawAffyData@cdfName),"cdf")[[1]])
			Require("reposTools")
			Try(annoPackages <- getReposEntry("http://www.bioconductor.org/data/metaData"))    
			Try(matchIndex <- match(dataName,annoPackages@repdatadesc@repdatadesc[,"Package"]))
			Try(if (!is.na(matchIndex))
			{
				Try(install.packages2(dataName,annoPackages))
				Require(dataName)
				Try(code2eval <- paste("Try(geneSymbols <- as.character(unlist(multiget(ls(envir=",dataName,"SYMBOL),env=",dataName,"SYMBOL))))",sep=""))
				Try(eval(parse(text=code2eval)))
				Try(assign("geneSymbols",geneSymbols,affylmGUIenvironment))
				Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
				Try(genelist <- cbind(as.matrix(as.character(ls(cdfenv))),as.matrix(geneSymbols)))
				Try(colnames(genelist) <- c("ID","Symbol"))
			}
			else
			{
				Try(genelist <- data.frame(ID=I(ls(cdfenv))))
				Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
			})

		}
		else
		{
			Try(genelist <- cbind(as.matrix(as.character(ls(cdfenv))),as.matrix(geneSymbols)))
			Try(colnames(genelist) <- c("ID","Symbol"))  
		})
    
  })
  
  Try(if (IDorSymbol=="Symbol" && !("Symbol" %in% colnames(genelist)))
  {
    Try(tkmessageBox(title="Symbols Not Available",message="Gene symbols are not available.  Probe set IDs will be used instead.",icon="warning"))
    Try(IDorSymbol <- "ID")  
  })
  
  Try(plotFunction <- function() 
  {
    Try(opar<-par(bg="white"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
    Try(plot(A,M,pch=pch,cex=cex,xlab=xLabel,ylab=yLabel,main=plotTitle))
    Try(if (numDEgenesLabeled>0)      
      Try(text(A[topGenes],M[topGenes],labels=substr(genelist[topGenes,IDorSymbol],1,GeneLabelsMaxLength),cex=0.8,col="blue"))) 
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    Try(tmp<-par(opar))
  }) 
  Try(plotTitle<-paste("M A Plot (",ContrastNamesVec[contrast],")",sep=""))
  Try(plotLabels <- GetPlotLabels(plotTitle,"A","M"))
  Try(if (length(plotLabels)==0) return())
  Try(plotTitle <- plotLabels$plotTitle)
  Try(xLabel    <- plotLabels$xLabel)
  Try(yLabel    <- plotLabels$yLabel)
      
  Require("tkrplot")  
  Try(ttGraph<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.withdraw(ttGraph))
  Try(tkwm.title(ttGraph,plotTitle))
  Try(imgLimmaGUI<-tkrplot(ttGraph,plotFunction,hscale=LocalHScale,vscale=LocalVScale))
  Try(tkwm.title(ttGraph,plotTitle))
  SetupPlotKeyBindings(tt=ttGraph,img=imgLimmaGUI)
  SetupPlotMenus(tt=ttGraph,initialfile="",plotFunction,img=imgLimmaGUI)  
  Try(tkgrid(imgLimmaGUI))
  Try(if (as.numeric(tclvalue(tkwinfo("reqheight",imgLimmaGUI)))<10)  # Nothing plotted.
    Try(tkdestroy(ttGraph))
  else
  {
    Try(tkwm.deiconify(ttGraph))
    Try(tkfocus(imgLimmaGUI))   
  })

  CopyToClip <- function() Try(tkrreplot(imgLimmaGUI))  
}

GetGeneLabelsOptions <- function()
{
  Try(ttGeneLabelsOptions <- tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttGeneLabelsOptions))
  Try(tkgrab.set(ttGeneLabelsOptions))
  Try(tkfocus(ttGeneLabelsOptions))
  Try(tkwm.title(ttGeneLabelsOptions,"D.E. Gene Labels"))
  Try(tkgrid(tklabel(ttGeneLabelsOptions,text="       ")))
  Try(HowManyDEGenesTcl <- tclVar(paste(10)))
  Try(entry.HowManyDEGenes<-tkentry(ttGeneLabelsOptions,width="12",font=.affylmGUIglobals$affylmGUIfont2,
    textvariable=HowManyDEGenesTcl,bg="white"))
  Try(GeneLabelsMaxLengthTcl <- tclVar(paste(10)))
  Try(entry.GeneLabelsMaxLength<-tkentry(ttGeneLabelsOptions,width="12",font=.affylmGUIglobals$affylmGUIfont2,
    textvariable=GeneLabelsMaxLengthTcl,bg="white"))

  Try(ReturnVal <- list())
  onOK <- function()
  {
    Try(tkgrab.release(ttGeneLabelsOptions))
    Try(tkdestroy(ttGeneLabelsOptions))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    Try(ReturnVal <<- list(HowManyDEGeneLabels=as.integer(tclvalue(HowManyDEGenesTcl)),
                           GeneLabelsMaxLength=as.integer(tclvalue(GeneLabelsMaxLengthTcl)),
                           IDorSymbol=tclvalue(IDorSymbolTcl)))
  }
  onCancel <- function() {Try(tkgrab.release(ttGeneLabelsOptions));Try(tkdestroy(ttGeneLabelsOptions));Try(tkfocus(.affylmGUIglobals$ttMain)); ReturnVal <<- list()}        

  Try(OK.but <-tkbutton(ttGeneLabelsOptions,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <-tkbutton(ttGeneLabelsOptions,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttGeneLabelsOptions,text="    "),tklabel(ttGeneLabelsOptions,text="Please select D.E. gene labeling options.",font=.affylmGUIglobals$affylmGUIfont2),tklabel(ttGeneLabelsOptions,text="    "),sticky="w"))
  Try(tkgrid(tklabel(ttGeneLabelsOptions,text="       ")))
  Try(tkgrid(tklabel(ttGeneLabelsOptions,text="    "),tklabel(ttGeneLabelsOptions,text="Number of labeled differentially expressed genes",font=.affylmGUIglobals$affylmGUIfont2),entry.HowManyDEGenes,tklabel(ttGeneLabelsOptions,text="    "),sticky="w"))
  Try(tkgrid.configure(entry.HowManyDEGenes,sticky="w"))
  Try(tkgrid(tklabel(ttGeneLabelsOptions,text="       ")))
  Try(tkgrid(tklabel(ttGeneLabelsOptions,text="       "),tklabel(ttGeneLabelsOptions,text="Maximum length of gene labels",font=.affylmGUIglobals$affylmGUIfont2),entry.GeneLabelsMaxLength,tklabel(ttGeneLabelsOptions,text="       "),sticky="w"))
  Try(tkgrid.configure(entry.GeneLabelsMaxLength,sticky="w"))
  Try(tkgrid(tklabel(ttGeneLabelsOptions,text="       ")))
	Try(IDorSymbolTcl <- tclVar("ID"))
  Try(rb1 <- tkradiobutton(ttGeneLabelsOptions,text="Use Probe Set ID",variable=IDorSymbolTcl,value="ID",font=.affylmGUIglobals$affylmGUIfont2))
	Try(rb2 <- tkradiobutton(ttGeneLabelsOptions,text="Use Gene Symbol",variable=IDorSymbolTcl,value="Symbol",font=.affylmGUIglobals$affylmGUIfont2))
	Try(tkgrid(tklabel(ttGeneLabelsOptions,text="       "),rb1))
	Try(tkgrid(tklabel(ttGeneLabelsOptions,text="       "),rb2))	
	Try(tkgrid.configure(rb1,sticky="w"))
	Try(tkgrid.configure(rb2,sticky="w"))
	
  Try(tkgrid(tklabel(ttGeneLabelsOptions,text="       ")))
  
  Try(tkgrid(tklabel(ttGeneLabelsOptions,text="       "),OK.but,Cancel.but))
  Try(tkgrid.configure(OK.but,sticky="e"))
  Try(tkgrid.configure(Cancel.but,sticky="w"))  
  Try(tkgrid(tklabel(ttGeneLabelsOptions,text="    ")))

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

  return(ReturnVal)

}

QQTplot <- function()
{
  Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
  Try(ContrastParameterizationNamesVec <- get("ContrastParameterizationNamesVec",envir=affylmGUIenvironment))
  Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))
  Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
  
  if (ArraysLoaded==FALSE)
  {
      Try(tkmessageBox(title="Quantile-Quantile t-Statistic Plot",message="No arrays have been loaded.  Please try New or Open from the File menu.",type="ok",icon="error"))
      Try(tkfocus(.affylmGUIglobals$ttMain))      
      return()
  }
  if (NumContrastParameterizations==0)
  {
    Try(tkmessageBox(title="Quantile-Quantile t-Statistic Plot",message="There are no contrast parameterizations loaded.  Select \"Compute Contrasts\" from the \"Linear Model\" menu.",type="ok",icon="error"))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    return()  
  }  

  Try(contrastParameterizationIndex <- ChooseContrastParameterization())
  Try(if (contrastParameterizationIndex==0) return()) # Cancel
  
  Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
  Try(ContrastNamesVec  <- colnames(as.matrix(ContrastParameterizationList[[contrastParameterizationIndex]]$contrastsMatrixInList$contrasts)))
  Try(NumContrasts <- length(ContrastNamesVec))

  Try(GetContrastReturnVal <- GetContrast(contrastParameterizationIndex))
  Try(if (GetContrastReturnVal$contrastIndex==0) return()) # Cancel
  Try(contrast <- GetContrastReturnVal$contrastIndex)
  Try(ContrastParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))

  Try(fit <- (ContrastParameterizationList[[ContrastParameterizationNameNode]])$fit)

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

  Try(if (ebayesAvailable==FALSE)
  {
    Try(tkmessageBox(title="QQT plot",message="t statistics are not available because of a lack of replicate arrays.",icon="error"))
    return()
  })


  Try(fit <- eBayes(fit))
  
  Try(if (exists("X11", env=.GlobalEnv) && Sys.info()["sysname"] != "Windows") 
    Try(cex <- 0.3)
  else
    Try(cex <- 0.2))    
  plotQQT <- function() 
  {
    Try(opar<-par(bg="white"))
    Try(if (NumContrasts>1) 
    {
      qqt(fit$t[,contrast],df=fit$df.residual+fit$df.prior,pch=16,cex=cex,main=plotTitle)
    }
    else 
    {
      qqt(fit$t,df=fit$df.residual+fit$df.prior,pch=16,cex=cex,main=plotTitle)
    })
    abline(0,1) 
    Try(tempGraphPar <- par(opar))
  }
  Try(LocalHScale <- .affylmGUIglobals$Myhscale)
  Try(LocalVScale <- .affylmGUIglobals$Myvscale)   
   
#  Try(plotTitle <- paste("Student's t Quantile-Quantile Plot for",ContrastNamesVec[contrast]))
  Try(plotTitle <- ContrastNamesVec[contrast])
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow")) 
  Try(plotTitleList <- GetPlotTitle(plotTitle)) 
  Try(if (length(plotTitleList)==0) return())
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(plotTitle <- plotTitleList$plotTitle)

  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(ttQQTplot <- tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.title(ttQQTplot,plotTitle))
  Try(Require("tkrplot"))

  Try(img <-tkrplot(ttQQTplot,plotQQT,hscale=LocalHScale,vscale=LocalVScale))
  Try(SetupPlotKeyBindings(tt=ttQQTplot,img=img))
  Try(SetupPlotMenus(tt=ttQQTplot,initialfile=paste(limmaDataSetNameText,"QQTPlot",ContrastNamesVec[contrast],sep=""),
                 plotFunction=plotQQT,img=img))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow")) 
  Try(tkgrid(img))
  Try(tkfocus(ttQQTplot))
}

LogOddsPlot <- function()
{
  Try(NumContrastParameterizations <- get("NumContrastParameterizations",envir=affylmGUIenvironment))
  Try(ContrastParameterizationNamesVec <- get("ContrastParameterizationNamesVec",envir=affylmGUIenvironment))
  Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))  
  Try(ContrastParameterizationTREEIndexVec <- get("ContrastParameterizationTREEIndexVec",envir=affylmGUIenvironment))
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(limmaDataSetNameText <- get("limmaDataSetNameText",envir=affylmGUIenvironment))
 
  if (ArraysLoaded==FALSE)
  {
      Try(tkmessageBox(title="Log Odds Plot",message="No arrays have been loaded.  Please try New or Open from the File menu.",type="ok",icon="error"))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      return()
  }

  if (NumContrastParameterizations==0)
  {
    Try(tkmessageBox(title="Log Odds Plot",message="There are no contrast parameterizations loaded.  Select \"Compute Contrasts\" from the \"Linear Model\" menu.",type="ok",icon="error"))
    Try(tkfocus(.affylmGUIglobals$ttMain))
    return()  
  }  

  Try(contrastParameterizationIndex <- ChooseContrastParameterization())
  Try(if (contrastParameterizationIndex==0) return()) # Cancel
  
  Try(.affylmGUIglobals$ContrastParameterizationTREEIndex <- ContrastParameterizationTREEIndexVec[contrastParameterizationIndex])
  Try(ContrastNamesVec  <- colnames(as.matrix(ContrastParameterizationList[[contrastParameterizationIndex]]$contrastsMatrixInList$contrasts)))
  Try(NumContrasts <- length(ContrastNamesVec))

  Try(GetContrastReturnVal <- GetContrast(contrastParameterizationIndex))
  Try(if (GetContrastReturnVal$contrastIndex==0) return()) # Cancel
  Try(contrast <- GetContrastReturnVal$contrastIndex)
  Try(ContrastParameterizationNameNode <- paste("ContrastParameterizationName.",.affylmGUIglobals$ContrastParameterizationTREEIndex,sep=""))

  Try(fit <- (ContrastParameterizationList[[ContrastParameterizationNameNode]])$fit)

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

  Try(if (ebayesAvailable==FALSE)
  {
    Try(tkmessageBox(title="Log Odds Plot",message="Log Odds (B statistic) values are not available because of a lack of replicate arrays.",icon="error"))
    return()
  })

  
  
  Try(fit <- eBayes(fit))

  Try(GeneLabelsOptions <- GetGeneLabelsOptions())
  Try(if (length(GeneLabelsOptions)==0) return())
  Try(numDEgenesLabeled   <- GeneLabelsOptions$HowManyDEGeneLabels)
  Try(GeneLabelsMaxLength <- GeneLabelsOptions$GeneLabelsMaxLength)
  Try(IDorSymbol <- GeneLabelsOptions$IDorSymbol)

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

  Try(if (numDEgenesLabeled>0)
  {
    Try(if (NumContrasts>1)
        Try(ord <- order(fit$lods[,contrast],decreasing=TRUE))
    else
        Try(ord <- order(fit$lods,decreasing=TRUE)))    
    Try(topGenes <- ord[1:numDEgenesLabeled])
  })
  Try(if (exists("X11", env=.GlobalEnv) && Sys.info()["sysname"] != "Windows") 
    Try(cex <- 0.3)
  else
    Try(cex <- 0.2))  

  Try(if (numDEgenesLabeled>0)
  {
    Try(if (NumContrasts>1) 
      Try(ord <- order(fit$lods[,contrast],decreasing=TRUE))
    else 
      Try(ord <- order(fit$lods,decreasing=TRUE)))
    Try(topGenes <- ord[1:numDEgenesLabeled])
    
    Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))
    Try(cdfenv<-getCdfInfo(RawAffyData))
    
		Try(genelist <- data.frame(ID=I(ls(cdfenv))))

		Try(geneSymbols <- get("geneSymbols",envir=affylmGUIenvironment))
		Try(if (length(geneSymbols)==0)
		{
			Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))  
			Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))
			Try(dataName <- strsplit(cleancdfname(RawAffyData@cdfName),"cdf")[[1]])
			Require("reposTools")
			Try(annoPackages <- getReposEntry("http://www.bioconductor.org/data/metaData"))    
			Try(matchIndex <- match(dataName,annoPackages@repdatadesc@repdatadesc[,"Package"]))
			Try(if (!is.na(matchIndex))
			{
				Try(install.packages2(dataName,annoPackages))
				Require(dataName)
				Try(code2eval <- paste("Try(geneSymbols <- as.character(unlist(multiget(ls(envir=",dataName,"SYMBOL),env=",dataName,"SYMBOL))))",sep=""))
				Try(eval(parse(text=code2eval)))
				Try(assign("geneSymbols",geneSymbols,affylmGUIenvironment))
				Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
				Try(genelist <- cbind(as.matrix(as.character(ls(cdfenv))),as.matrix(geneSymbols)))
				Try(colnames(genelist) <- c("ID","Symbol"))
			}
			else
			{
				Try(genelist <- data.frame(ID=I(ls(cdfenv))))
				Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
			})

		}
		else
		{
			Try(genelist <- cbind(as.matrix(as.character(ls(cdfenv))),as.matrix(geneSymbols)))
			Try(colnames(genelist) <- c("ID","Symbol"))  
		})
    
  })

  plotLogOdds <- function()
  {
    Try(opar<-par(bg="white"))
    Try(if (NumContrasts>1)
    {
      Try(plot(fit$coef[,contrast],fit$lods[,contrast],pch=16,cex=cex,xlab="Log Fold Change",ylab="Log Odds",main=plotTitle))
      Try(if (numDEgenesLabeled>0)
        text(fit$coef[topGenes,contrast],fit$lods[topGenes,contrast],labels=substr(genelist[topGenes,IDorSymbol],1,GeneLabelsMaxLength),cex=0.8,col="blue"))
    }
    else
    {
      Try(plot(fit$coef,fit$lods,pch=16,cex=cex,xlab="Log Fold Change",ylab="Log Odds",main=plotTitle))
      Try(if (numDEgenesLabeled>0)
        text(fit$coef[topGenes],fit$lods[topGenes],labels=substring(genelist[topGenes,IDorSymbol],1,10),cex=0.8,col="blue"))
    })
    Try(tempGraphPar <- par(opar))
  }
  Try(LocalHScale <- .affylmGUIglobals$Myhscale)
  Try(LocalVScale <- .affylmGUIglobals$Myvscale)   
   
  Try(plotTitle <- (ContrastNamesVec[contrast]))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow")) 
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(plotTitleList <- GetPlotTitle(plotTitle)) 
  Try(if (length(plotTitleList)==0) return())
  Try(plotTitle <- plotTitleList$plotTitle)

  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch")) 
  Try(tkfocus(.affylmGUIglobals$ttMain))  
  Try(ttLogOddsPlot <- tktoplevel(.affylmGUIglobals$ttMain))  
  Try(tkwm.title(ttLogOddsPlot,plotTitle))
  Try(Require("tkrplot"))

  Try(img <-tkrplot(ttLogOddsPlot,plotLogOdds,hscale=LocalHScale,vscale=LocalVScale))
  Try(SetupPlotKeyBindings(tt=ttLogOddsPlot,img=img))
  Try(SetupPlotMenus(tt=ttLogOddsPlot,initialfile=paste(limmaDataSetNameText,"LogOddsPlot",ContrastNamesVec[contrast],sep=""),
                 plotFunction=plotLogOdds,img=img))
  
  Try(tkgrid(img))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkfocus(ttLogOddsPlot))

}



ImageQualityPlot <- function()
{
  Try(SlideNamesVec  <- get("SlideNamesVec", envir=affylmGUIenvironment)) 
  Try(LocalHScale <- .affylmGUIglobals$Myhscale)
  Try(LocalVScale <- .affylmGUIglobals$Myvscale)   
  Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment)) 
  Try(RawAffyData <- get("RawAffyData", envir=affylmGUIenvironment)) 
  Try(if (ArraysLoaded==FALSE)
  {
    Try(tkmessageBox(title="Image Array Plot",message="Error: No arrays have been loaded.",
        icon="error",default="ok"))
    return()
  })
  
  Try(NormMethod <- get("NormMethod", envir=affylmGUIenvironment))
  Try(if (NormMethod!="PLM")
  {
    Try(tkmessageBox(title="Error! Plot requires PLM normalization",message=
      "This plot requires PLM normalization.  Please choose \"Normalize\" from the \"Normalization Menu\" and select \"Robust Probe-level Linear Model\"",
      icon="error"))
    return()
  })
  
  Try(weightsPLM <- get("weightsPLM", envir=affylmGUIenvironment))
  
  Try(slide <- GetSlideNum())
  Try(if (slide==0) return())
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))

  Try(plotFunction <- function() 
  {
    Try(opar<-par(bg="white"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
		pm.index <- unique(unlist(indexProbes(RawAffyData, "pm")))
		rows <- nrow(RawAffyData)
		cols <- ncol(RawAffyData)
		pm.x.locs <- pm.index%%rows
		pm.x.locs[pm.x.locs == 0] <- rows
		pm.y.locs <- pm.index%/%rows + 1
		xycoor <- matrix(cbind(pm.x.locs,pm.y.locs),ncol=2)
		xycoor2 <- matrix(cbind(pm.x.locs,pm.y.locs+1),ncol=2)

		weightmatrix <- matrix(nrow=rows,ncol=cols)
		weightmatrix[xycoor] <- weightsPLM[,slide]
		weightmatrix[xycoor2] <- weightsPLM[,slide]
		# this line flips the matrix around so it is correct
		weightmatrix <- as.matrix(rev(as.data.frame(weightmatrix)))
		image(weightmatrix,col=terrain.colors(12),xaxt='n',yaxt='n',main=SlideNamesVec[slide])
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
    Try(tmp<-par(opar))
  })
  Try(plotTitle<-SlideNamesVec[slide])
  Try(plotLabels <- GetPlotLabels(plotTitle,"",""))
  Try(if (length(plotLabels)==0) return())
  Try(plotTitle <- plotLabels$plotTitle)
  Try(xLabel    <- plotLabels$xLabel)
  Try(yLabel    <- plotLabels$yLabel)
  
  Try(WhetherToUseTkrplot <- tclvalue(tkmessageBox(title="Where To Plot Array Image",type="yesnocancel",
    message="Plot this image in R rather than a new (Tk) window? (Requires less memory.)",icon="question")))
  Try(if (WhetherToUseTkrplot=="cancel") return())
  Try(if (WhetherToUseTkrplot=="yes")
    plotFunction()
  else
  {
    Require("tkrplot")  
    Try(ttGraph<-tktoplevel(.affylmGUIglobals$ttMain))
    Try(tkwm.withdraw(ttGraph))
    Try(tkwm.title(ttGraph,plotTitle))
    Try(imgLimmaGUI<-tkrplot(ttGraph,plotFunction,hscale=LocalHScale,vscale=LocalVScale))
    Try(tkwm.title(ttGraph,paste("Image Plot for",SlideNamesVec[slide])))
    SetupPlotKeyBindings(tt=ttGraph,img=imgLimmaGUI)
    SetupPlotMenus(tt=ttGraph,initialfile="",plotFunction,img=imgLimmaGUI)  
    Try(tkgrid(imgLimmaGUI))
    Try(if (as.numeric(tclvalue(tkwinfo("reqheight",imgLimmaGUI)))<10)  # Nothing plotted.
      Try(tkdestroy(ttGraph))
    else
    {
      Try(tkwm.deiconify(ttGraph))
      Try(tkfocus(imgLimmaGUI))   
    })

    CopyToClip <- function() Try(tkrreplot(imgLimmaGUI))  
  })
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}



GetMultipleContrasts <- function(contrastParameterizationIndex)
{
  Try(ttGetMultipleContrasts<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttGetMultipleContrasts))
  Try(tkgrab.set(ttGetMultipleContrasts)  )
  Try(tkfocus(ttGetMultipleContrasts))
  Try(tkwm.title(ttGetMultipleContrasts,"Choose one or more contrast"))
  Try(scr <- tkscrollbar(ttGetMultipleContrasts, repeatinterval=5,command=function(...)tkyview(tl,...)))
  Try(xscr <- tkscrollbar(ttGetMultipleContrasts, repeatinterval=5,command=function(...)tkxview(tl,...) ,orient="horizontal"))                       
  ## Safest to make sure scr exists before setting yscrollcommand
  Try(tl<-tklistbox(ttGetMultipleContrasts,height=4,width=30,selectmode="multiple",xscrollcommand=function(...)tkset(xscr,...),yscrollcommand=function(...)tkset(scr,...),background="white",font=.affylmGUIglobals$affylmGUIfont2)   )
  Try(lbl2<-tklabel(ttGetMultipleContrasts,text="Which contrast(s) is this for?",font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttGetMultipleContrasts,text="       "),row=0,column=1,columnspan=1))
  Try(tkgrid(tklabel(ttGetMultipleContrasts,text="       "),row=0,column=4,columnspan=1))
  Try(tkgrid(lbl2,row=1,column=2,columnspan=2,rowspan=1))
  Try(tkgrid.configure(lbl2,sticky="w"))
  Try(tkgrid(tklabel(ttGetMultipleContrasts,text="         "),row=2,column=1))
  Try(tkgrid(tl,row=2,column=2,columnspan=2,rowspan=4,sticky="ew"))
  Try(tkgrid(scr,row=2,column=4,columnspan=1,rowspan=4,sticky="wns"))
  Try(tkgrid(xscr,row=6,column=2,columnspan=2,sticky="wne"))
  
  Try(ContrastParameterizationList <- get("ContrastParameterizationList",envir=affylmGUIenvironment))

  Try(ContrastNamesVec  <- colnames(as.matrix(ContrastParameterizationList[[contrastParameterizationIndex]]$contrastsMatrixInList$contrasts)))
  
  Try(NumContrasts <- length(ContrastNamesVec))
  
  coefIndexList <- list()

  Try(if (NumContrasts>0)
    Try(for (i in (1:NumContrasts))     
      Try(tkinsert(tl,"end",ContrastNamesVec[i]))))

  Try(tkselection.set(tl,0))

  Try(ReturnVal <- list(coefIndices=list())) # Other attributes can be added later if necessary.
  onOK <- function()
  {
			Try(ReturnVal <<- list(contrastIndices=as.list(as.numeric(strsplit(tclvalue(tkcurselection(tl))," ")[[1]])+1)))
      Try(tkgrab.release(ttGetMultipleContrasts));Try(tkdestroy(ttGetMultipleContrasts));Try(tkfocus(.affylmGUIglobals$ttMain))
  }
  onCancel <- function() {Try(tkgrab.release(ttGetMultipleContrasts));Try(tkdestroy(ttGetMultipleContrasts));Try(tkfocus(.affylmGUIglobals$ttMain));Try(ReturnVal <<- list(contrastIndices=list()))}
  Try(OK.but <-tkbutton(ttGetMultipleContrasts,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <-tkbutton(ttGetMultipleContrasts,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttGetMultipleContrasts,text="    ")))
  Try(tkgrid(tklabel(ttGetMultipleContrasts,text="    "),tklabel(ttGetMultipleContrasts,text="    "),OK.but,Cancel.but))
  Try(tkgrid.configure(OK.but,sticky="e"))
  Try(tkgrid.configure(Cancel.but,sticky="w"))  
  Try(tkbind(OK.but, "<Return>",onOK))
  Try(tkbind(tl, "<Return>",onOK))    
  Try(tkbind(Cancel.but, "<Return>",onCancel))      
  Try(tkgrid(tklabel(ttGetMultipleContrasts,text="    ")))
  Try(tkfocus(ttGetMultipleContrasts))
  Try(tkbind(ttGetMultipleContrasts, "<Destroy>", function() {Try(tkgrab.release(ttGetMultipleContrasts));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkwait.window(ttGetMultipleContrasts))

  return (ReturnVal)
}


GetSetNames <- function(numSets=2,set1="",set2="",set3="")
{
  Try(ttGetSetNames<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttGetSetNames))
  Try(tkgrab.set(ttGetSetNames))
  Try(tkfocus(ttGetSetNames)  )
  Try(tkwm.title(ttGetSetNames,"Set names for Venn diagram"))
  Try(tkgrid(tklabel(ttGetSetNames,text="    ")))
  Try(set1Tcl <- tclVar(init=set1))
  Try(entry.set1<-tkentry(ttGetSetNames,width="40",font=.affylmGUIglobals$affylmGUIfont2,textvariable=set1Tcl,bg="white"))
  Try(tkgrid(tklabel(ttGetSetNames,text="Set 1 : ",font=.affylmGUIglobals$affylmGUIfont2),entry.set1))
  Try(tkgrid(tklabel(ttGetSetNames,text="    ")))
  Try(tkgrid.configure(entry.set1,columnspan=2))
  Try(set2Tcl <- tclVar(init=set2))
  Try(if (numSets>1)
  {
    Try(entry.set2<-tkentry(ttGetSetNames,width="40",font=.affylmGUIglobals$affylmGUIfont2,textvariable=set2Tcl,bg="white"))
    Try(tkgrid(tklabel(ttGetSetNames,text="Set 2 : ",font=.affylmGUIglobals$affylmGUIfont2),entry.set2))
    Try(tkgrid(tklabel(ttGetSetNames,text="    ")))
    Try(tkgrid.configure(entry.set2,columnspan=2))
  })
  Try(set3Tcl <- tclVar(init=set3))
  Try(if (numSets>2)
  {
    Try(entry.set3<-tkentry(ttGetSetNames,width="40",font=.affylmGUIglobals$affylmGUIfont2,textvariable=set3Tcl,bg="white"))
    Try(tkgrid(tklabel(ttGetSetNames,text="Set 3 :   ",font=.affylmGUIglobals$affylmGUIfont2),entry.set3))
    Try(tkgrid(tklabel(ttGetSetNames,text="    ")))
    Try(tkgrid.configure(entry.set3,columnspan=2))
  })

  Try(ReturnVal <- list())
  Try(onOK <- function()
  {
      Try(set1 <- tclvalue(set1Tcl))
      Try(set2 <- "")
      Try(if (numSets>1)
        Try(set2 <- tclvalue(set2Tcl)))
      Try(set3 <- "")
      Try(if (numSets>2)
        Try(set3 <- tclvalue(set3Tcl)))
      Try(tkgrab.release(ttGetSetNames))
      Try(tkdestroy(ttGetSetNames))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(ReturnVal <<- list(set1=set1,set2=set2,set3=set3))
  })
  onCancel <- function() {Try(tkgrab.release(ttGetSetNames));Try(tkdestroy(ttGetSetNames));Try(tkfocus(.affylmGUIglobals$ttMain));ReturnVal <<- list()}
  OK.but <-tkbutton(ttGetSetNames,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  Cancel.but <-tkbutton(ttGetSetNames,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
  Try(tkgrid(tklabel(ttGetSetNames,text="    "),OK.but,Cancel.but))
  Try(tkgrid(tklabel(ttGetSetNames,text="    ")))
  Try(tkbind(ttGetSetNames, "<Destroy>", function() {Try(tkgrab.release(ttGetSetNames));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkfocus(ttGetSetNames))
  Try(tkwait.window(ttGetSetNames))

  return (ReturnVal)
}

GetContrastNamesForHeatDiagram <- function(numContrasts=2,ContrastNames=c("Contrast 1","Contrast 2"))
{
  Try(ttGetContrastNamesForHeatDiagram<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttGetContrastNamesForHeatDiagram))
  Try(tkgrab.set(ttGetContrastNamesForHeatDiagram))
  Try(tkfocus(ttGetContrastNamesForHeatDiagram)  )
  Try(tkwm.title(ttGetContrastNamesForHeatDiagram,"Contrast names for heat diagram"))
  Try(tkgrid(tklabel(ttGetContrastNamesForHeatDiagram,text="    ")))
  
  Try(namesTcl <- list())
  Try(entryBoxes <- list())
  
  Try(for (i in (1:numContrasts))
  {
    Try(namesTcl[[i]] <- tclVar(init=ContrastNames[i]))
    Try(entryBoxes[[i]]<-tkentry(ttGetContrastNamesForHeatDiagram,width="40",font=.affylmGUIglobals$affylmGUIfont2,textvariable=namesTcl[[i]],bg="white"))
    Try(tkgrid(tklabel(ttGetContrastNamesForHeatDiagram,text=paste("Contrast",i),font=.affylmGUIglobals$affylmGUIfont2),entryBoxes[[i]]))
    Try(tkgrid(tklabel(ttGetContrastNamesForHeatDiagram,text="    ")))
    Try(tkgrid.configure(entryBoxes[[i]],columnspan=2))
  })

  Try(ReturnVal <- c())
  Try(onOK <- function()
  {
      Try(ReturnVal <<- c())
      Try(for (i in (1:numContrasts))
      {
        Try(ReturnVal[i] <<- tclvalue(namesTcl[[i]]))
        Try(names(ReturnVal)[i] <<- paste("Contrast",i,sep=""))
      })
      Try(tkgrab.release(ttGetContrastNamesForHeatDiagram))
      Try(tkdestroy(ttGetContrastNamesForHeatDiagram))
      Try(tkfocus(.affylmGUIglobals$ttMain))
  })
  onCancel <- function() {Try(tkgrab.release(ttGetContrastNamesForHeatDiagram));Try(tkdestroy(ttGetContrastNamesForHeatDiagram));Try(tkfocus(.affylmGUIglobals$ttMain));ReturnVal <<- c()}
  OK.but <-tkbutton(ttGetContrastNamesForHeatDiagram,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2)
  Cancel.but <-tkbutton(ttGetContrastNamesForHeatDiagram,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2)
  Try(tkgrid(tklabel(ttGetContrastNamesForHeatDiagram,text="    "),OK.but,Cancel.but))
  Try(tkgrid(tklabel(ttGetContrastNamesForHeatDiagram,text="    ")))
  Try(tkbind(ttGetContrastNamesForHeatDiagram, "<Destroy>", function() {Try(tkgrab.release(ttGetContrastNamesForHeatDiagram));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkfocus(ttGetContrastNamesForHeatDiagram))
  Try(tkwait.window(ttGetContrastNamesForHeatDiagram))

  return (ReturnVal)
}
topTable2 <- function (fit, coef = 1, number = 10, genelist = NULL, adjust.method = "holm", 
    sort.by = "B") 
{
    if (!missing(genelist)) 
        fit$genes <- genelist
    if ("t" %in% names(fit))
      toptable2(fit = fit[c("coefficients", "stdev.unscaled")], 
        coef = coef, number = number, genelist = fit$genes, A = fit$Amean, 
        eb = fit[c("t", "p.value", "lods")], adjust.method = adjust.method, 
        sort.by = sort.by)
    else
      toptable2(fit = fit[c("coefficients", "stdev.unscaled")], 
        coef = coef, number = number, genelist = fit$genes, A = fit$Amean, 
        adjust.method = adjust.method, 
        sort.by = sort.by)
}

toptable2 <- function (fit, coef = 1, number = 10, genelist = NULL, A = NULL, 
    eb = NULL, adjust.method = "holm", sort.by = "B", ...) 
{
    if (is.null(eb)) {
        fit$coefficients <- as.matrix(fit$coef)[, coef]
        fit$stdev.unscaled <- as.matrix(fit$stdev)[, coef]
        eb <- ebayes(fit, ...)
        coef <- 1
    }
    M <- as.matrix(fit$coef)[, coef]
    if (is.null(A)) {
        if (sort.by == "A") 
            stop("Cannot sort by A-values as these have not been given")
    }
    else {
        if (NCOL(A) > 1) 
            A <- rowMeans(A, na.rm = TRUE)
    }
    tstat <- as.matrix(eb$t)[, coef]
    P.Value <- as.matrix(eb$p)[, coef]
    B <- as.matrix(eb$lods)[, coef]
    ord <- switch(sort.by, M = order(abs(M), decreasing = TRUE), 
        A = order(A, decreasing = TRUE), P = order(P.Value, decreasing = FALSE), 
        p = order(P.Value, decreasing = FALSE), T = order(abs(tstat), 
            decreasing = TRUE), t = order(abs(tstat), decreasing = TRUE), 
        B = order(B, decreasing = TRUE), order(B, decreasing = TRUE))
    top <- ord[1:number]
    i <- is.na(P.Value)
    if (any(i)) 
        P.Value[!i] <- p.adjust(P.Value[!i], method = adjust.method)
    else P.Value <- p.adjust(P.Value, method = adjust.method)
    if (is.null(genelist)) 
        tab <- data.frame(M = M[top])
    else if (is.null(dim(genelist))) 
        tab <- data.frame(Name = I(genelist[top]), M = M[top])
    else tab <- data.frame(genelist[top, ,drop=FALSE], M = M[top])
    if (!is.null(A)) 
        tab <- data.frame(tab, A = A[top])
    tab <- data.frame(tab, t = tstat[top], P.Value = P.Value[top], 
        B = B[top])
    rownames(tab) <- as.character(1:length(M))[top]
    tab
}

.First.lib <- function(libname, pkgname, where) 
{
     capable <- capabilities()
     if(!capable["tcltk"]){
         stop(paste("The tcl/tk library is not available in your system.",
                    "Download/install the tcltk library from",
                    "www.tcl.tk/software/tcltk/"))
     }else{
         if(interactive()){
             out <- paste("Package tcltk not able to be loaded!")
             if (.Platform$OS.type == "windows")
                 out <- paste(out,"\nThe most likely cause of this",
                              "is that your Tcl/Tk installation is",
                              "misconfigured\nPlease see the R",
                              "Windows FAQ, question 3.6:\n",
                              "http://cran.r-project.org/bin/windows/contrib/rw-FAQ.html#Package%20TclTk%20does%20not%20work.")

             require("tcltk", character.only = TRUE) || stop(out)
         }
     }

	if (require(limma)==FALSE)
	{
		  if (interactive())
			  tkmessageBox(title="An error has occured!",message=paste("Cannot find package limma"),icon="error",type="ok")
			stop("Cannot find package limma")
	}

  if (interactive())
  {
		if (.Platform$OS.type=="windows")
		{
			regPath  <- "HKEY_CURRENT_USER\\SOFTWARE\\ActiveState\\ActiveTcl"
			regPath2 <- "HKEY_LOCAL_MACHINE\\SOFTWARE\\ActiveState\\ActiveTcl"
			if(inherits(try(TclVersion <- tclvalue(tkcmd("registry","get",regPath,"CurrentVersion")),TRUE),"try-error")&&
				 inherits(try(TclVersion2 <- tclvalue(tkcmd("registry","get",regPath2,"CurrentVersion")),TRUE),"try-error"))
			{
				cat(paste("\nWarning: ActiveTcl could not be found in the Windows Registry.\n"))
				cat(paste("\nEither it has not been installed or it has not been installed with sufficient privileges.\n\n"))
				cat(paste("\naffylmGUI requires the Tcl/Tk extensions Tktable and BWidget which are not distributed with R,\n"))
				cat(paste("\nbut they are distributed with ActiveTcl.\n"))
			}
			else
			{
				if (!inherits(try(TclVersion <- tclvalue(tkcmd("registry","get",regPath,"CurrentVersion")),TRUE),"try-error"))
				{
					regPath <- paste(regPath,TclVersion,sep="\\")
					TclPath <-  tclvalue(tkcmd("registry","get",regPath,""))
					cat(paste("\nActiveTcl was found in the Windows Registry (for CURRENT_USER), installed in",TclPath,sep="\n"))
					cat(paste("\nThis directory will be added to the Tcl search path to enable affylmGUI\n"))
					cat(paste("to find the Tktable and BWidget extensions.\n"))
					addTclPath(paste(gsub("\\\\","/",TclPath),"lib",sep="/"))
				}
				if (!inherits(try(TclVersion2 <- tclvalue(tkcmd("registry","get",regPath2,"CurrentVersion")),TRUE),"try-error"))      
				{
					regPath2 <- paste(regPath2,TclVersion2,sep="\\")
					TclPath2 <-  tclvalue(tkcmd("registry","get",regPath2,""))
					cat(paste("\nActiveTcl was found in the Windows Registry (for LOCAL_MACHINE), installed in",TclPath2,sep="\n"))
					cat(paste("\nThis directory will be added to the Tcl search path to enable affylmGUI\n"))
					cat(paste("to find the Tktable and BWidget extensions.\n"))
					addTclPath(paste(gsub("\\\\","/",TclPath2),"lib",sep="/"))
				}
			}
		}


		if ((.Platform$OS.type=="windows")&&(.Platform$GUI == "Rgui"))
		{
			winMenuAdd("affylmGUI");winMenuAddItem("affylmGUI","affylmGUI","affylmGUI()")
			cat(paste("\nTo begin, type affylmGUI() or use the pull-down menu.\n"))
		}
		else
			cat(paste("\nTo begin, type affylmGUI()\n"))

    # I only get .First.lib to ask the user whether they want to start the GUI with
    # a message box for the Windows OS.  I encountered some problems under linux
    # for the case where the Tcl/Tk extensions can't be found (so affylmGUI tries
    # to exit), and speculated that there could be problems arising from running
    # the whole affylmGUI() program before finishing .First.lib.
    if (interactive() && .Platform$OS.type=="windows")
    {
      BeginAffyLimmaGUI <- tclvalue(tkmessageBox(title="affylmGUI",message="Begin affylmGUI?",type="yesno",icon="question"))
      if (BeginAffyLimmaGUI=="yes") 
        affylmGUI()
      else
        bringToTop(-1)
    }
  }
}


