R/MDSgui.R

MDSgui <-
function () 
{
	tclRequire("Tktable")
tclRequire("BWidget")
    newUser <- function() {
        NewU = tktoplevel()
        tkwm.resizable(NewU, "0", "0")
        tkwm.deiconify(NewU)
        tkwm.title(NewU, "New User")
        tkwm.geometry(NewU, "280x100")
        NewUcanvas = tkcanvas(NewU, width = "1128", height = "756", 
            bg = col.sec)
        tkplace(NewUcanvas, relx = 0, rely = 0, relwidth = 1, 
            relheight = 1, `in` = NewU)
        frameNU <- tkwidget(NewU, "TitleFrame", text = "User Name Entry", 
            background = "white")
        tkplace(frameNU, relx = 0.02, rely = 0.02, relwidth = 0.96, 
            relheight = 0.96, `in` = NewU)
        tkplace(tklabel(frameNU, text = "Enter your Name", background = "white"), 
            relx = 0.05, rely = 0.3, `in` = frameNU)
        UNinput = tclVar("")
        UNtext = tkentry(NewU, width = 15, textvariable = UNinput)
        tkplace(UNtext, relx = 0.6, rely = 0.3, `in` = frameNU)
        On.Enter <- function() {
            UN = as.character(tclvalue(UNinput))
            if (tclvalue(MGvar$Active.UserName) == "None") {
                tclvalue(MGvar$Active.UserName) <<- UN
                tclvalue(MGvar$UserName) <- paste("User: ", tclvalue(MGvar$Active.UserName))
                tkdestroy(NewU)
            }
            else {
                surechange = tkmessageBox(message = "Are you sure you want to replace current user?", 
                  type = "yesno", default = "no")
                if (as.character(surechange) == "yes") {
                  tclvalue(MGvar$Active.UserName) <<- UN
                  tclvalue(MGvar$UserName) <- paste("User: ", 
                    tclvalue(MGvar$Active.UserName))
                  tkdestroy(NewU)
                }
                else {
                  tkdestroy(NewU)
                }
            }
        }
        tkplace(tkbutton(NewU, text = "Enter", width = 15, command = function() On.Enter()), 
            relx = 0.3, rely = 0.7, `in` = NewU)
        tkfocus(NewU)
        tkbind(NewU, "<Return>", On.Enter)
        tkwait.window(NewU)
    }
    plotting2D <- function(data, title = MGvar$activeplot.title, 
        Measure = MGvar$dMeas, showtitle = MGvar$activeplot.title.show, 
        showmeas = MGvar$activeplot.distmeas, xlabel = MGvar$activeplot.xlab, 
        ylabel = MGvar$activeplot.ylab, bgcol = MGvar$activeplot.bg, 
        pointcex = MGvar$activeplot.cex, showlabs = MGvar$activeplot.labs, 
        showpoints = MGvar$activeplot.showpoints, pointcol = MGvar$activeplot.pointcol, 
        pointshape = MGvar$activeplot.type, ymeas = MGvar$activeplot.yaxt, 
        xmeas = MGvar$activeplot.xaxt, axcol = MGvar$activeplot.axescol, 
        indexLabeled = MGvar$indexLabeled, zoomedcoords = MGvar$newCoords, 
        showreg = MGvar$activeplot.showreg, regcol = MGvar$activeplot.regcol, 
        showleg = MGvar$activeplot.showleg, Zrat = MGvar$zoominrat, 
        Mvup = MGvar$moveup, Mvdn = MGvar$movedown, Mvlt = MGvar$moveleft, 
        Mvrt = MGvar$moveright, PTcolsindex = MGvar$MDSmat.Cols, 
        showdist = MGvar$activeplot.showdist, distcol = MGvar$activeplot.distcol) {
        if (showtitle == "yes") {
            graphtitle = title
        }
        if (showtitle == "no") {
            graphtitle = ""
        }
        if (showmeas == "yes") {
            distanceMeasure = MGvar$dMeas
        }
        if (showmeas == "no") {
            distanceMeasure = ""
        }
        if (showpoints == "yes") {
            pointtype = "p"
        }
        if (showpoints == "no") {
            pointtype = "n"
        }
        params <- par(bg = bgcol)
        par(mar = c(3, 3, 3, 3))
        par(cex.axis = 0.8)
        if (nrow(data) == 1 && ncol(data) == 1) {
            plot(data, type = "n", xaxt = "n", yaxt = "n", ylab = "n", 
                xlab = "n")
            par(params)
        }
        else {
            MGvar$X.Coords <<- data[, 1]
            MGvar$Y.Coords <<- data[, 2]
            tabzoomswitch <- "off"
            if (tclvalue(MGvar$ActivePlottingTab) == "Tab1") {
                if (MGvar$Tab1.zoomedswitch == "on") {
                  tabzoomswitch <- "on"
                  MGvar$X.Coords <<- zoomedcoords[, 1]
                  MGvar$Y.Coords <<- zoomedcoords[, 2]
                }
            }
            if (tclvalue(MGvar$ActivePlottingTab) == "Tab2") {
                if (MGvar$Tab2.zoomedswitch == "on") {
                  tabzoomswitch <- "on"
                  MGvar$X.Coords <<- zoomedcoords[, 1]
                  MGvar$Y.Coords <<- zoomedcoords[, 2]
                }
            }
            if (tclvalue(MGvar$ActivePlottingTab) == "Tab3") {
                if (MGvar$Tab3.zoomedswitch == "on") {
                  tabzoomswitch <- "on"
                  MGvar$X.Coords <<- zoomedcoords[, 1]
                  MGvar$Y.Coords <<- zoomedcoords[, 2]
                }
            }
            if (tclvalue(MGvar$ActivePlottingTab) == "Tab4") {
                if (MGvar$Tab4.zoomedswitch == "on") {
                  tabzoomswitch <- "on"
                  MGvar$X.Coords <<- zoomedcoords[, 1]
                  MGvar$Y.Coords <<- zoomedcoords[, 2]
                }
            }
            if (tclvalue(MGvar$ActivePlottingTab) == "Tab5") {
                if (MGvar$Tab5.zoomedswitch == "on") {
                  tabzoomswitch <- "on"
                  MGvar$X.Coords <<- zoomedcoords[, 1]
                  MGvar$Y.Coords <<- zoomedcoords[, 2]
                }
            }
            Xmin <- min(MGvar$X.Coords)
            Xmax <- max(MGvar$X.Coords)
            Ymin <- min(MGvar$Y.Coords)
            Ymax <- max(MGvar$Y.Coords)
            Xrange <- Xmax - Xmin
            Yrange <- Ymax - Ymin
            Xmin <- Xmin + (1 - Zrat) * Xrange/2 - (Mvlt - 1) * 
                Xrange + (Mvrt - 1) * Xrange
            Xmax <- Xmax - (1 - Zrat) * Xrange/2 - (Mvlt - 1) * 
                Xrange + (Mvrt - 1) * Xrange
            Ymin <- Ymin + (1 - Zrat) * Yrange/2 - (Mvdn - 1) * 
                Yrange + (Mvup - 1) * Yrange
            Ymax <- Ymax - (1 - Zrat) * Yrange/2 - (Mvdn - 1) * 
                Yrange + (Mvup - 1) * Yrange
            if (showleg == "yes") {
                Ymax = Ymax + 0.03 * Yrange
                Xmax = Xmax + 0.015 * Xrange
                Xmin = Xmin - 0.015 * Xrange
            }
            plot(MGvar$X.Coords, MGvar$Y.Coords, ylim = c(Ymin, 
                Ymax), xlim = c(Xmin, Xmax), type = "n", asp = 1, 
                xaxt = xmeas, yaxt = ymeas, main = graphtitle, 
                bg = bgcol, cex = pointcex, col = pointcol, fg = axcol, 
                pch = pointshape, ylab = "", xlab = "", plt = c(1, 
                  1, 1, 1))
            par(params)
            countcols = 1
            if (length(MGvar$remPcompindex) > 0) {
                for (i in 1:nrow(MGvar$activedata)) {
                  skip = FALSE
                  for (j in 1:length(MGvar$remPcompindex)) {
                    if (i == MGvar$remPcompindex[j]) {
                      skip = TRUE
                    }
                  }
                  if (!skip) {
                    MGvar$PTcolsindex[countcols] = MGvar$MDSmat.Cols[i]
                    countcols = countcols + 1
                  }
                }
            }
            if (showpoints == "yes") {
                for (i in 1:nrow(data)) {
                  points(MGvar$X.Coords[i], MGvar$Y.Coords[i], 
                    type = "p", cex = pointcex, col = PTcolsindex[i], 
                    pch = pointshape)
                }
            }
            mtext(text = xlabel, side = 1, line = 1.9, adj = 0.5, 
                cex = 1, col = "black")
            mtext(text = ylabel, side = 2, line = 1.9, adj = 0.5, 
                cex = 1, col = "black")
            if (showleg == "yes") {
                legend("topleft", pch = 15, bty = "o", col = MGvar$ClasTabCols, 
                  legend = names(MGvar$ClasTabCols))
            }
            if (showreg == "yes") {
                regdat = MGvar$activedata
                if (MGvar$removedpoints) {
                  regdat = MGvar$removedpointsactivedata
                }
                X = data
                labels = colnames(regdat)
                var.names <- labels
                Z.info <- biplot.check.Z(regdat, FALSE)
                Z <- Z.info$X
                unscaled.Z <- Z.info$unscaled.X
                means <- Z.info$means
                sd <- Z.info$sd
                Z <- as.matrix(Z)
                Bmat <- solve(t(X) %*% X) %*% t(X) %*% Z
                Br <- t(Bmat)
                usr <- par("usr")
                numax <- ncol(Z)
                ax.style <- biplot.ax.control(numax, list(var.names))
                ax <- ax.style
                if (ax$type == "prediction") 
                  if (nrow(Br) > 1) 
                    axes.direction <- solve(diag(diag(Br %*% 
                      t(Br)))) %*% Br
                  else axes.direction <- (1/(Br %*% t(Br))) %*% 
                    Br
                else axes.direction <- Br
                z.axes <- lapply(1:length(ax$which), calibrate.axis, 
                  unscaled.Z, means, sd, axes.direction, ax$which, 
                  ax$ticks, ax$orthogx, ax$orthogy, ax$oblique)
                colrs = c()
                for (i in 1:ncol(regdat)) {
                  if (i%%7 == 0) {
                    num = 7
                  }
                  if (i%%7 != 0) {
                    num = i%%7
                  }
                  colrs[i] = brewer.pal(7, "Dark2")[num]
                }
                regcurves <- vector("list", ncol(regdat))
                for (i in 1:ncol(regdat)) {
                  nextrun = FALSE
                  if (length(MGvar$remAxcompindex) > 0) {
                    for (j in 1:length(MGvar$remAxcompindex)) {
                      if (i == MGvar$remAxcompindex[j]) {
                        nextrun = TRUE
                      }
                    }
                  }
                  if (nextrun) {
                    next
                  }
                  y = regdat[, i]
                  B = solve(t(X) %*% X) %*% t(X) %*% y
                  m = B[2]/B[1]
                  grandmax = max(Ymax, Xmax)
                  grandmin = min(Ymin, Xmin)
                  if (m > 1 || m < -1) {
                    y1 = grandmin * 2
                    y2 = grandmax * 2
                    x1 = y1/m
                    x2 = y2/m
                  }
                  if (m <= 1 && m >= -1) {
                    x1 = grandmin * 2
                    x2 = grandmax * 2
                    y1 = m * x1
                    y2 = m * x2
                  }
                  Xvals = c(x1, x2)
                  Yvals = c(y1, y2)
                  lines(Xvals, Yvals, col = colrs[i])
                  theta = (atan(m) * 57.2957795)
                  if (m > 1 || m < -1) {
                    text(x1/2, Ymin, labels[i], srt = theta, 
                      pos = 3, cex = 0.5, col = colrs[i])
                  }
                  if (m <= 1 && m >= -1) {
                    text(Xmin, y1/2, labels[i], srt = theta, 
                      pos = 3, cex = 0.5, col = colrs[i])
                  }
                  marker.mat <- z.axes[[i]][z.axes[[i]][, 4] == 
                    1, 1:3]
                  x.vals <- marker.mat[, 1]
                  y.vals <- marker.mat[, 2]
                  lin.coef <- coefficients(lm(y.vals ~ x.vals))
                  invals <- x.vals < usr[2] & x.vals > usr[1] & 
                    y.vals < usr[4] & y.vals > usr[3]
                  std.markers <- zapsmall(marker.mat[invals, 
                    3])
                  x.vals <- x.vals[invals]
                  y.vals <- y.vals[invals]
                  if (ax.style$tick.label[i]) 
                    label.on.off <- rep(1, sum(invals))
                  else rep(0, sum(invals))
                  if (!ax.style$tick.label[i]) 
                    label.on.off[c(1, length(label.on.off))] <- 1
                  apply(cbind(x.vals, y.vals, std.markers, label.on.off), 
                    1, .marker.func, coef = lin.coef, col = colrs[i], 
                    tick.size = ax.style$tick.size[i], side = ax.style$tick.label.side[i], 
                    pos = ax.style$tick.label.pos[i], offset = ax.style$tick.label.offset[i], 
                    label.col = ax.style$tick.label.col[i], cex = ax.style$tick.label.cex[i])
                }
            }
            if (showlabs == "yes") {
                if (showpoints == "no") {
                  for (i in 1:nrow(data)) {
                    text(MGvar$X.Coords[i], MGvar$Y.Coords[i], 
                      rownames(data)[i], cex = pointcex, col = PTcolsindex[i])
                  }
                }
                else {
                  for (i in 1:nrow(data)) {
                    text(MGvar$X.Coords[i], MGvar$Y.Coords[i], 
                      rownames(data)[i], cex = pointcex, pos = 3)
                  }
                }
            }
            if (showmeas == "yes") {
                mtext(text = Measure, side = 3, line = 2.4, adj = 0.01, 
                  cex = 0.7, col = "black")
            }
            MGvar$parPlotSize <<- par("plt")
            MGvar$usrCoords <<- par("usr")
            MGvar$labelsVec <<- rownames(data)
            MGvar$ZlabelsVec <<- rownames(zoomedcoords)
            if (length(MGvar$indexLabeled) > 0) {
                for (i in (1:length(MGvar$indexLabeled))) {
                  indexClosest <- MGvar$indexLabeled[i]
                  if (tabzoomswitch == "off") {
                    text(MGvar$X.Coords[indexClosest], MGvar$Y.Coords[indexClosest], 
                      labels = MGvar$labelsVec[indexClosest], 
                      pos = MGvar$GenSet.ILPos)
                  }
                  if (tabzoomswitch == "on") {
                    text(MGvar$X.Coords[indexClosest], MGvar$Y.Coords[indexClosest], 
                      labels = MGvar$ZlabelsVec[indexClosest], 
                      pos = MGvar$GenSet.ILPos)
                  }
                }
            }
            Shepindexmat <- matrix(0, nrow = nrow(MGvar$MDSmat), 
                ncol = nrow(MGvar$MDSmat))
            rownames(Shepindexmat) <- rownames(MGvar$MDSmat)
            colnames(Shepindexmat) <- rownames(MGvar$MDSmat)
            count = 1
            for (i in 1:(nrow(MGvar$MDSmat) - 1)) {
                for (j in (i + 1):nrow(MGvar$MDSmat)) {
                  Shepindexmat[i, j] = count
                  count = count + 1
                }
            }
            truepos = 0
            if (showdist == "yes") {
                if (length(MGvar$Shep.indexLabeled) > 0) {
                  cls = rainbow(length(MGvar$Shep.indexLabeled))
                  for (i in (1:length(MGvar$Shep.indexLabeled))) {
                    for (j in 1:length(MGvar$Shepx)) if (MGvar$Shep.indexLabeled[i] == 
                      MGvar$ShepPointindex[j, 1]) {
                      truepos = MGvar$ShepPointindex[j, 2]
                    }
                    for (k in 1:nrow(MGvar$MDSmat)) {
                      for (m in 1:nrow(MGvar$MDSmat)) {
                        if (Shepindexmat[k, m] == truepos) {
                          Shepobj1 = rownames(Shepindexmat)[k]
                          for (p in 1:nrow(MGvar$MDSmat)) {
                            if (Shepobj1 == rownames(MGvar$MDSmat)[p]) {
                              obj1x = data[p, 1]
                              obj1y = data[p, 2]
                            }
                          }
                          Shepobj2 = colnames(Shepindexmat)[m]
                          for (r in 1:nrow(MGvar$MDSmat)) {
                            if (Shepobj2 == rownames(MGvar$MDSmat)[r]) {
                              obj2x = data[r, 1]
                              obj2y = data[r, 2]
                            }
                          }
                          segments(obj1x, obj1y, obj2x, obj2y, 
                            col = cls[i])
                        }
                      }
                    }
                  }
                }
            }
            segments(MGvar$first.xCoord, MGvar$first.yCoord, 
                MGvar$first.xCoord, MGvar$latest.yCoord, col = "blue")
            segments(MGvar$first.xCoord, MGvar$first.yCoord, 
                MGvar$latest.xCoord, MGvar$first.yCoord, col = "blue")
            segments(MGvar$latest.xCoord, MGvar$first.yCoord, 
                MGvar$latest.xCoord, MGvar$latest.yCoord, col = "blue")
            segments(MGvar$first.xCoord, MGvar$latest.yCoord, 
                MGvar$latest.xCoord, MGvar$latest.yCoord, col = "blue")
        }
    }
    .marker.func <- function(vec, coef, col, tick.size, side, 
        pos, offset, label.col, cex) {
        x <- vec[1]
        y <- vec[2]
        marker.val <- vec[3]
        label.on.off <- vec[4]
        if (is.na(coef[2])) 
            .marker.label.cm(x, y, grad = "h", marker.val, expand = tick.size, 
                col = col, label.on.off = label.on.off, side = side, 
                pos = pos, offset = offset, label.col = label.col, 
                cex = cex)
        else if (coef[2] == 0) 
            .marker.label.cm(x, y, grad = "v", marker.val, expand = tick.size, 
                col = col, label.on.off = label.on.off, side = side, 
                pos = pos, offset = offset, label.col = label.col, 
                cex = cex)
        else .marker.label.cm(x, y, grad = -1/coef[2], marker.val, 
            expand = tick.size, col = col, label.on.off = label.on.off, 
            side = side, pos = pos, offset = offset, label.col = label.col, 
            cex = cex)
    }
    calibrate.axis <- function(j, unscaled.X, means, sd, axes.rows, 
        ax.which, ax.tickvec, ax.orthogxvec, ax.orthogyvec, ax.oblique) {
        ax.num <- ax.which[j]
        tick <- ax.tickvec[j]
        ax.direction <- axes.rows[j, ]
        r <- ncol(axes.rows)
        ax.orthog <- rbind(ax.orthogxvec, ax.orthogyvec)
        if (nrow(ax.orthog) < r) 
            ax.orthog <- rbind(ax.orthog, 0)
        if (nrow(axes.rows) > 1) 
            phi.vec <- diag(1/diag(axes.rows %*% t(axes.rows))) %*% 
                axes.rows %*% ax.orthog[, j]
        else phi.vec <- (1/(axes.rows %*% t(axes.rows))) %*% 
            axes.rows %*% ax.orthog[, j]
        number.points <- 100
        std.ax.tick.label <- pretty(unscaled.X[, ax.num], n = tick)
        std.range <- c(min(std.ax.tick.label), max(std.ax.tick.label))
        std.ax.tick.label.min <- std.ax.tick.label - (std.range[2] - 
            std.range[1])
        std.ax.tick.label.max <- std.ax.tick.label + (std.range[2] - 
            std.range[1])
        std.ax.tick.label <- c(std.ax.tick.label, std.ax.tick.label.min, 
            std.ax.tick.label.max)
        interval <- (std.ax.tick.label - means[ax.num])/sd[ax.num]
        axis.vals <- seq(from = min(interval), to = max(interval), 
            length = number.points)
        axis.vals <- sort(unique(c(axis.vals, interval)))
        number.points <- length(axis.vals)
        axis.points <- matrix(0, nrow = number.points, ncol = r)
        for (i in 1:r) axis.points[, i] <- ax.orthog[i, ax.num] + 
            (axis.vals - phi.vec[ax.num]) * ax.direction[i]
        axis.points <- cbind(axis.points, axis.vals * sd[ax.num] + 
            means[ax.num], 0)
        for (i in 1:number.points) if (any(zapsmall(axis.points[i, 
            r + 1] - std.ax.tick.label) == 0)) 
            axis.points[i, r + 2] <- 1
        axis.points
    }
    biplot.ax.control <- function(p, X.names, which = 1:p, type = "prediction", 
        col = "grey", lwd = 1, lty = 1, label = "Orthog", label.col = col, 
        label.cex = 0.75, label.dist = 0, ticks = 5, tick.col = col, 
        tick.size = 1, tick.label = T, tick.label.col = tick.col, 
        tick.label.cex = 0.6, tick.label.side = "left", tick.label.offset = 0.5, 
        tick.label.pos = 1, predict.col = col, predict.lwd = lwd, 
        predict.lty = lty, ax.names = X.names, rotate = NULL, 
        orthogx = 0, orthogy = 0, oblique = NULL) {
        if (!all(is.numeric(which))) 
            which <- match(which, X.names, nomatch = 0)
        which <- which[which <= p]
        which <- which[which > 0]
        ax.num <- length(which)
        if (type != "prediction" & type != "interpolation") 
            stop("Incorrect type of biplot axes specified")
        while (length(col) < ax.num) col <- c(col, col)
        col <- as.vector(col[1:ax.num])
        while (length(lwd) < ax.num) lwd <- c(lwd, lwd)
        lwd <- as.vector(lwd[1:ax.num])
        while (length(lty) < ax.num) lty <- c(lty, lty)
        lty <- as.vector(lty[1:ax.num])
        if (label != "Orthog" & label != "Hor" & label != "Paral") 
            stop("Incorrect specification of axis label direction")
        while (length(label.col) < ax.num) label.col <- c(label.col, 
            label.col)
        label.col <- as.vector(label.col[1:ax.num])
        while (length(label.cex) < ax.num) label.cex <- c(label.cex, 
            label.cex)
        label.cex <- as.vector(label.cex[1:ax.num])
        while (length(label.dist) < ax.num) label.dist <- c(label.dist, 
            label.dist)
        label.dist <- as.vector(label.dist[1:ax.num])
        while (length(ticks) < ax.num) ticks <- c(ticks, ticks)
        ticks <- as.vector(ticks[1:ax.num])
        while (length(tick.col) < ax.num) tick.col <- c(tick.col, 
            tick.col)
        tick.col <- as.vector(tick.col[1:ax.num])
        while (length(tick.size) < ax.num) tick.size <- c(tick.size, 
            tick.size)
        tick.size <- as.vector(tick.size[1:ax.num])
        while (length(tick.label) < ax.num) tick.label <- c(tick.label, 
            tick.label)
        tick.label <- as.vector(tick.label[1:ax.num])
        while (length(tick.label.col) < ax.num) tick.label.col <- c(tick.label.col, 
            tick.label.col)
        tick.label.col <- as.vector(tick.label.col[1:ax.num])
        while (length(tick.label.cex) < ax.num) tick.label.cex <- c(tick.label.cex, 
            tick.label.cex)
        tick.label.cex <- as.vector(tick.label.cex[1:ax.num])
        while (length(tick.label.side) < ax.num) tick.label.side <- c(tick.label.side, 
            tick.label.side)
        tick.label.side <- as.vector(tick.label.side[1:ax.num])
        while (length(tick.label.offset) < ax.num) tick.label.offset <- c(tick.label.offset, 
            tick.label.offset)
        tick.label.offset <- as.vector(tick.label.offset[1:ax.num])
        while (length(tick.label.pos) < ax.num) tick.label.pos <- c(tick.label.pos, 
            tick.label.pos)
        tick.label.pos <- as.vector(tick.label.pos[1:ax.num])
        while (length(predict.col) < ax.num) predict.col <- c(predict.col, 
            predict.col)
        predict.col <- as.vector(predict.col[1:ax.num])
        while (length(predict.lwd) < ax.num) predict.lwd <- c(predict.lwd, 
            predict.lwd)
        predict.lwd <- as.vector(predict.lwd[1:ax.num])
        while (length(predict.lty) < ax.num) predict.lty <- c(predict.lty, 
            predict.lty)
        predict.lty <- as.vector(predict.lty[1:ax.num])
        ax.names <- ax.names[which]
        while (length(ax.names) < p) ax.names <- c(ax.names, 
            "")
        ax.names <- as.vector(ax.names[1:ax.num])
        if (!is.null(oblique)) 
            if (length(oblique) != p) 
                stop("For oblique translations values must be specified for each variable")
        while (length(orthogx) < p) orthogx <- c(orthogx, orthogx)
        orthogx <- as.vector(orthogx[1:p])
        while (length(orthogy) < p) orthogy <- c(orthogy, orthogy)
        orthogy <- as.vector(orthogy[1:p])
        list(which = which, type = type, col = col, lwd = lwd, 
            lty = lty, label = label, label.col = label.col, 
            label.cex = label.cex, label.dist = label.dist, ticks = ticks, 
            tick.col = tick.col, tick.size = tick.size, tick.label = tick.label, 
            tick.label.col = tick.label.col, tick.label.cex = tick.label.cex, 
            tick.label.side = tick.label.side, tick.label.offset = tick.label.offset, 
            tick.label.pos = tick.label.pos, predict.col = predict.col, 
            predict.lty = predict.lty, predict.lwd = predict.lwd, 
            names = ax.names, rotate = rotate, orthogx = orthogx, 
            orthogy = orthogy, oblique = oblique)
    }
    biplot.check.Z <- function(X, scaled.mat) {
        X <- as.matrix(X)
        unscaled.X <- X
        means <- apply(X, 2, mean)
        sd <- sqrt(apply(X, 2, var))
        if (scaled.mat) 
            X <- scale(X)
        else {
            X <- scale(X, scale = FALSE)
            sd <- rep(1, ncol(X))
        }
        if (is.null(dimnames(X))) 
            dimnames(X) <- list(paste(1:nrow(X)), paste("V", 
                1:ncol(X), sep = ""))
        if (length(dimnames(X)[[1]]) == 0) 
            dimnames(X)[[1]] <- paste(1:nrow(X))
        if (length(dimnames(X)[[2]]) == 0) 
            dimnames(X)[[2]] <- paste("V", 1:ncol(X), sep = "")
        list(X = X, unscaled.X = unscaled.X, means = means, sd = sd)
    }
    .marker.label.cm <- function(x, y, grad, marker.val, expand = 1, 
        col, label.on.off, side, pos, offset, label.col, cex) {
        usr <- par("usr")
        uin <- par("pin")/c(usr[2] - usr[1], usr[4] - usr[3])
        mm <- 1/(uin[1] * 25.4)
        d <- expand * mm
        if (grad == "v") {
            lines(rep(x, 2), c(y - d, y + d), col = col)
            if (label.on.off == 1) 
                text(x, y - d, label = marker.val, pos = pos, 
                  offset = offset, col = label.col, cex = cex)
        }
        if (grad == "h") {
            lines(c(x - d, x + d), rep(y, 2), col = col)
            if (label.on.off == 1) 
                if (side == "right") 
                  text(x + d, y, label = marker.val, pos = pos, 
                    offset = offset, col = label.col, cex = cex)
                else text(x - d, y, label = marker.val, pos = pos, 
                  offset = offset, col = label.col, cex = cex)
        }
        if (is.numeric(grad)) {
            b <- d * sqrt(1/(1 + grad * grad))
            a <- b * grad
            lines(c(x - b, x + b), c(y - a, y + a), col = col)
            if (label.on.off == 1) 
                if (side == "right") 
                  text(x + b, y + a, label = marker.val, pos = pos, 
                    offset = offset, col = label.col, cex = cex)
                else text(x - b, y - a, label = marker.val, pos = pos, 
                  offset = offset, col = label.col, cex = cex)
        }
    }
    labelClosestPoint <- function(xClick, yClick, imgXcoords, 
        imgYcoords) {
        squared.Distance.P <- (xClick - imgXcoords)^2 + (yClick - 
            imgYcoords)^2
        indexClosest <- which.min(squared.Distance.P)
        MGvar$indexLabeled <<- c(MGvar$indexLabeled, indexClosest)
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab1") {
            MGvar$indexLabeled.T1 <<- c(MGvar$indexLabeled.T1, 
                indexClosest)
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab2") {
            MGvar$indexLabeled.T2 <<- c(MGvar$indexLabeled.T2, 
                indexClosest)
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab3") {
            MGvar$indexLabeled.T3 <<- c(MGvar$indexLabeled.T3, 
                indexClosest)
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab4") {
            MGvar$indexLabeled.T4 <<- c(MGvar$indexLabeled.T4, 
                indexClosest)
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab5") {
            MGvar$indexLabeled.T5 <<- c(MGvar$indexLabeled.T5, 
                indexClosest)
        }
        tabplot()
    }
    OnPlotLeftClick <- function(x, y) {
        xClick <- x
        yClick <- y
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab1") {
            width <- as.numeric(tclvalue(tkwinfo("reqwidth", 
                img)))
            height <- as.numeric(tclvalue(tkwinfo("reqheight", 
                img)))
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab2") {
            width <- as.numeric(tclvalue(tkwinfo("reqwidth", 
                img2)))
            height <- as.numeric(tclvalue(tkwinfo("reqheight", 
                img2)))
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab3") {
            width <- as.numeric(tclvalue(tkwinfo("reqwidth", 
                img3)))
            height <- as.numeric(tclvalue(tkwinfo("reqheight", 
                img3)))
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab4") {
            width <- as.numeric(tclvalue(tkwinfo("reqwidth", 
                img4)))
            height <- as.numeric(tclvalue(tkwinfo("reqheight", 
                img4)))
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab5") {
            width <- as.numeric(tclvalue(tkwinfo("reqwidth", 
                img5)))
            height <- as.numeric(tclvalue(tkwinfo("reqheight", 
                img5)))
        }
        xMin <- MGvar$parPlotSize[1] * width
        xMax <- MGvar$parPlotSize[2] * width
        yMin <- MGvar$parPlotSize[3] * height
        yMax <- MGvar$parPlotSize[4] * height
        rangeX <- MGvar$usrCoords[2] - MGvar$usrCoords[1]
        rangeY <- MGvar$usrCoords[4] - MGvar$usrCoords[3]
        imgXcoords <- (MGvar$X.Coords - MGvar$usrCoords[1]) * 
            (xMax - xMin)/rangeX + xMin
        imgYcoords <- (MGvar$Y.Coords - MGvar$usrCoords[3]) * 
            (yMax - yMin)/rangeY + yMin
        xClick <- as.numeric(xClick) + 0.5
        yClick <- as.numeric(yClick) + 0.5
        yClick <- height - yClick
        xPlotCoord <- MGvar$usrCoords[1] + (xClick - xMin) * 
            rangeX/(xMax - xMin)
        yPlotCoord <- MGvar$usrCoords[3] + (yClick - yMin) * 
            rangeY/(yMax - yMin)
        labelClosestPoint(xClick, yClick, imgXcoords, imgYcoords)
    }
    LabelSpecificPoint <- function() {
        Labtt = tktoplevel()
        tkwm.resizable(Labtt, "0", "0")
        tkwm.deiconify(Labtt)
        tkwm.title(Labtt, "Point Label")
        tkwm.geometry(Labtt, "280x100")
        LabCanvas = tkcanvas(Labtt, width = 280, height = 100, 
            bg = col.sec)
        tkplace(LabCanvas, relx = 0, `in` = Labtt)
        frameLab <- tkwidget(Labtt, "TitleFrame", text = "Label a Specific Point", 
            background = "white")
        tkplace(frameLab, relx = 0.02, rely = 0.02, relwidth = 0.96, 
            relheight = 0.96, `in` = Labtt)
        tkplace(tklabel(frameLab, text = "Choose the Point Name", 
            background = "white"), relx = 0.05, rely = 0.3, `in` = frameLab)
        objnames = rownames(MGvar$activedata)
        LabInput.val = tclVar(objnames[1])
        LabInput.ComboBox <- tkwidget(Labtt, "ComboBox", editable = FALSE, 
            values = objnames, width = 10, textvariable = LabInput.val)
        tkplace(LabInput.ComboBox, relx = 0.6, rely = 0.3, `in` = frameLab)
        On.Enter <- function() {
            Lab = as.character(tclvalue(LabInput.val))
            datlength = nrow(MGvar$MDSmat)
            indexlength = length(MGvar$indexLabeled)
            pointpos = 0
            for (i in 1:datlength) {
                if (rownames(MGvar$MDSmat)[i] == Lab) {
                  pointpos = i
                }
            }
            if (pointpos == 0) {
                tkmessageBox(title = "Point Label Error", message = "The name does not match any of the points. \nPlease check spelling", 
                  icon = "error", type = "ok")
            }
            if (pointpos > 0) {
                MGvar$indexLabeled[indexlength + 1] <<- pointpos
                names(MGvar$indexLabeled)[indexlength + 1] <<- rownames(MGvar$MDSmat)[pointpos]
                if (tclvalue(MGvar$ActivePlottingTab) == "Tab1") {
                  MGvar$indexLabeled.T1 <<- c(MGvar$indexLabeled.T1, 
                    MGvar$indexLabeled[indexlength + 1])
                }
                if (tclvalue(MGvar$ActivePlottingTab) == "Tab2") {
                  MGvar$indexLabeled.T2 <<- c(MGvar$indexLabeled.T2, 
                    MGvar$indexLabeled[indexlength + 1])
                }
                if (tclvalue(MGvar$ActivePlottingTab) == "Tab3") {
                  MGvar$indexLabeled.T3 <<- c(MGvar$indexLabeled.T3, 
                    MGvar$indexLabeled[indexlength + 1])
                }
                if (tclvalue(MGvar$ActivePlottingTab) == "Tab4") {
                  MGvar$indexLabeled.T4 <<- c(MGvar$indexLabeled.T4, 
                    MGvar$indexLabeled[indexlength + 1])
                }
                if (tclvalue(MGvar$ActivePlottingTab) == "Tab5") {
                  MGvar$indexLabeled.T5 <<- c(MGvar$indexLabeled.T5, 
                    MGvar$indexLabeled[indexlength + 1])
                }
            }
            tabplot()
            tkdestroy(Labtt)
        }
        tkplace(tkbutton(Labtt, text = "Enter", width = 15, command = function() On.Enter()), 
            relx = 0.3, rely = 0.7, `in` = frameLab)
        tkfocus(Labtt)
        tkbind(Labtt, "<Return>", On.Enter)
    }
    ChangePointCol <- function() {
        MGcomp$CPCol <<- tktoplevel()
        tkwm.resizable(MGcomp$CPCol, "0", "0")
        tkwm.title(MGcomp$CPCol, "Choose Point")
        tkwm.geometry(MGcomp$CPCol, "280x90")
        CPColcanvas = tkcanvas(MGcomp$CPCol, width = 300, height = 120, 
            bg = col.sec)
        tkplace(CPColcanvas, relx = 0, rely = 0, `in` = MGcomp$CPCol)
        frameCPC <- tkwidget(MGcomp$CPCol, "TitleFrame", text = "Active Cursor", 
            background = "white")
        tkplace(frameCPC, relx = 0.05, rely = 0.05, relheight = 0.9, 
            relwidth = 0.9, `in` = MGcomp$CPCol)
        tkplace(tklabel(frameCPC, text = "The cursor is now active. Please\nuse the cursor to select the point\nwhose colour you wish to change.", 
            background = "white"), relx = 0.1, rely = 0.2, `in` = frameCPC)
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab1") {
            tkbind(img, "<Button-1>", GetCoordsLeftClick.PointCol)
            tkconfigure(img, cursor = "crosshair")
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab2") {
            tkbind(img2, "<Button-1>", GetCoordsLeftClick.PointCol)
            tkconfigure(img2, cursor = "crosshair")
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab3") {
            tkbind(img3, "<Button-1>", GetCoordsLeftClick.PointCol)
            tkconfigure(img3, cursor = "crosshair")
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab4") {
            tkbind(img4, "<Button-1>", GetCoordsLeftClick.PointCol)
            tkconfigure(img4, cursor = "crosshair")
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab5") {
            tkbind(img5, "<Button-1>", GetCoordsLeftClick.PointCol)
            tkconfigure(img5, cursor = "crosshair")
        }
        tkwait.window(MGcomp$CPCol)
        ActiveArrowCursor()
    }
    GetClosestPointChangeCol <- function(xClick, yClick, imgXcoords, 
        imgYcoords) {
        squared.Distance <- (xClick - imgXcoords)^2 + (yClick - 
            imgYcoords)^2
        Closest <- which.min(squared.Distance)
        PCol <- tktoplevel()
        tkwm.resizable(PCol, "0", "0")
        tkwm.title(PCol, "Point Colour")
        tkwm.geometry(PCol, "250x90")
        PColcanvas = tkcanvas(PCol, width = 300, height = 120, 
            bg = col.sec)
        tkplace(PColcanvas, relx = 0, rely = 0, `in` = PCol)
        framePC <- tkwidget(PCol, "TitleFrame", text = "Choose Point Colour", 
            background = "white")
        tkplace(framePC, relx = 0.05, rely = 0.05, relheight = 0.9, 
            relwidth = 0.9, `in` = PCol)
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab1") {
            ptcol <- MGvar$activeplot.pointcol.T1
            ptcol.temp <- MGvar$activeplot.pointcol.T1
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab2") {
            ptcol <- MGvar$activeplot.pointcol.T2
            ptcol.temp <- MGvar$activeplot.pointcol.T2
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab3") {
            ptcol <- MGvar$activeplot.pointcol.T3
            ptcol.temp <- MGvar$activeplot.pointcol.T3
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab4") {
            ptcol <- MGvar$activeplot.pointcol.T4
            ptcol.temp <- MGvar$activeplot.pointcol.T4
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab5") {
            ptcol <- MGvar$activeplot.pointcol.T5
            ptcol.temp <- MGvar$activeplot.pointcol.T5
        }
        tkplace(tklabel(framePC, text = paste(rownames(MGvar$MDSmat)[Closest]), 
            background = "white"), relx = 0.1, rely = 0.35, `in` = framePC)
        ChangePtCol <- function() {
            ptcol.temp <<- tclvalue(.Tcl(paste("tk_chooseColor", 
                .Tcl.args(initialcolor = ptcol.temp, title = "Choose a Colour"))))
            if (nchar(ptcol.temp) > 0) 
                tkconfigure(Ptcol.but, bg = ptcol.temp)
            ptcol <<- ptcol.temp
            tkdestroy(PCol)
        }
        Ptcol.but <- tkbutton(PCol, text = "", width = 2, height = 1, 
            bg = ptcol, command = function() ChangePtCol())
        tkplace(Ptcol.but, relx = 0.8, rely = 0.35, `in` = framePC)
        tkwait.window(PCol)
        MGvar$MDSmat.Cols[Closest] <<- ptcol
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab1") {
            MGvar$MDSmat.Cols.T1[Closest] <<- ptcol
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab2") {
            MGvar$MDSmat.Cols.T2[Closest] <<- ptcol
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab3") {
            MGvar$MDSmat.Cols.T3[Closest] <<- ptcol
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab4") {
            MGvar$MDSmat.Cols.T4[Closest] <<- ptcol
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab5") {
            MGvar$MDSmat.Cols.T5[Closest] <<- ptcol
        }
        tabplot()
    }
    GetCoordsLeftClick.PointCol <- function(x, y) {
        xClick <- x
        yClick <- y
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab1") {
            width <- as.numeric(tclvalue(tkwinfo("reqwidth", 
                img)))
            height <- as.numeric(tclvalue(tkwinfo("reqheight", 
                img)))
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab2") {
            width <- as.numeric(tclvalue(tkwinfo("reqwidth", 
                img2)))
            height <- as.numeric(tclvalue(tkwinfo("reqheight", 
                img2)))
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab3") {
            width <- as.numeric(tclvalue(tkwinfo("reqwidth", 
                img3)))
            height <- as.numeric(tclvalue(tkwinfo("reqheight", 
                img3)))
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab4") {
            width <- as.numeric(tclvalue(tkwinfo("reqwidth", 
                img4)))
            height <- as.numeric(tclvalue(tkwinfo("reqheight", 
                img4)))
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab5") {
            width <- as.numeric(tclvalue(tkwinfo("reqwidth", 
                img5)))
            height <- as.numeric(tclvalue(tkwinfo("reqheight", 
                img5)))
        }
        xMin <- MGvar$parPlotSize[1] * width
        xMax <- MGvar$parPlotSize[2] * width
        yMin <- MGvar$parPlotSize[3] * height
        yMax <- MGvar$parPlotSize[4] * height
        rangeX <- MGvar$usrCoords[2] - MGvar$usrCoords[1]
        rangeY <- MGvar$usrCoords[4] - MGvar$usrCoords[3]
        imgXcoords <- (MGvar$MDSmat[, 1] - MGvar$usrCoords[1]) * 
            (xMax - xMin)/rangeX + xMin
        imgYcoords <- (MGvar$MDSmat[, 2] - MGvar$usrCoords[3]) * 
            (yMax - yMin)/rangeY + yMin
        xClick <- as.numeric(xClick) + 0.5
        yClick <- as.numeric(yClick) + 0.5
        yClick <- height - yClick
        xPlotCoord <- MGvar$usrCoords[1] + (xClick - xMin) * 
            rangeX/(xMax - xMin)
        yPlotCoord <- MGvar$usrCoords[3] + (yClick - yMin) * 
            rangeY/(yMax - yMin)
        GetClosestPointChangeCol(xClick, yClick, imgXcoords, 
            imgYcoords)
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab1") {
            tkbind(img, "<Button-1>", OnPlotLeftClick)
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab2") {
            tkbind(img2, "<Button-1>", OnPlotLeftClick)
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab3") {
            tkbind(img3, "<Button-1>", OnPlotLeftClick)
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab4") {
            tkbind(img4, "<Button-1>", OnPlotLeftClick)
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab5") {
            tkbind(img5, "<Button-1>", OnPlotLeftClick)
        }
        tkdestroy(MGcomp$CPCol)
    }
    EnlargedActivePlot <- function() {
        ReusePOW()
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab1") {
            MGvar$EnActivePlot.switch.T1 <<- "on"
            MGvar$EnActivePlot.switch.T2 <<- "off"
            MGvar$EnActivePlot.switch.T3 <<- "off"
            MGvar$EnActivePlot.switch.T4 <<- "off"
            MGvar$EnActivePlot.switch.T5 <<- "off"
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab2") {
            MGvar$EnActivePlot.switch.T1 <<- "off"
            MGvar$EnActivePlot.switch.T2 <<- "on"
            MGvar$EnActivePlot.switch.T3 <<- "off"
            MGvar$EnActivePlot.switch.T4 <<- "off"
            MGvar$EnActivePlot.switch.T5 <<- "off"
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab3") {
            MGvar$EnActivePlot.switch.T1 <<- "off"
            MGvar$EnActivePlot.switch.T2 <<- "off"
            MGvar$EnActivePlot.switch.T3 <<- "on"
            MGvar$EnActivePlot.switch.T4 <<- "off"
            MGvar$EnActivePlot.switch.T5 <<- "off"
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab4") {
            MGvar$EnActivePlot.switch.T1 <<- "off"
            MGvar$EnActivePlot.switch.T2 <<- "off"
            MGvar$EnActivePlot.switch.T3 <<- "off"
            MGvar$EnActivePlot.switch.T4 <<- "on"
            MGvar$EnActivePlot.switch.T5 <<- "off"
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab5") {
            MGvar$EnActivePlot.switch.T1 <<- "off"
            MGvar$EnActivePlot.switch.T2 <<- "off"
            MGvar$EnActivePlot.switch.T3 <<- "off"
            MGvar$EnActivePlot.switch.T4 <<- "off"
            MGvar$EnActivePlot.switch.T5 <<- "on"
        }
        MGcomp$EActive <<- tktoplevel()
        tkwm.title(MGcomp$EActive, "Enlarged Active Plot")
        tkwm.geometry(MGcomp$EActive, "650x650")
        EActiveCanvas <- tkcanvas(MGcomp$EActive, width = 650, 
            height = 650, bg = col.sec)
        tkplace(EActiveCanvas, `in` = MGcomp$EActive)
        EC.height <- as.numeric(tclvalue(tkwinfo("height", MGcomp$EActive)))
        EC.width <- as.numeric(tclvalue(tkwinfo("width", MGcomp$EActive)))
        WidthScale = 650/1.5
        POhscale <- EC.width/WidthScale
        dimrat = 1.5/1.4
        POvscale <- POhscale/dimrat
        MGcomp$POimg <<- tkrplot(MGcomp$EActive, function() plotting2D(MGvar$MDSmat, 
            indexLabeled = MGvar$indexLabeled), hscale = POhscale, 
            vscale = POvscale)
        tkplace(MGcomp$POimg, relx = 0.05, rely = 0.02, relwidth = 0.9, 
            `in` = MGcomp$EActive)
        tabplot()
        tkbind(MGcomp$POimg, "<Button-1>", OnPOPlotLeftClick)
        tkconfigure(MGcomp$POimg, cursor = "hand2")
        CopyAPToClip <- function() {
            tkrreplot(MGcomp$POimg)
        }
        tkplace(tkbutton(MGcomp$EActive, text = "Copy to Clipboard", 
            width = 20, command = function() CopyAPToClip()), 
            relx = 0.19, rely = 0.93, `in` = MGcomp$EActive)
        tkplace(tkbutton(MGcomp$EActive, text = "Plot Options", 
            width = 20, command = function() ConfPlotOptions()), 
            relx = 0.6, rely = 0.93, `in` = MGcomp$EActive)
        tkbind(MGcomp$EActive, "<Destroy>", function() {
            if (tclvalue(MGvar$ActivePlottingTab) == "Tab1") {
                MGvar$EnActivePlot.switch.T1 <<- "off"
            }
            if (tclvalue(MGvar$ActivePlottingTab) == "Tab2") {
                MGvar$EnActivePlot.switch.T2 <<- "off"
            }
            if (tclvalue(MGvar$ActivePlottingTab) == "Tab3") {
                MGvar$EnActivePlot.switch.T3 <<- "off"
            }
            if (tclvalue(MGvar$ActivePlottingTab) == "Tab4") {
                MGvar$EnActivePlot.switch.T4 <<- "off"
            }
            if (tclvalue(MGvar$ActivePlottingTab) == "Tab5") {
                MGvar$EnActivePlot.switch.T5 <<- "off"
            }
        })
        MainPlotPOPMenu <- tkmenu(MGcomp$POimg, tearoff = FALSE)
        tkadd(MainPlotPOPMenu, "command", label = "Clear Added Point Labels", 
            command = ClearMainPOPPoints)
        tkadd(MainPlotPOPMenu, "command", label = "Label Specific Point", 
            command = LabelSpecificPoint)
        RightClickMainPOP <- function(x, y) {
            rootx <- as.integer(tkwinfo("rootx", MGcomp$POimg))
            rooty <- as.integer(tkwinfo("rooty", MGcomp$POimg))
            xTxt <- as.integer(x) + rootx
            yTxt <- as.integer(y) + rooty
            tcl("tk_popup", MainPlotPOPMenu, xTxt, yTxt)
        }
        tkbind(MGcomp$POimg, "<Button-3>", RightClickMainPOP)
        tkbind(MGcomp$EActive, "<Configure>", resize.EConf)
    }
    resize.EConf <- function() {
        EC.height <- as.numeric(tclvalue(tkwinfo("height", MGcomp$EActive)))
        EC.width <- as.numeric(tclvalue(tkwinfo("width", MGcomp$EActive)))
        WidthScale = 650/1.5
        EShscale <- EC.width/WidthScale
        dimrat = 1.5/1.4
        ESvscale <- EShscale/dimrat
        tkrreplot(MGcomp$POimg, hscale = EShscale, vscale = ESvscale)
    }
    ClearMainPOPPoints <- function() {
        MGvar$indexLabeled <<- c()
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab1") {
            MGvar$indexLabeled.T1 <<- c()
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab2") {
            MGvar$indexLabeled.T2 <<- c()
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab3") {
            MGvar$indexLabeled.T3 <<- c()
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab4") {
            MGvar$indexLabeled.T4 <<- c()
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab5") {
            MGvar$indexLabeled.T5 <<- c()
        }
        tkrreplot(MGcomp$POimg)
        tabplot()
    }
    OnPOPlotLeftClick <- function(x, y) {
        xClick <- x
        yClick <- y
        width <- as.numeric(tclvalue(tkwinfo("reqwidth", MGcomp$POimg)))
        height <- as.numeric(tclvalue(tkwinfo("reqheight", MGcomp$POimg)))
        xMin <- MGvar$parPlotSize[1] * width
        xMax <- MGvar$parPlotSize[2] * width
        yMin <- MGvar$parPlotSize[3] * height
        yMax <- MGvar$parPlotSize[4] * height
        rangeX <- MGvar$usrCoords[2] - MGvar$usrCoords[1]
        rangeY <- MGvar$usrCoords[4] - MGvar$usrCoords[3]
        imgXcoords <- (MGvar$X.Coords - MGvar$usrCoords[1]) * 
            (xMax - xMin)/rangeX + xMin
        imgYcoords <- (MGvar$Y.Coords - MGvar$usrCoords[3]) * 
            (yMax - yMin)/rangeY + yMin
        xClick <- as.numeric(xClick) + 0.5
        yClick <- as.numeric(yClick) + 0.5
        yClick <- height - yClick
        xPlotCoord <- MGvar$usrCoords[1] + (xClick - xMin) * 
            rangeX/(xMax - xMin)
        yPlotCoord <- MGvar$usrCoords[3] + (yClick - yMin) * 
            rangeY/(yMax - yMin)
        msg <- paste("Label the point closest to these approximate plot coordinates: \n", 
            "x =", format(xPlotCoord, digits = 2), ",y =", format(yPlotCoord, 
                digits = 2), "?")
        mbval <- tkmessageBox(title = "Label Point Closest to These Approximate Plot Coordinates", 
            message = msg, type = "yesno", icon = "question")
        if (tclvalue(mbval) == "yes") 
            labelClosestPoint(xClick, yClick, imgXcoords, imgYcoords)
    }
    plotting3D <- function(data, title = MGvar$rglplot.title, 
        showtitle = MGvar$rglplot.title.show, xlabel = MGvar$rglplot.xlab, 
        ylabel = MGvar$rglplot.ylab, zlabel = MGvar$rglplot.zlab, 
        showpoints = MGvar$rglplot.showpoints, showlabels = MGvar$rglplot.showlabels, 
        colour = MGvar$rglplot.ptcol, ptsize = MGvar$rglplot.ptsize, 
        axmeas = MGvar$rglplot.axmeas) {
        if (showtitle == "yes") {
            graphtitle = title
        }
        if (showtitle == "no") {
            graphtitle = ""
        }
        if (showpoints == "yes") {
            pointtype = "p"
        }
        if (showpoints == "no") {
            pointtype = "n"
        }
        if (axmeas == "yes") {
            AM = TRUE
        }
        if (axmeas == "no") {
            AM = FALSE
        }
        plot3d(data, aspect = TRUE, type = pointtype, col = colour, 
            size = ptsize, xlab = "", ylab = "", zlab = "", axes = AM)
        if (showlabels == "yes") {
            for (i in 1:nrow(data)) {
                text3d(data[i, ], texts = rownames(data)[i], 
                  col = MGvar$MDSmat.Cols[i], adj = c(0, 1), 
                  cex = 1)
            }
        }
        decorate3d(main = MGvar$sthreeDplot.title, xlab = xlabel, 
            ylab = ylabel, zlab = zlabel, axes = AM)
    }
    plotting3Dstatic <- function(data, title = MGvar$sthreeDplot.title, 
        Measure = MGvar$dMeas, showtitle = MGvar$sthreeDplot.title.show, 
        showmeas = MGvar$sthreeDplot.distmeas, xlabel = MGvar$sthreeDplot.xlab, 
        ylabel = MGvar$sthreeDplot.ylab, zlabel = MGvar$sthreeDplot.zlab, 
        showleg = MGvar$sthreeDplot.leg.show, bgcol = MGvar$sthreeDplot.bg, 
        showpoints = MGvar$sthreeDplot.showpoints, showlabs = MGvar$sthreeDplot.showlabels, 
        pointcex = MGvar$sthreeDplot.cex, pointshape = MGvar$sthreeDplot.type, 
        pointcol = MGvar$sthreeDplot.pointcol, showregX = MGvar$sthreeDplot.showregX, 
        regXcol = MGvar$sthreeDplot.regXcol, showregZ = MGvar$sthreeDplot.showregZ, 
        regZcol = MGvar$sthreeDplot.regZcol, showregY = MGvar$sthreeDplot.showregY, 
        regYcol = MGvar$sthreeDplot.regYcol, showaxes = MGvar$sthreeDplot.showaxes, 
        axcol = MGvar$sthreeDplot.axescol, showgrid = MGvar$sthreeDplot.showgrid, 
        Ang = MGvar$sthreeDplot.angle, HL = MGvar$sthreeDplot.HL, 
        yscale = MGvar$sthreeDplot.yscale) {
        if (showtitle == "yes") {
            graphtitle = title
        }
        if (showtitle == "no") {
            graphtitle = ""
        }
        if (showmeas == "yes") {
            distanceMeasure = MGvar$dMeas
        }
        if (showmeas == "no") {
            distanceMeasure = ""
        }
        if (showpoints == "yes") {
            pointtype = "p"
        }
        if (showpoints == "no") {
            pointtype = "n"
        }
        if (showaxes == "yes") {
            tdbox = TRUE
        }
        if (showaxes == "no") {
            tdbox = FALSE
        }
        if (showgrid == "yes") {
            sgrid = TRUE
        }
        if (showgrid == "no") {
            sgrid = FALSE
        }
        if (HL == "yes") {
            HLight = TRUE
        }
        if (HL == "no") {
            HLight = FALSE
        }
        par(mar = c(3, 3, 3, 3))
        par(cex.axis = 0.8)
        params <- par(bg = bgcol)
        if (nrow(data) == 1 && ncol(data) == 1) {
            data = matrix(0, ncol = 2)
            scatterplot3d(data, type = "n")
            par(params)
        }
        else {
            if (!HLight) {
                statplot = scatterplot3d(data[, 1], data[, 2], 
                  data[, 3], type = pointtype, xlab = xlabel, 
                  ylab = ylabel, zlab = zlabel, main = graphtitle, 
                  pch = pointshape, if (!HLight) {
                    color = pointcol
                  }, cex.symbols = pointcex, box = tdbox, col.axis = axcol, 
                  grid = sgrid, angle = Ang, highlight.3d = HLight, 
                  scale.y = yscale)
            }
            if (HLight) {
                statplot = scatterplot3d(data[, 1], data[, 2], 
                  data[, 3], type = pointtype, xlab = xlabel, 
                  ylab = ylabel, zlab = zlabel, main = graphtitle, 
                  pch = pointshape, cex.symbols = pointcex, box = tdbox, 
                  col.axis = axcol, grid = sgrid, angle = Ang, 
                  highlight.3d = HLight, scale.y = yscale)
            }
            statplot.coords <- statplot$xyz.convert(data[, 1], 
                data[, 2], data[, 3])
            if (showlabs == "yes" && showpoints == "no") {
                for (i in 1:nrow(data)) {
                  text(statplot.coords$x[i], statplot.coords$y[i], 
                    labels = rownames(data)[i], cex = pointcex, 
                    col = MGvar$MDSmat.Cols[i])
                }
            }
            if (showlabs == "yes" && showpoints == "yes") {
                for (i in 1:nrow(data)) {
                  text(statplot.coords$x[i], statplot.coords$y[i], 
                    labels = rownames(data)[i], cex = 0.6 * pointcex, 
                    col = MGvar$MDSmat.Cols[i])
                }
            }
            par(params)
            if (showmeas == "yes") {
                mtext(text = Measure, side = 3, line = 2.8, adj = 0, 
                  cex = 0.7, col = "black")
            }
            if (showregX == "yes") {
            }
            if (showregY == "yes") {
            }
            if (showregZ == "yes") {
            }
        }
    }
    EnlargedStat3DPlot <- function() {
        ReusePOW()
        MGvar$EStat.switch <<- "on"
        MGcomp$EStat <<- tktoplevel()
        tkwm.title(MGcomp$EStat, "Enlarged Static 3D Plot")
        tkwm.geometry(MGcomp$EStat, "650x650")
        EStatCanvas <- tkcanvas(MGcomp$EStat, width = 650, height = 650, 
            bg = col.sec)
        tkplace(EStatCanvas, `in` = MGcomp$EStat)
        POhscale <- 1.5
        POvscale <- 1.4
        MGcomp$POstatimg <<- tkrplot(MGcomp$EStat, function() plotting3Dstatic(MGvar$MDSmat), 
            hscale = POhscale, vscale = POvscale)
        tkplace(MGcomp$POstatimg, relx = 0.05, rely = 0.02, relwidth = 0.9, 
            `in` = MGcomp$EStat)
        CopyToClip <- function() {
            tkrreplot(MGcomp$POstatimg)
        }
        tkplace(tkbutton(MGcomp$EStat, text = "Copy to Clipboard", 
            width = 20, command = function() tkrreplot(MGcomp$POstatimg)), 
            relx = 0.19, rely = 0.93, `in` = MGcomp$EStat)
        tkplace(tkbutton(MGcomp$EStat, text = "Plot Options", 
            width = 20, command = function() threeDPlotOptions()), 
            relx = 0.6, rely = 0.93, `in` = MGcomp$EStat)
        tkbind(MGcomp$EStat, "<Configure>", resize.EStat)
    }
    resize.EStat <- function() {
        ESta.height <- as.numeric(tclvalue(tkwinfo("height", 
            MGcomp$EStat)))
        ESta.width <- as.numeric(tclvalue(tkwinfo("width", MGcomp$EStat)))
        WidthScale = 650/1.5
        EShscale <- ESta.width/WidthScale
        dimrat = 1.5/1.4
        ESvscale <- EShscale/dimrat
        tkrreplot(MGcomp$POstatimg, hscale = EShscale, vscale = ESvscale)
    }
    plotShepard <- function(shepdists, conf, showtitle = MGvar$shepplot.title.show, 
        showlabs = MGvar$shepplot.labs.show, showleg = MGvar$shepplot.leg.show, 
        bgcol = MGvar$shepplot.bg, showpoints = MGvar$shepplot.showpoints, 
        pointcex = MGvar$shepplot.cex, pointshape = MGvar$shepplot.type, 
        pointcol = MGvar$shepplot.pointcol, showcurve = MGvar$shepplot.curve.show, 
        curvetype = MGvar$shepplot.curve.type, curvecol = MGvar$shepplot.curvecol, 
        xmeas = MGvar$shepplot.Axes.xaxt, bold = MGvar$shepplot.bold, 
        ymeas = MGvar$shepplot.Axes.yaxt, axcol = MGvar$shepplot.Axescol, 
        Tab = tclvalue(MGvar$ActivePlottingTab), showplabs = MGvar$shepplot.showlabels) {
        if (showtitle == "yes") {
            MGvar$activeshepplot.title <<- paste("Shepard Plot for", 
                Tab)
            graphtitle <- MGvar$activeshepplot.title
        }
        if (showtitle == "no") {
            graphtitle <- ""
        }
        if (showpoints == "yes") {
            pointtype = "p"
        }
        if (showpoints == "no") {
            pointtype = "n"
        }
        par(mar = c(3, 3, 2, 5))
        params <- par(bg = bgcol)
        if (nrow(conf) == 1 && ncol(conf) == 1) {
            dumx = c(1, 1)
            plot(dumx, type = "n", asp = 1, xlab = "", ylab = "", 
                xaxt = "n", yaxt = "n")
            par(params)
        }
        else {
            MGvar$Shepx <<- as.vector(0)
            MGvar$Shepy <<- as.vector(0)
            ShepComp <- Shepard(as.dist(shepdists), conf)
            dmat <- matrix(0, nrow(shepdists), ncol(shepdists))
            for (i in 1:nrow(shepdists)) {
                for (j in 1:nrow(shepdists)) {
                  comp = 0
                  for (k in 1:ncol(conf)) {
                    comp = comp + (conf[i, k] - conf[j, k])^2
                  }
                  dmat[i, j] = sqrt(comp)
                }
            }
            tShepy <- as.vector(0)
            len = nrow(shepdists)
            count = 1
            for (i in 1:(len - 1)) {
                for (j in (i + 1):len) {
                  tShepy[count] <- dmat[j, i]
                  names(tShepy)[count] <- paste(rownames(shepdists)[i], 
                    ":", colnames(shepdists)[j])
                  count = count + 1
                }
            }
            count = 1
            for (i in 1:(len - 1)) {
                for (j in (i + 1):len) {
                  MGvar$tShepx[count] <<- shepdists[j, i]
                  names(MGvar$tShepx)[count] <<- paste(rownames(shepdists)[i], 
                    ":", colnames(shepdists)[j])
                  count = count + 1
                }
            }
            Shepvals <- data.frame(tShepx = MGvar$tShepx, tShepy, 
                seq(1:length(MGvar$tShepx)))
            rownames(Shepvals) = names(MGvar$tShepx)
            OrderedVals = Shepvals[order(Shepvals$tShepx), ]
            MGvar$OrderedVals <<- as.matrix(OrderedVals)
            MGvar$Shepx <<- MGvar$OrderedVals[, 1]
            MGvar$Shepy <<- MGvar$OrderedVals[, 2]
            names(MGvar$Shepx) <<- rownames(MGvar$OrderedVals)
            if (MGvar$shep.firstrun == "yes") {
                ShepCompfunc = ShepFirstRun(ShepComp, tShepx = MGvar$tShepx, 
                  Shepx = MGvar$Shepx)
                MGvar$ShepPointindex <<- ShepCompfunc$ShepPointindex
                MGvar$DistFunc <<- ShepCompfunc$f.DistFunc
                ActiveDistFunc()
                MGvar$shep.firstrun <<- "no"
            }
            Ymin <- min(MGvar$Shepy)
            Ymax <- max(MGvar$Shepy)
            Xmin <- min(MGvar$Shepx)
            Xmax <- max(MGvar$Shepx)
            Gmax <- max(Ymax, Xmax)
            Xrange <- Xmax - Xmin
            Yrange <- Ymax - Ymin
            if (showleg == "yes") {
                Ymax = Ymax + 0.15 * Yrange
            }
            plot(MGvar$Shepx, MGvar$Shepy, type = pointtype, 
                ylim = c(0, Gmax), xlim = c(0, Gmax), cex = pointcex, 
                xlab = "", ylab = "", main = graphtitle, pch = pointshape, 
                col = pointcol, xaxt = xmeas, yaxt = ymeas, fg = axcol, 
                cex.axis = 0.7, mex = 1, mgp = c(2.5, 0.5, 0))
            if (showplabs == "yes") {
                text(MGvar$Shepx, ShepComp$y, names(MGvar$Shepx), 
                  cex = pointcex, col = pointcol)
            }
            if (showcurve == "yes") {
                if (bold) {
                  lnwid = 2
                }
                if (!bold) {
                  lnwid = 1
                }
                if (!MGvar$is.Metric) {
                  lines(ShepComp$x, ShepComp$yf, type = "S", 
                    col = curvecol, lty = curvetype, lwd = lnwid)
                }
                if (MGvar$is.Metric) {
                  lines(ShepComp$x, ShepComp$x, col = curvecol, 
                    lty = curvetype, lwd = lnwid)
                }
            }
            par(params)
            if (showlabs == "yes") {
                mtext(text = "Observed Dissimilarity", side = 1, 
                  line = 1.2, adj = 0.5, cex = 1, col = "black")
                mtext(text = "Ordination Distance", side = 2, 
                  line = 2.1, adj = 0.5, cex = 1, col = "black")
            }
            if (showleg == "yes") {
                legend(Xmin, 1.06 * Ymax, " Line Label", bty = "n", 
                  cex = 0.8, pt.bg = "white", lty = curvetype, 
                  col = curvecol)
                legend(Xmin + 0.02 * Xrange, Ymax, "    Point Label", 
                  bty = "n", cex = 0.8, pch = pointshape, pt.bg = "white", 
                  col = pointcol)
            }
            MGvar$Shep.parPlotSize <<- par("plt")
            MGvar$Shep.usrCoords <<- par("usr")
            MGvar$Shep.labelsVec <<- rownames(MGvar$OrderedVals)
            if (length(MGvar$Shep.indexLabeled) > 0) {
                clrs = rainbow(length(MGvar$Shep.indexLabeled))
                points(MGvar$Shepx, MGvar$Shepy, type = pointtype, 
                  ylim = c(0, Ymax), xlim = c(0, Xmax), cex = pointcex, 
                  xlab = "", ylab = "", main = graphtitle, pch = pointshape, 
                  col = "grey", xaxt = xmeas, yaxt = ymeas, fg = axcol, 
                  cex.axis = 0.7, mex = 1, mgp = c(2.5, 0.5, 
                    0))
                if (showcurve == "yes") {
                  if (bold) {
                    lnwid = 2
                  }
                  if (!bold) {
                    lnwid = 1
                  }
                  if (!MGvar$is.Metric) {
                    lines(ShepComp$x, ShepComp$yf, type = "S", 
                      col = curvecol, lty = curvetype, lwd = lnwid)
                  }
                  if (MGvar$is.Metric) {
                    lines(ShepComp$x, ShepComp$x, col = curvecol, 
                      lty = curvetype, lwd = lnwid)
                  }
                }
                for (i in (1:length(MGvar$Shep.indexLabeled))) {
                  indexClosest <- MGvar$Shep.indexLabeled[i]
                  if (length(MGvar$Shep.indexLabeled) < 10) {
                    text(MGvar$Shepx[indexClosest], MGvar$Shepy[indexClosest], 
                      labels = MGvar$Shep.labelsVec[indexClosest], 
                      cex = 0.6, pos = MGvar$GenSet.ILPos)
                  }
                  points(MGvar$Shepx[indexClosest], MGvar$Shepy[indexClosest], 
                    cex = 2 * pointcex, col = clrs[i], pch = 16)
                }
            }
            segments(MGvar$first.xPlotCoord, MGvar$first.yPlotCoord, 
                MGvar$first.xPlotCoord, MGvar$latest.yPlotCoord, 
                col = "blue")
            segments(MGvar$first.xPlotCoord, MGvar$first.yPlotCoord, 
                MGvar$latest.xPlotCoord, MGvar$first.yPlotCoord, 
                col = "blue")
            segments(MGvar$latest.xPlotCoord, MGvar$first.yPlotCoord, 
                MGvar$latest.xPlotCoord, MGvar$latest.yPlotCoord, 
                col = "blue")
            segments(MGvar$first.xPlotCoord, MGvar$latest.yPlotCoord, 
                MGvar$latest.xPlotCoord, MGvar$latest.yPlotCoord, 
                col = "blue")
        }
    }
    Internal.ShepFirstRun <- function(ShepComp) {
        if (MGvar$shep.firstrun == "yes") {
            time1 = proc.time()
            MGvar$ShepPointindex <<- matrix(nrow = length(MGvar$tShepx), 
                ncol = 2)
            rownames(MGvar$ShepPointindex) <<- names(MGvar$tShepx)
            MGvar$ShepPointindex[, 2] <<- seq(1:length(MGvar$tShepx))
            for (i in 1:length(MGvar$tShepx)) {
                for (j in 1:length(MGvar$Shepx)) {
                  if (names(MGvar$tShepx)[i] == names(MGvar$Shepx)[j]) {
                    MGvar$ShepPointindex[i, 1] <<- j
                    MGvar$DistFunc[j] <<- ShepComp$yf[i]
                    names(MGvar$DistFunc)[j] <<- names(MGvar$Shepx)[j]
                  }
                }
            }
            MGvar$shep.firstrun <<- "no"
            ActiveDistFunc()
            time2 = proc.time()
            print(time2 - time1)
        }
    }
    Shep.labelClosestPoint <- function(xClick, yClick, imgXcoords, 
        imgYcoords) {
        squared.Distance.Sh <- (xClick - imgXcoords)^2 + (yClick - 
            imgYcoords)^2
        indexClosest <- which.min(squared.Distance.Sh)
        MGvar$Shep.indexLabeled <<- c(MGvar$Shep.indexLabeled, 
            indexClosest)
        if (MGvar$GenSet.CalcShep == "yes") {
            tkrreplot(imgshep)
        }
        tabplot()
        if (MGvar$EnShep.switch == "on") {
            tkrreplot(MGcomp$imgEShep)
        }
        tclvalue(Shep.WhichShow.var) <<- "Active Plot"
        tkconfigure(Shep.WhichShow.ComboBox, textvariable = Shep.WhichShow.var)
    }
    Shep.OnLeftClick <- function(x, y) {
        if (MGvar$GenSet.CalcShep == "yes") {
            xClick <- x
            yClick <- y
            width <- as.numeric(tclvalue(tkwinfo("reqwidth", 
                imgshep)))
            height <- as.numeric(tclvalue(tkwinfo("reqheight", 
                imgshep)))
            xMin <- MGvar$Shep.parPlotSize[1] * width
            xMax <- MGvar$Shep.parPlotSize[2] * width
            yMin <- MGvar$Shep.parPlotSize[3] * height
            yMax <- MGvar$Shep.parPlotSize[4] * height
            rangeX <- MGvar$Shep.usrCoords[2] - MGvar$Shep.usrCoords[1]
            rangeY <- MGvar$Shep.usrCoords[4] - MGvar$Shep.usrCoords[3]
            imgXcoords <- (MGvar$Shepx - MGvar$Shep.usrCoords[1]) * 
                (xMax - xMin)/rangeX + xMin
            imgYcoords <- (MGvar$Shepy - MGvar$Shep.usrCoords[3]) * 
                (yMax - yMin)/rangeY + yMin
            xClick <- as.numeric(xClick) + 0.5
            yClick <- as.numeric(yClick) + 0.5
            yClick <- height - yClick
            xPlotCoord <- MGvar$Shep.usrCoords[1] + (xClick - 
                xMin) * rangeX/(xMax - xMin)
            yPlotCoord <- MGvar$Shep.usrCoords[3] + (yClick - 
                yMin) * rangeY/(yMax - yMin)
            Shep.labelClosestPoint(xClick, yClick, imgXcoords, 
                imgYcoords)
        }
    }
    Shep.LabelSpecificPoint <- function() {
        LabStt = tktoplevel()
        tkwm.resizable(LabStt, "0", "0")
        tkwm.deiconify(LabStt)
        tkwm.title(LabStt, "Shepard Point Label")
        tkwm.geometry(LabStt, "300x210")
        LabScanvas = tkcanvas(LabStt, width = 300, height = 250, 
            bg = col.sec)
        tkplace(LabScanvas, `in` = LabStt)
        frameLabS <- tkwidget(LabStt, "TitleFrame", text = "Label a Specific Point", 
            background = "white")
        tkplace(frameLabS, relx = 0.02, relwidth = 0.96, rely = 0.02, 
            relheight = 0.96, `in` = LabStt)
        fontsmall <- tkfont.create(family = "times", size = 9)
        tkplace(tklabel(frameLabS, text = "Each point on the Shepard Plot represents the MDS \nfound distance between each object pairing in the \nactive data. In order to choose a point please select \nthe names of two objects in the data.", 
            font = fontsmall), relx = 0.05, rely = 0.1, `in` = frameLabS)
        tkplace(tklabel(frameLabS, text = "Enter the Object1", 
            background = "white"), relx = 0.08, rely = 0.5, `in` = frameLabS)
        objnames = rownames(MGvar$MDSmat)
        LabInput1.val = tclVar(objnames[1])
        LabInput1.ComboBox <- tkwidget(LabStt, "ComboBox", editable = FALSE, 
            values = objnames, width = 12, textvariable = LabInput1.val)
        tkplace(LabInput1.ComboBox, relx = 0.6, rely = 0.5, `in` = frameLabS)
        tkplace(tklabel(frameLabS, text = "Enter the Object2", 
            background = "white"), relx = 0.08, rely = 0.65, 
            `in` = frameLabS)
        LabInput2.val = tclVar(objnames[2])
        LabInput2.ComboBox <- tkwidget(LabStt, "ComboBox", editable = FALSE, 
            values = objnames, width = 12, textvariable = LabInput2.val)
        tkplace(LabInput2.ComboBox, relx = 0.6, rely = 0.65, 
            `in` = frameLabS)
        On.SEnter <- function() {
            Lab1 = as.character(tclvalue(LabInput1.val))
            Lab2 = as.character(tclvalue(LabInput2.val))
            datlength = nrow(MGvar$MDSmat)
            indexlength = length(MGvar$Shep.indexLabeled)
            pointpos1 = 0
            for (i in 1:datlength) {
                if (rownames(MGvar$MDSmat)[i] == Lab1) {
                  pointpos1 = i
                }
            }
            pointpos2 = 0
            for (j in 1:datlength) {
                if (rownames(MGvar$MDSmat)[j] == Lab2) {
                  pointpos2 = j
                }
            }
            if (pointpos2 < pointpos1) {
                dummy = pointpos1
                pointpos1 = pointpos2
                pointpos2 = dummy
            }
            if (pointpos1 == 0 || pointpos2 == 0) {
                tkmessageBox(title = "Point Label Error", message = "At least one of the names does not match any of the points. \nPlease check spelling", 
                  icon = "error", type = "ok")
            }
            if (pointpos1 > 0 && pointpos2 > 0) {
                indexmat = matrix(nrow = datlength, ncol = datlength)
                count = 1
                for (i in 1:(datlength - 1)) {
                  for (j in (i + 1):datlength) {
                    indexmat[i, j] = count
                    count = count + 1
                  }
                }
                pointname <- names(MGvar$tShepx)[indexmat[pointpos1, 
                  pointpos2]]
                for (i in 1:length(MGvar$Shepx)) {
                  if (pointname == names(MGvar$Shepx)[i]) {
                    MGvar$Shep.indexLabeled[indexlength + 1] <<- i
                    names(MGvar$Shep.indexLabeled)[indexlength + 
                      1] <<- pointname
                  }
                }
            }
            tkdestroy(LabStt)
            if (MGvar$GenSet.CalcShep == "yes") {
                tkrreplot(imgshep)
            }
            tabplot()
            if (MGvar$EnShep.switch == "on") {
                tkrreplot(MGcomp$imgEShep)
            }
            tclvalue(Shep.WhichShow.var) <<- "Active Plot"
            tkconfigure(Shep.WhichShow.ComboBox, textvariable = Shep.WhichShow.var)
        }
        tkplace(tkbutton(LabStt, text = "Enter", width = 15, 
            command = function() On.SEnter()), relx = 0.3, rely = 0.82, 
            `in` = frameLabS)
        tkfocus(LabStt)
        tkbind(LabStt, "<Return>", On.SEnter)
    }
    plotScree <- function(stress, current, best, Cdim, Odim, 
        showtitle = MGvar$screeplot.title.show, showlabs = MGvar$screeplot.labs.show, 
        showleg = MGvar$screeplot.leg.show, bgcol = MGvar$screeplot.bg, 
        pointtype = MGvar$screeplot.points.show, showCdim = MGvar$screeplot.Cdim.show, 
        showOdim = MGvar$screeplot.Odim.show, CPcol = MGvar$screeplot.Ccol, 
        OPcol = MGvar$screeplot.Ocol, showcurve = MGvar$screeplot.curve.show, 
        curvetype = MGvar$screeplot.curve.type, curvecol = MGvar$screeplot.curvecol, 
        Cline = MGvar$screeplot.Cline.show, Oline = MGvar$screeplot.Oline.show, 
        xmeas = MGvar$screeplot.Axes.xaxt, ymeas = MGvar$screeplot.Axes.yaxt, 
        axcol = MGvar$screeplot.Axescol, Tab = tclvalue(MGvar$ActivePlottingTab)) {
        if (showtitle == "yes") {
            MGvar$activescreeplot.title <<- paste("Scree Plot for", 
                Tab)
            if (Tab == "Tab1" && MGvar$MDStype.T1 == "ClasScal") {
                MGvar$activescreeplot.title <<- paste("Eigen-Plot for", 
                  Tab)
            }
            if (Tab == "Tab2" && MGvar$MDStype.T2 == "ClasScal") {
                MGvar$activescreeplot.title <<- paste("Eigen-Plot for", 
                  Tab)
            }
            if (Tab == "Tab3" && MGvar$MDStype.T3 == "ClasScal") {
                MGvar$activescreeplot.title <<- paste("Eigen-Plot for", 
                  Tab)
            }
            if (Tab == "Tab4" && MGvar$MDStype.T4 == "ClasScal") {
                MGvar$activescreeplot.title <<- paste("Eigen-Plot for", 
                  Tab)
            }
            if (Tab == "Tab5" && MGvar$MDStype.T5 == "ClasScal") {
                MGvar$activescreeplot.title <<- paste("Eigen-Plot for", 
                  Tab)
            }
            graphtitle = MGvar$activescreeplot.title
        }
        if (showtitle == "no") {
            graphtitle = ""
        }
        if (showcurve == "yes") {
            curve = "l"
        }
        if (showcurve == "no") {
            curve = "n"
        }
        par(mar = c(4, 3, 2, 2))
        params <- par(bg = bgcol)
        if (length(stress) == 1) {
            plot(stress, type = "n", asp = 1, xlab = "", ylab = "", 
                xaxt = "n", yaxt = "n")
            par(params)
        }
        else {
            cap = min((MGvar$maxdims - 2), 10)
            plot(stress[1:cap], type = "n", main = graphtitle, 
                col = curvecol, xaxt = xmeas, yaxt = ymeas, fg = axcol, 
                sub = "", ylab = "", xlab = "")
            if (showcurve == "yes") {
                lines(stress[1:2], lty = 2)
                linseq = seq(2, cap)
                lines(linseq, stress[2:cap], lty = curvetype)
            }
            par(params)
            if (pointtype == "yes") {
                points(stress[1:cap])
            }
            if (showCdim == "yes") {
                points(current, cex = 2, pch = 16, col = CPcol)
            }
            if (showOdim == "yes") {
                points(best, cex = 1.6, pch = 16, col = OPcol)
            }
            if (Cline == "yes") {
                abline(v = Cdim, lty = 3, col = CPcol)
            }
            if (Oline == "yes") {
                abline(v = Odim + 0.05, lty = 3, col = OPcol)
            }
            if (showleg == "yes") {
                if (showCdim == "yes") {
                  legend(7, (0.99 * max(stress)), "Current", 
                    pch = 16, bty = "n", pt.bg = "white", lty = 2, 
                    col = CPcol)
                }
                else {
                  legend(7, (0.99 * max(stress)), "Current", 
                    bty = "n", pt.bg = "white", lty = 2, col = CPcol)
                }
                if (showOdim == "yes") {
                  legend(7, (0.91 * max(stress)), "Optimal", 
                    pch = 16, bty = "n", pt.bg = "white", lty = 2, 
                    col = OPcol)
                }
                else {
                  legend(7, (0.91 * max(stress)), "Optimal", 
                    bty = "n", pt.bg = "white", lty = 2, col = OPcol)
                }
            }
            if (showlabs == "yes") {
                CS = "no"
                mtext(text = "Dimensions", side = 1, line = 2, 
                  adj = 0.5, cex = 1, col = "black")
                if (Tab == "Tab1" && MGvar$MDStype.T1 == "ClasScal") {
                  mtext(text = "Eigen Values", side = 2, line = 2.1, 
                    adj = 0.5, cex = 1, col = "black")
                  CS = "yes"
                }
                if (Tab == "Tab2" && MGvar$MDStype.T2 == "ClasScal") {
                  mtext(text = "Eigen Values", side = 2, line = 2.1, 
                    adj = 0.5, cex = 1, col = "black")
                  CS = "yes"
                }
                if (Tab == "Tab3" && MGvar$MDStype.T3 == "ClasScal") {
                  mtext(text = "Eigen Values", side = 2, line = 2.1, 
                    adj = 0.5, cex = 1, col = "black")
                  CS = "yes"
                }
                if (Tab == "Tab4" && MGvar$MDStype.T4 == "ClasScal") {
                  mtext(text = "Eigen Values", side = 2, line = 2.1, 
                    adj = 0.5, cex = 1, col = "black")
                  CS = "yes"
                }
                if (Tab == "Tab5" && MGvar$MDStype.T5 == "ClasScal") {
                  mtext(text = "Eigen Values", side = 2, line = 2.1, 
                    adj = 0.5, cex = 1, col = "black")
                  CS = "yes"
                }
                if (CS == "no") {
                  mtext(text = "Stress", side = 2, line = 2.1, 
                    adj = 0.5, cex = 1, col = "black")
                }
            }
        }
    }
    StressPlot <- function(showtitle = MGvar$stressplot.title.show, 
        showtime = MGvar$stressplot.time.show, showlabs = MGvar$stressplot.labs.show, 
        bgcol = MGvar$stressplot.bg, curvetype = MGvar$stressplot.curve.type, 
        curvecol = MGvar$stressplot.curvecol, xmeas = MGvar$stressplot.Axes.xaxt, 
        ymeas = MGvar$stressplot.Axes.yaxt, axcol = MGvar$stressplot.Axescol) {
        if (showtitle == "yes") {
            graphtitle = "Stress Plot"
        }
        if (showtitle == "no") {
            graphtitle = ""
        }
        par(mar = c(4, 3, 2, 2))
        params <- par(bg = bgcol)
        if (length(MGvar$stressitervec) == 1) {
            plot(MGvar$stressitervec, type = "n", col = curvecol, 
                xaxt = "n", yaxt = "n", ylab = "", xlab = "")
            par(params)
        }
        else {
            len = length(MGvar$stressitervec)
            plotseq = cbind(seq(1:(len)), MGvar$stressitervec)
            if (len > 50) {
                plotseq = cbind(plotseq[(len - 49):len, 1], MGvar$stressitervec[(len - 
                  49):len])
            }
            tline = max(plotseq[, 2])
            tline = tline + 0.4 * (max(plotseq[, 2]) - min(plotseq[, 
                2]))
            bline = max(0, min(plotseq[, 2]) - 0.6 * (max(plotseq[, 
                2]) - min(plotseq[, 2])))
            plot(plotseq, type = "l", main = graphtitle, ylim = c(bline, 
                tline), lty = curvetype, col = curvecol, xaxt = xmeas, 
                yaxt = ymeas, fg = axcol, sub = "", ylab = "", 
                xlab = "")
            if (showtime == "yes") {
                timeval <- paste("Time: ", round(MGvar$proctime, 
                  1), " seconds")
                stressval <- paste("Stress: ", round(MGvar$stressitervec[len], 
                  4))
                iterval <- paste("Iterations: ", len)
                legend("topright", c(timeval, stressval, iterval), 
                  cex = 0.7)
            }
            if (showlabs == "yes") {
                mtext(text = "Iterations", side = 1, line = 2, 
                  adj = 0.5, cex = 1, col = "black")
                mtext(text = "Stress", side = 2, line = 2.1, 
                  adj = 0.5, cex = 1, col = "black")
            }
            par(params)
        }
    }
    StressPlot2 <- function(showtitle = MGvar$stressplot.title.show, 
        showtime = MGvar$stressplot.time.show, showlabs = MGvar$stressplot.labs.show, 
        bgcol = MGvar$stressplot.bg, curvetype = MGvar$stressplot.curve.type, 
        curvecol = MGvar$stressplot.curvecol, xmeas = MGvar$stressplot.Axes.xaxt, 
        ymeas = MGvar$stressplot.Axes.yaxt, axcol = MGvar$stressplot.Axescol) {
        if (showtitle == "yes") {
            graphtitle = "Stress Plot (Logged Differences)"
        }
        if (showtitle == "no") {
            graphtitle = ""
        }
        par(mar = c(4, 3, 2, 2))
        params <- par(bg = bgcol)
        if (length(MGvar$stressitervec) == 1) {
            plot(MGvar$stressitervec, type = "n", col = curvecol, 
                xaxt = "n", yaxt = "n", ylab = "", xlab = "")
            par(params)
        }
        else {
            len = length(MGvar$stressitervec)
            plotseq = cbind(seq(1:(len)), MGvar$stressitervec)
            if (len > 50) {
                plotseq = cbind(plotseq[(len - 49):len, 1], MGvar$stressitervec[(len - 
                  49):len])
            }
            MGvar$diffvec <<- plotseq[, 2]
            MGvar$diffvec <<- log(-(MGvar$diffvec[-1] - MGvar$diffvec[-length(MGvar$diffvec)]))
            tline = max(MGvar$diffvec)
            tline = tline + 0.4 * (max(MGvar$diffvec) - min(MGvar$diffvec))
            bline = min(0, min(MGvar$diffvec) - 0.6 * (max(MGvar$diffvec) - 
                min(MGvar$diffvec)))
            plot(plotseq[-1, 1], MGvar$diffvec, type = "l", main = graphtitle, 
                ylim = c(bline, tline), lty = curvetype, col = curvecol, 
                xaxt = xmeas, yaxt = ymeas, fg = axcol, sub = "", 
                ylab = "", xlab = "")
            if (showtime == "yes") {
                timeval <- paste("Time: ", round(MGvar$proctime, 
                  1), " seconds")
                stressval <- paste("Stress: ", round(MGvar$stressitervec[len], 
                  4))
                iterval <- paste("Iterations: ", len)
                legend("topright", c(timeval, stressval, iterval), 
                  cex = 0.7)
            }
            if (showlabs == "yes") {
                mtext(text = "Iterations", side = 1, line = 2, 
                  adj = 0.5, cex = 1, col = "black")
                mtext(text = "Logged Stress Differences", side = 2, 
                  line = 2.1, adj = 0.5, cex = 1, col = "black")
            }
            par(params)
        }
    }
    EnlargedStress <- function() {
        ReusePOW()
        MGvar$EnStress.switch <<- "on"
        MGcomp$EStress <<- tktoplevel()
        tkwm.geometry(MGcomp$EStress, "773x575")
        tkwm.title(MGcomp$EStress, "Enlarged Stress Plot")
        EStresscanvas = tkcanvas(MGcomp$EStress, width = 818, 
            height = 580, bg = col.sec)
        tkplace(EStresscanvas, `in` = MGcomp$EStress)
        ES.height <- as.numeric(tclvalue(tkwinfo("height", MGcomp$EStress)))
        ES.width <- as.numeric(tclvalue(tkwinfo("width", MGcomp$EStress)))
        WidthScale = 773/1.8
        EShscale <- ES.width/WidthScale
        dimrat = 1.8/1.3
        ESvscale <- EShscale/dimrat
        MGcomp$imgEStress <<- tkrplot(MGcomp$EStress, function() StressPlot(), 
            hscale = EShscale, vscale = ESvscale)
        tkplace(MGcomp$imgEStress, relx = 0.05, rely = 0.02, 
            relwidth = 0.9, `in` = MGcomp$EStress)
        CopyStToClip <- function() {
            tkrreplot(MGcomp$imgEStress)
        }
        tkplace(tkbutton(MGcomp$EStress, text = "Copy to Clipboard", 
            width = 20, command = function() CopyStToClip()), 
            relx = 0.22, rely = 0.93, `in` = MGcomp$EStress)
        tkplace(tkbutton(MGcomp$EStress, text = "Plot Options", 
            width = 20, command = function() StressPlotOps()), 
            relx = 0.6, rely = 0.93, `in` = MGcomp$EStress)
        tkbind(MGcomp$imgEStress, "<Destroy>", function() {
            MGvar$EnStress.switch <<- "off"
        })
        tkbind(MGcomp$EStress, "<Configure>", resize.EStress)
    }
    resize.EStress <- function() {
        ES.height <- as.numeric(tclvalue(tkwinfo("height", MGcomp$EStress)))
        ES.width <- as.numeric(tclvalue(tkwinfo("width", MGcomp$EStress)))
        WidthScale = 773/1.8
        MGvar$ESt1hscale <<- ES.width/WidthScale
        dimrat = 1.8/1.3
        MGvar$ESt1vscale <<- MGvar$ESt1hscale/dimrat
        tkrreplot(MGcomp$imgEStress, hscale = MGvar$ESt1hscale, 
            vscale = MGvar$ESt1vscale)
    }
    Replot.imgEStress <- function() {
        resize.EStress()
        resize.EStress2()
    }
    EnlargedStress2 <- function() {
        ReusePOW()
        MGvar$EnStress2.switch <<- "on"
        MGcomp$EStress2 <<- tktoplevel()
        tkwm.geometry(MGcomp$EStress2, "773x575")
        tkwm.title(MGcomp$EStress2, "Enlarged Stress Plot 2")
        EStress2canvas = tkcanvas(MGcomp$EStress2, width = 818, 
            height = 580, bg = col.sec)
        tkplace(EStress2canvas, `in` = MGcomp$EStress2)
        EShscale = 1.8
        ESvscale = 1.3
        MGcomp$imgEStress2 <<- tkrplot(MGcomp$EStress2, function() StressPlot2(), 
            hscale = EShscale, vscale = ESvscale)
        tkplace(MGcomp$imgEStress2, relx = 0.05, rely = 0.02, 
            relwidth = 0.9, `in` = MGcomp$EStress2)
        CopyStToClip <- function() {
            tkrreplot(MGcomp$imgEStress2)
        }
        tkplace(tkbutton(MGcomp$EStress2, text = "Copy to Clipboard", 
            width = 20, command = function() CopyStToClip()), 
            relx = 0.22, rely = 0.93, `in` = MGcomp$EStress2)
        tkplace(tkbutton(MGcomp$EStress2, text = "Plot Options", 
            width = 20, command = function() StressPlotOps()), 
            relx = 0.6, rely = 0.93, `in` = MGcomp$EStress2)
        tkbind(MGcomp$imgEStress2, "<Destroy>", function() {
            MGvar$EnStress2.switch <<- "off"
        })
        tkbind(MGcomp$EStress2, "<Configure>", resize.EStress2)
    }
    resize.EStress2 <- function() {
        ES2.height <- as.numeric(tclvalue(tkwinfo("height", MGcomp$EStress2)))
        ES2.width <- as.numeric(tclvalue(tkwinfo("width", MGcomp$EStress2)))
        WidthScale = 773/1.8
        MGvar$ESt2hscale <<- ES2.width/WidthScale
        dimrat = 1.8/1.3
        MGvar$ESt2vscale <<- MGvar$ESt2hscale/dimrat
        tkrreplot(MGcomp$imgEStress2, hscale = MGvar$ESt2hscale, 
            vscale = MGvar$ESt2vscale)
    }
    Procrust <- function(X, Y, labels = NULL, col1 = "sea green", 
        col2 = "blue", ...) {
        X <- scale(X, scale = F)
        Y <- scale(Y, scale = F)
        q <- ncol(X)
        p <- ncol(Y)
        while (q < p) {
            X <- cbind(X, 0)
            q <- q + 1
        }
        Cmat <- t(Y) %*% X
        swd <- svd(Cmat)
        Amat <- swd$v %*% t(swd$u)
        rho <- sum(eigen(Amat %*% Cmat)$values)/sum(eigen(t(X) %*% 
            X)$values)
        Xtilde <- rho * X %*% Amat
    }
    ProcrustesMDSGUIplot <- function(conf1, conf2, showtitle = MGvar$procplot.title.show, 
        showleg = MGvar$procplot.leg.show, ylabel = MGvar$procplot.ylab, 
        xlabel = MGvar$procplot.xlab, bgcol = MGvar$procplot.bg, 
        showpoints1 = MGvar$procplot.showpoints1, showlabs1 = MGvar$procplot.labs1, 
        pointcex1 = MGvar$procplot.cex1, pointshape1 = MGvar$procplot.type1, 
        pointcol1 = MGvar$procplot.point1col, showpoints2 = MGvar$procplot.showpoints2, 
        showlabs2 = MGvar$procplot.labs2, pointcex2 = MGvar$procplot.cex2, 
        pointshape2 = MGvar$procplot.type2, pointcol2 = MGvar$procplot.point2col, 
        ymeas = MGvar$procplot.yaxt, xmeas = MGvar$procplot.xaxt, 
        axcol = MGvar$procplot.axescol, tab1 = "Plot1", tab2 = "Plot2", 
        showreg1 = MGvar$procplot.showreg1, showreg2 = MGvar$procplot.showreg2, 
        regcol1 = MGvar$procplot.regcol1, regcol2 = MGvar$procplot.regcol2, 
        Mvup = MGvar$proc.moveup, Mvdn = MGvar$proc.movedown, 
        Mvlt = MGvar$proc.moveleft, Mvrt = MGvar$proc.moveright, 
        Zrat = MGvar$proc.zoominrat) {
        if (showtitle == "yes") {
            graphtitle = paste("Procrustes Analysis for", tab1, 
                "on", tab2)
        }
        if (showtitle == "no") {
            graphtitle = ""
        }
        if (showpoints1 == "yes") {
            pointtype1 = "p"
        }
        if (showpoints1 == "no") {
            pointtype1 = "n"
        }
        if (showpoints2 == "yes") {
            pointtype2 = "p"
        }
        if (showpoints2 == "no") {
            pointtype2 = "n"
        }
        par(mar = c(3, 3, 3, 3))
        par(cex.axis = 0.8)
        params <- par(bg = bgcol)
        if (nrow(conf1) == 1 && ncol(conf1) == 1) {
            plot(conf1, type = "n", xaxt = "n", yaxt = "n", ylab = "n", 
                xlab = "n", xaxt = "n", yaxt = "n")
            par(params)
        }
        else {
            proc = Procrust(conf1, conf2, labels = dimnames(MGvar$activedata)[[1]])
            Xminproc <- min(proc[, 1])
            Yminproc <- min(proc[, 2])
            Xminconf2 <- min(conf2[, 1])
            Yminconf2 <- min(conf2[, 2])
            Xmin <- min(Xminproc, Xminconf2)
            Ymin <- min(Yminproc, Yminconf2)
            Xmaxproc <- max(proc[, 1])
            Ymaxproc <- max(proc[, 2])
            Xmaxconf2 <- max(conf2[, 1])
            Ymaxconf2 <- max(conf2[, 2])
            Xmax <- max(Xmaxproc, Xmaxconf2)
            Ymax <- max(Ymaxproc, Ymaxconf2)
            Xrange <- Xmax - Xmin
            Yrange <- Ymax - Ymin
            Xmin <- Xmin + (1 - Zrat) * Xrange/2 - (Mvlt - 1) * 
                Xrange + (Mvrt - 1) * Xrange
            Xmax <- Xmax - (1 - Zrat) * Xrange/2 - (Mvlt - 1) * 
                Xrange + (Mvrt - 1) * Xrange
            Ymin <- Ymin + (1 - Zrat) * Yrange/2 - (Mvdn - 1) * 
                Yrange + (Mvup - 1) * Yrange
            Ymax <- Ymax - (1 - Zrat) * Yrange/2 - (Mvdn - 1) * 
                Yrange + (Mvup - 1) * Yrange
            if (showleg == "yes") {
                Ymax = Ymax + 0.1 * Yrange
            }
            if (showleg == "yes") {
                Ymax = Ymax + 0.1 * Yrange
                Xmax = Xmax + 0.05 * Xrange
                Xmin = Xmin - 0.05 * Xrange
            }
            plot(proc, type = "n", ylim = c(Ymin, Ymax), xlim = c(Xmin, 
                Xmax), main = graphtitle, ylab = "", xlab = "", 
                xaxt = xmeas, yaxt = ymeas, fg = axcol)
            if (showleg == "yes") {
                legend(Xmin, 1.09 * Ymax, tab1, pch = pointshape1, 
                  bty = "n", cex = 0.8, pt.bg = "white", col = pointcol1)
                legend(Xmin, 1.03 * Ymax, tab2, pch = pointshape2, 
                  bty = "n", cex = 0.8, pt.bg = "white", col = pointcol2)
                if (showreg1 == "yes") {
                  leglab1 = paste("Regression Line: ", tab1)
                  legend(Xmin + 0.25 * Xrange, 1.09 * Ymax, leglab1, 
                    bty = "n", cex = 0.8, pt.bg = "white", lty = 1, 
                    col = regcol1)
                }
                if (showreg2 == "yes") {
                  leglab2 = paste("Regression Line: ", tab2)
                  legend(Xmin + 0.25 * Xrange, 1.03 * Ymax, leglab2, 
                    bty = "n", cex = 0.8, pt.bg = "white", lty = 1, 
                    col = regcol2)
                }
            }
            points(proc, type = pointtype1, col = pointcol1, 
                cex = pointcex1, pch = pointshape1)
            points(conf2, type = pointtype2, col = pointcol2, 
                cex = pointcex2, pch = pointshape2)
            if (showlabs1 == "yes") {
                text(proc, rownames(proc), cex = pointcex1, col = pointcol1)
            }
            if (showlabs2 == "yes") {
                text(conf2, rownames(conf2), cex = pointcex2, 
                  col = pointcol2)
            }
            if (showreg1 == "yes") {
                regline1 = lm(proc[, 2] ~ proc[, 1])
                abline(regline1, col = regcol1)
            }
            if (showreg2 == "yes") {
                regline2 = lm(conf2[, 2] ~ conf2[, 1])
                abline(regline2, col = regcol2)
            }
            mtext(text = xlabel, side = 1, line = 1.9, adj = 0.5, 
                cex = 1, col = "black")
            mtext(text = ylabel, side = 2, line = 1.9, adj = 0.5, 
                cex = 1, col = "black")
            params <- par(bg = bgcol)
            MGvar$Proc.parPlotSize <<- par("plt")
            MGvar$Proc.usrCoords <<- par("usr")
            MGvar$Proc.labelsVec <<- rownames(conf1)
            if (length(MGvar$Proc.indexLabeled) > 0) {
                for (i in (1:length(MGvar$Proc.indexLabeled))) {
                  indexClosest <- MGvar$Proc.indexLabeled[i]
                  text(proc[indexClosest, 1], proc[indexClosest, 
                    2], labels = MGvar$Proc.labelsVec[indexClosest], 
                    pos = MGvar$GenSet.ILPos, col = pointcol1)
                  text(conf2[indexClosest, 1], conf2[indexClosest, 
                    2], labels = MGvar$Proc.labelsVec[indexClosest], 
                    pos = MGvar$GenSet.ILPos, col = pointcol2)
                }
            }
        }
    }
    Proc.labelClosestPoint <- function(xClick, yClick, imgXcoords, 
        imgYcoords) {
        squared.Distance.P <- (xClick - imgXcoords)^2 + (yClick - 
            imgYcoords)^2
        indexClosest <- which.min(squared.Distance.P)
        MGvar$Proc.indexLabeled <<- c(MGvar$Proc.indexLabeled, 
            indexClosest)
        tkrreplot(procimg)
        if (MGvar$EnProcPlot.switch == "on") {
            tkrreplot(MGcomp$POprocimg)
        }
    }
    Proc.OnLeftClick <- function(x, y) {
        xClick <- x
        yClick <- y
        width <- as.numeric(tclvalue(tkwinfo("reqwidth", procimg)))
        height <- as.numeric(tclvalue(tkwinfo("reqheight", procimg)))
        xMin <- MGvar$Proc.parPlotSize[1] * width
        xMax <- MGvar$Proc.parPlotSize[2] * width
        yMin <- MGvar$Proc.parPlotSize[3] * height
        yMax <- MGvar$Proc.parPlotSize[4] * height
        rangeX <- MGvar$Proc.usrCoords[2] - MGvar$Proc.usrCoords[1]
        rangeY <- MGvar$Proc.usrCoords[4] - MGvar$Proc.usrCoords[3]
        imgXcoords <- (ProcConf2[, 1] - MGvar$Proc.usrCoords[1]) * 
            (xMax - xMin)/rangeX + xMin
        imgYcoords <- (ProcConf2[, 2] - MGvar$Proc.usrCoords[3]) * 
            (yMax - yMin)/rangeY + yMin
        xClick <- as.numeric(xClick) + 0.5
        yClick <- as.numeric(yClick) + 0.5
        yClick <- height - yClick
        xPlotCoord <- MGvar$Proc.usrCoords[1] + (xClick - xMin) * 
            rangeX/(xMax - xMin)
        yPlotCoord <- MGvar$Proc.usrCoords[3] + (yClick - yMin) * 
            rangeY/(yMax - yMin)
        Proc.labelClosestPoint(xClick, yClick, imgXcoords, imgYcoords)
    }
    Proc.LabelSpecificPoint <- function() {
        Labtt = tktoplevel()
        tkwm.resizable(Labtt, "0", "0")
        tkwm.deiconify(Labtt)
        tkwm.title(Labtt, "Procrutes Point Label")
        tkwm.geometry(Labtt, "280x100")
        LabCanvas = tkcanvas(Labtt, width = 280, height = 100, 
            bg = col.sec)
        tkplace(LabCanvas, relx = 0, `in` = Labtt)
        frameLab <- tkwidget(Labtt, "TitleFrame", text = "Label a Specific Point", 
            background = "white")
        tkplace(frameLab, relx = 0.02, rely = 0.02, relwidth = 0.96, 
            relheight = 0.96, `in` = Labtt)
        tkplace(tklabel(frameLab, text = "Enter the Point Name", 
            background = "white"), relx = 0.05, rely = 0.3, `in` = frameLab)
        LabInput.val = tclVar("")
        LabInput = tkentry(Labtt, width = 15, textvariable = LabInput.val)
        tkplace(LabInput, relx = 0.6, rely = 0.3, `in` = frameLab)
        On.Enter <- function() {
            Lab = as.character(tclvalue(LabInput.val))
            datlength = nrow(ProcConf2)
            indexlength = length(MGvar$Proc.indexLabeled)
            pointpos = 0
            for (i in 1:datlength) {
                if (rownames(ProcConf2)[i] == Lab) {
                  pointpos = i
                }
            }
            if (pointpos == 0) {
                tkmessageBox(title = "Point Label Error", message = "The name does not match any of the points. \nPlease check spelling", 
                  icon = "error", type = "ok")
            }
            if (pointpos > 0) {
                MGvar$Proc.indexLabeled[indexlength + 1] <<- pointpos
                names(MGvar$Proc.indexLabeled)[indexlength + 
                  1] <<- rownames(ProcConf2)[pointpos]
            }
            tkrreplot(procimg)
            tkdestroy(Labtt)
        }
        tkplace(tkbutton(Labtt, text = "Enter", width = 15, command = function() On.Enter()), 
            relx = 0.3, rely = 0.7, `in` = frameLab)
        tkfocus(Labtt)
        tkbind(Labtt, "<Return>", On.Enter)
    }
    EnlargedProcPlot <- function() {
        ReusePOW()
        MGvar$EnProcPlot.switch <<- "on"
        MGcomp$EProc <<- tktoplevel()
        tkwm.title(MGcomp$EProc, "Enlarged Procrustes Plot")
        tkwm.geometry(MGcomp$EProc, "650x650")
        EProcCanvas <- tkcanvas(MGcomp$EProc, width = 650, height = 650, 
            bg = col.sec)
        tkplace(EProcCanvas, `in` = MGcomp$EProc)
        POhscale <- 1.5
        POvscale <- 1.4
        MGcomp$POprocimg <<- tkrplot(MGcomp$EProc, function() ProcrustesMDSGUIplot(conf1 = ProcConf1, 
            conf2 = ProcConf2), hscale = POhscale, vscale = POvscale)
        tkplace(MGcomp$POprocimg, relx = 0.05, rely = 0.02, relwidth = 0.9, 
            `in` = MGcomp$EProc)
        tkbind(MGcomp$POprocimg, "<Button-1>", OnPOProcLeftClick)
        tkconfigure(MGcomp$POprocimg, cursor = "hand2")
        CopyAPToClip <- function() {
            tkrreplot(MGcomp$POprocimg)
        }
        tkplace(tkbutton(MGcomp$EProc, text = "Copy to Clipboard", 
            width = 20, command = function() CopyAPToClip()), 
            relx = 0.19, rely = 0.93, `in` = MGcomp$EProc)
        tkplace(tkbutton(MGcomp$EProc, text = "Plot Options", 
            width = 20, command = function() ProcPlotOps()), 
            relx = 0.6, rely = 0.93, `in` = MGcomp$EProc)
        tkbind(MGcomp$POprocimg, "<Destroy>", function() {
            MGvar$EnActivePlot.switch.T1 <<- "off"
        })
        ProcPlotPOPMenu <- tkmenu(MGcomp$POprocimg, tearoff = FALSE)
        tkadd(ProcPlotPOPMenu, "command", label = "Clear Added Point Labels", 
            command = ClearProcPoints)
        RightClickProcPOP <- function(x, y) {
            rootx <- as.integer(tkwinfo("rootx", MGcomp$POprocimg))
            rooty <- as.integer(tkwinfo("rooty", MGcomp$POprocimg))
            xTxt <- as.integer(x) + rootx
            yTxt <- as.integer(y) + rooty
            tcl("tk_popup", ProcPlotPOPMenu, xTxt, yTxt)
        }
        tkbind(MGcomp$POprocimg, "<Button-3>", RightClickProcPOP)
        tkbind(MGcomp$EProc, "<Configure>", resize.EProc)
    }
    resize.EProc <- function() {
        EP.height <- as.numeric(tclvalue(tkwinfo("height", MGcomp$EProc)))
        EP.width <- as.numeric(tclvalue(tkwinfo("width", MGcomp$EProc)))
        WidthScale = 650/1.5
        EShscale <- EP.width/WidthScale
        dimrat = 1.5/1.4
        ESvscale <- EShscale/dimrat
        tkrreplot(MGcomp$POprocimg, hscale = EShscale, vscale = ESvscale)
    }
    OnPOProcLeftClick <- function(x, y) {
        xClick <- x
        yClick <- y
        width <- as.numeric(tclvalue(tkwinfo("reqwidth", MGcomp$POprocimg)))
        height <- as.numeric(tclvalue(tkwinfo("reqheight", MGcomp$POprocimg)))
        xMin <- MGvar$Proc.parPlotSize[1] * width
        xMax <- MGvar$Proc.parPlotSize[2] * width
        yMin <- MGvar$Proc.parPlotSize[3] * height
        yMax <- MGvar$Proc.parPlotSize[4] * height
        rangeX <- MGvar$Proc.usrCoords[2] - MGvar$Proc.usrCoords[1]
        rangeY <- MGvar$Proc.usrCoords[4] - MGvar$Proc.usrCoords[3]
        imgXcoords <- (ProcConf2[, 1] - MGvar$Proc.usrCoords[1]) * 
            (xMax - xMin)/rangeX + xMin
        imgYcoords <- (ProcConf2[, 2] - MGvar$Proc.usrCoords[3]) * 
            (yMax - yMin)/rangeY + yMin
        xClick <- as.numeric(xClick) + 0.5
        yClick <- as.numeric(yClick) + 0.5
        yClick <- height - yClick
        xPlotCoord <- MGvar$Proc.usrCoords[1] + (xClick - xMin) * 
            rangeX/(xMax - xMin)
        yPlotCoord <- MGvar$Proc.usrCoords[3] + (yClick - yMin) * 
            rangeY/(yMax - yMin)
        msg <- paste("Label the point closest to these approximate plot coordinates: \n", 
            "x =", format(xPlotCoord, digits = 2), ",y =", format(yPlotCoord, 
                digits = 2), "?")
        mbval <- tkmessageBox(title = "Label Point Closest to These Approximate Plot Coordinates", 
            message = msg, type = "yesno", icon = "question")
        if (tclvalue(mbval) == "yes") 
            Proc.labelClosestPoint(xClick, yClick, imgXcoords, 
                imgYcoords)
    }
    savetext <- function() {
        file <- tclvalue(tkgetSaveFile(initialfile = tclvalue(tclfile.tail(wfile)), 
            initialdir = tclvalue(tclfile.dir(wfile))))
        if (!length(file)) 
            return()
        chn <- tclopen(file, "w")
        tclputs(chn, tclvalue(tkget(Notetxt, "0.0", "end")))
        tclclose(chn)
        wfile <<- file
    }
    loadtext <- function() {
        file <- tclvalue(tkgetOpenFile())
        if (!length(file)) 
            return()
        chn <- tclopen(file, "r")
        tkinsert(Notetxt, "0.0", tclvalue(tclread(chn)))
        tclclose(chn)
        wfile <<- file
    }
    runtextascode <- function() {
        code <- tclvalue(tkget(Notetxt, "0.0", "end"))
        e <- try(parse(text = code))
        if (inherits(e, "try-error")) {
            tkmessageBox(message = "Syntax error", icon = "error")
            return()
        }
        cat("Executing from MDSGUI note tab window:", "-----", 
            code, "result:", sep = "\n")
        print(eval(e))
    }
    tableplace <- function() {
        myConfarray <- c("Tab", "Plot1", "Plot2", "Plot3", "Plot4", 
            "Plot5", "Stat 3D", "RGL 3D", "Measure", MGvar$dMeas.T1, 
            MGvar$dMeas.T2, MGvar$dMeas.T3, MGvar$dMeas.T4, MGvar$dMeas.T5, 
            MGvar$dMeas.3S, MGvar$dMeas.3R, "MDS", MGvar$MDStype.T1, 
            MGvar$MDStype.T2, MGvar$MDStype.T3, MGvar$MDStype.T4, 
            MGvar$MDStype.T5, MGvar$MDStype.3S, MGvar$MDStype.3R, 
            "Dims", MGvar$MDS.dimensions.T1, MGvar$MDS.dimensions.T2, 
            MGvar$MDS.dimensions.T3, MGvar$MDS.dimensions.T4, 
            MGvar$MDS.dimensions.T5, MGvar$MDS.dimensions.3S, 
            MGvar$MDS.dimensions.3R, MGvar$StCalc, MGvar$MDSStress.T1, 
            MGvar$MDSStress.T2, MGvar$MDSStress.T3, MGvar$MDSStress.T4, 
            MGvar$MDSStress.T5, MGvar$MDSStress.3S, MGvar$MDSStress.3R, 
            "Plot.Dims", MGvar$TabDims.T1, MGvar$TabDims.T2, 
            MGvar$TabDims.T3, MGvar$TabDims.T4, MGvar$TabDims.T5, 
            MGvar$TabDims.3S, MGvar$TabDims.3R, "Tolerence", 
            MGvar$MDS.tol.T1, MGvar$MDS.tol.T2, MGvar$MDS.tol.T3, 
            MGvar$MDS.tol.T4, MGvar$MDS.tol.T5, MGvar$MDS.tol.3S, 
            MGvar$MDS.tol.3R, "Iterations", MGvar$MDS.iter.T1, 
            MGvar$MDS.iter.T2, MGvar$MDS.iter.T3, MGvar$MDS.iter.T4, 
            MGvar$MDS.iter.T5, MGvar$MDS.iter.3S, MGvar$MDS.iter.3R)
        MGcomp$Confarray <<- tclArray()
        dim(myConfarray) <- c(8, 8)
        for (i in 0:7) for (j in 0:7) {
            MGcomp$Confarray[[i, j]] <- myConfarray[i + 1, j + 
                1]
        }
        table.Conf <- tkwidget(frameConfTab, "table", rows = 8, 
            cols = 8, variable = MGcomp$Confarray, xscrollcommand = function(...) tkset(tablescr, 
                ...), titlerows = "1", titlecols = "1", selectmode = "extended", 
            background = "white", width = 6, height = 8)
        tkgrid(table.Conf)
        tcl(table.Conf, "width", 0, 6)
        tcl(table.Conf, "width", 1, 19)
        tcl(table.Conf, "width", 2, 15)
        tcl(table.Conf, "width", 3, 7)
        tcl(table.Conf, "width", 4, 11)
        tcl(table.Conf, "width", 5, 11)
        tablescr <- tkscrollbar(frameConfTab, orient = "horizontal", 
            command = function(...) tkxview(table.Conf, ...))
        tkgrid(tablescr, sticky = "new", columnspan = 6)
        tkgrid.configure(tablescr, sticky = "new", columnspan = 5)
        tkconfigure(table.Conf, variable = MGcomp$Confarray, 
            background = "white", selectmode = "extended")
        MGcomp$table.Conf <<- table.Conf
    }
    tableupdate <- function() {
        myConfarray <- c("Tab", "Plot1", "Plot2", "Plot3", "Plot4", 
            "Plot5", "Stat 3D", "RGL 3D", "Measure", MGvar$dMeas.T1, 
            MGvar$dMeas.T2, MGvar$dMeas.T3, MGvar$dMeas.T4, MGvar$dMeas.T5, 
            MGvar$dMeas.3S, MGvar$dMeas.3R, "MDS", MGvar$MDStype.T1, 
            MGvar$MDStype.T2, MGvar$MDStype.T3, MGvar$MDStype.T4, 
            MGvar$MDStype.T5, MGvar$MDStype.3S, MGvar$MDStype.3R, 
            "Dims", MGvar$MDS.dimensions.T1, MGvar$MDS.dimensions.T2, 
            MGvar$MDS.dimensions.T3, MGvar$MDS.dimensions.T4, 
            MGvar$MDS.dimensions.T5, MGvar$MDS.dimensions.3S, 
            MGvar$MDS.dimensions.3R, MGvar$StCalc, MGvar$MDSStress.T1, 
            MGvar$MDSStress.T2, MGvar$MDSStress.T3, MGvar$MDSStress.T4, 
            MGvar$MDSStress.T5, MGvar$MDSStress.3S, MGvar$MDSStress.3R, 
            "Plot.Dims", MGvar$TabDims.T1, MGvar$TabDims.T2, 
            MGvar$TabDims.T3, MGvar$TabDims.T4, MGvar$TabDims.T5, 
            MGvar$TabDims.3S, MGvar$TabDims.3R, "Tolerence", 
            MGvar$MDS.tol.T1, MGvar$MDS.tol.T2, MGvar$MDS.tol.T3, 
            MGvar$MDS.tol.T4, MGvar$MDS.tol.T5, MGvar$MDS.tol.3S, 
            MGvar$MDS.tol.3R, "Iterations", MGvar$MDS.iter.T1, 
            MGvar$MDS.iter.T2, MGvar$MDS.iter.T3, MGvar$MDS.iter.T4, 
            MGvar$MDS.iter.T5, MGvar$MDS.iter.3S, MGvar$MDS.iter.3R)
        MGcomp$Confarray <<- tclArray()
        dim(myConfarray) <- c(8, 8)
        for (i in 0:7) for (j in 0:7) {
            MGcomp$Confarray[[i, j]] <- myConfarray[i + 1, j + 
                1]
        }
        tkconfigure(MGcomp$table.Conf, variable = MGcomp$Confarray)
    }
    GOtoActiveTab <- function() {
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab1") {
            tk2notetab.select(myPlottingNB, "Plot1")
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab2") {
            tk2notetab.select(myPlottingNB, "Plot2")
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab3") {
            tk2notetab.select(myPlottingNB, "Plot3")
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab4") {
            tk2notetab.select(myPlottingNB, "Plot4")
        }
        if (tclvalue(MGvar$ActivePlottingTab) == "Tab5") {
            tk2notetab.select(myPlottingNB, "Plot5")
        }
    }
    Incomplete = function() {
        tkmessageBox(message = "this code is incomplete!", icon = "error", 
            type = "ok")
    }
    LargeDataOps <- function() {
        LDO = tktoplevel()
        tkwm.resizable(LDO, "0", "0")
        tkwm.deiconify(LDO)
        tkwm.title(LDO, "Large Data")
        tkwm.geometry(LDO, "350x250")
        LDOcanvas = tkcanvas(LDO, width = "1128", height = "756", 
            bg = col.sec)
        tkplace(LDOcanvas, relx = 0, rely = 0, relwidth = 1, 
            relheight = 1, `in` = LDO)
        frameLDO <- tkwidget(LDO, "TitleFrame", text = "Large Data Options", 
            background = "white")
        tkplace(frameLDO, relx = 0.02, rely = 0.02, relwidth = 0.96, 
            relheight = 0.96, `in` = LDO)
        tkplace(tklabel(frameLDO, text = "The Data that you have uploaded has a number of objects\n greater than 50. Some processes of the MDS-GUI may\n run very slowly with data of this size. You are advised\n to deactivate the following.", 
            background = "white"), relx = 0.05, rely = 0.15, 
            `in` = frameLDO)
        tkplace(tklabel(frameLDO, text = "Scree Plot", background = "white"), 
            relx = 0.15, rely = 0.5, `in` = frameLDO)
        DScree = tclVar(1)
        DScree.CB <- tk2checkbutton(LDO)
        tkconfigure(DScree.CB, variable = DScree)
        tkplace(DScree.CB, relx = 0.75, rely = 0.5, `in` = frameLDO)
        tkplace(tklabel(frameLDO, text = "Shepard Plot", background = "white"), 
            relx = 0.15, rely = 0.6, `in` = frameLDO)
        DShep = tclVar(1)
        DShep.CB <- tk2checkbutton(LDO)
        tkconfigure(DShep.CB, variable = DShep)
        tkplace(DShep.CB, relx = 0.75, rely = 0.6, `in` = frameLDO)
        On.Deactivate <- function() {
            if (as.numeric(tclvalue(DScree)) == 1) {
                MGvar$GenSet.CalcScree <<- "no"
                tclvalue(MGvar$GS.Scree.val) <<- 0
            }
            if (as.numeric(tclvalue(DShep)) == 1) {
                MGvar$GenSet.CalcShep <<- "no"
                tclvalue(MGvar$GS.Shep.val) <<- 0
            }
            tkdestroy(LDO)
        }
        tkplace(tkbutton(LDO, text = "Deactivate", width = 15, 
            command = function() On.Deactivate()), relx = 0.35, 
            rely = 0.8, `in` = LDO)
        tkfocus(LDO)
        tkbind(LDO, "<Return>", On.Deactivate)
        tkwait.window(LDO)
    }
    LoadDataSettxt = function() {
        fileName <- tclvalue(tkgetOpenFile())
        if (!nchar(fileName)) 
            tkmessageBox(message = "No file was selected!")
        else {
            loadeddata = read.table(fileName)
            MGvar$activedata <<- loadeddata
            namingtt <- tktoplevel()
            tkwm.resizable(namingtt, "0", "0")
            tkwm.deiconify(namingtt)
            tkwm.title(namingtt, "New Active Dataset Options")
            tkwm.geometry(namingtt, "350x400")
            Loadcanvas = tkcanvas(namingtt, width = "1128", height = "756", 
                bg = col.sec)
            tkplace(Loadcanvas, relx = 0, rely = 0, relwidth = 1, 
                relheight = 1, `in` = namingtt)
            frameNaming <- tkwidget(namingtt, "TitleFrame", text = "Dataset Name", 
                background = "white")
            tkplace(frameNaming, relx = 0.02, rely = 0.02, relwidth = 0.96, 
                relheight = 0.16, `in` = namingtt)
            tkplace(tklabel(frameNaming, text = "Enter the name of your DataSet", 
                background = "white"), relx = 0.08, rely = 0.4, 
                `in` = frameNaming)
            ChangingName = tclVar("")
            NewNameBox = tkentry(namingtt, width = 15, textvariable = ChangingName)
            tkplace(NewNameBox, relx = 0.65, rely = 0.4, `in` = frameNaming)
            frameTrans <- tkwidget(namingtt, "TitleFrame", text = "Dataset Transpose", 
                background = "white")
            tkplace(frameTrans, relx = 0.02, rely = 0.19, relwidth = 0.96, 
                relheight = 0.3, `in` = namingtt)
            fontsmall <- tkfont.create(family = "times", size = 9)
            tkplace(tklabel(frameTrans, text = "All procedures in this package require that the active data have\n objects as rows and variables as columns. If your data is not\n in this format then please transpose.", 
                font = fontsmall), relx = 0.05, rely = 0.15, 
                `in` = frameTrans)
            tkplace(tklabel(frameTrans, text = "Transpose Active Data?", 
                background = "white"), relx = 0.08, rely = 0.65, 
                `in` = frameTrans)
            cbtrans <- tk2checkbutton(namingtt)
            cbTValue <- tclVar("0")
            tkconfigure(cbtrans, variable = cbTValue)
            tkplace(cbtrans, relx = 0.75, rely = 0.65, `in` = frameTrans)
            frameScale <- tkwidget(namingtt, "TitleFrame", text = "Dataset Scale", 
                background = "white")
            tkplace(frameScale, relx = 0.02, rely = 0.5, relwidth = 0.96, 
                relheight = 0.2, `in` = namingtt)
            tkplace(tklabel(frameScale, text = "Scaling Data will scale the columns of your data between 0 and 1.", 
                font = fontsmall), relx = 0.04, rely = 0.25, 
                `in` = frameScale)
            tkplace(tklabel(frameScale, text = "Scale your active data?", 
                background = "white"), relx = 0.08, rely = 0.6, 
                `in` = frameScale)
            ScDat.val <- tclVar(0)
            ScDat.CB <- tk2checkbutton(namingtt)
            tkconfigure(ScDat.CB, variable = ScDat.val)
            tkplace(ScDat.CB, relx = 0.75, rely = 0.6, `in` = frameScale)
            frameCol <- tkwidget(namingtt, "TitleFrame", text = "Dataset Colours", 
                background = "white")
            tkplace(frameCol, relx = 0.02, rely = 0.71, relwidth = 0.96, 
                relheight = 0.2, `in` = namingtt)
            tkplace(tklabel(frameCol, text = "Does the data contain a column of object category information?", 
                font = fontsmall), relx = 0.02, rely = 0.25, 
                `in` = frameCol)
            tkplace(tklabel(frameCol, text = "Yes", background = "white"), 
                relx = 0.1, rely = 0.6, `in` = frameCol)
            ColDat <- tclVar(0)
            ColDat.CB <- tk2checkbutton(namingtt)
            tkconfigure(ColDat.CB, variable = ColDat)
            tkplace(ColDat.CB, relx = 0.25, rely = 0.6, `in` = frameCol)
            tkplace(tklabel(frameCol, text = "Which Column?", 
                background = "white"), relx = 0.4, rely = 0.6, 
                `in` = frameCol)
            ColColumn <- tclVar("First")
            ColColumn.ComboBox <- tkwidget(namingtt, "ComboBox", 
                editable = FALSE, values = c("First", "Last"), 
                width = 6, textvariable = ColColumn)
            tkplace(ColColumn.ComboBox, relx = 0.7, rely = 0.6, 
                `in` = frameCol)
            OnOk.Name <- function() {
                MGvar$ClasTabCols <<- c()
                NName = as.character(tclvalue(ChangingName))
                MGvar$datatitle <<- NName
                tclvalue(labelText) <- paste("Active Dataset is", 
                  MGvar$datatitle)
                tkentryconfigure(dataMenu, 7, state = "disabled")
                YesCol <- as.character(tclvalue(ColDat))
                if (YesCol == "1") {
                  if (as.character(tclvalue(ColColumn)) == "First") {
                    MGvar$ClasVec <<- MGvar$activedata[, 1]
                    MGvar$activedata <<- MGvar$activedata[, -1]
                  }
                  if (as.character(tclvalue(ColColumn)) == "Last") {
                    MGvar$ClasVec <<- MGvar$activedata[, ncol(MGvar$activedata)]
                    MGvar$activedata <<- MGvar$activedata[, -ncol(MGvar$activedata)]
                  }
                  MGvar$ClasTab <<- table(MGvar$ClasVec)
                  potcols <- c(brewer.pal(9, "Set1"), brewer.pal(12, 
                    "Paired"))
                  for (i in 1:nrow(MGvar$activedata)) {
                    for (j in 1:length(MGvar$ClasTab)) {
                      if (MGvar$ClasVec[i] == names(MGvar$ClasTab)[j]) {
                        if (j == length(potcols)) {
                          num = length(potcols)
                        }
                        if (j != length(potcols)) {
                          num = j%%length(potcols)
                        }
                        MGvar$MDSmat.Cols[i] <<- potcols[num]
                      }
                    }
                  }
                  for (i in 1:length(MGvar$ClasTab)) {
                    MGvar$ClasTabCols <<- c(MGvar$ClasTabCols, 
                      potcols[i])
                    names(MGvar$ClasTabCols)[i] <<- names(MGvar$ClasTab)[i]
                  }
                  MGvar$MDSmat.Cols.T1 <<- MGvar$MDSmat.Cols
                  MGvar$MDSmat.Cols.T2 <<- MGvar$MDSmat.Cols
                  MGvar$MDSmat.Cols.T3 <<- MGvar$MDSmat.Cols
                  MGvar$MDSmat.Cols.T4 <<- MGvar$MDSmat.Cols
                  MGvar$MDSmat.Cols.T5 <<- MGvar$MDSmat.Cols
                  tkentryconfigure(dataMenu, 7, state = "active")
                }
                else {
                  FirstPointColInitialise()
                  PointColInitialise()
                }
                TOp = as.character(tclvalue(cbTValue))
                if (TOp == "1") {
                  MGvar$activedata <<- t(MGvar$activedata)
                  tkmessageBox(message = paste("Your data has been transposed"))
                }
                Scl <- as.character(tclvalue(ScDat.val))
                if (Scl == "1") {
                  MGvar$activedata <<- stand.1.range(MGvar$activedata)
                }
                if (is.numeric(as.matrix(MGvar$activedata))) {
                  if (0 %in% as.matrix(MGvar$activedata)) {
                    tkentryconfigure(MDSMenuDistCal, 10, state = "disabled")
                    if (MGvar$dMeas == "Wave-Hedges") {
                      MGvar$dMeas <<- "Euclidean.Distance"
                    }
                    tkentryconfigure(MDSMenuDistCal, 6, state = "disabled")
                    if (MGvar$dMeas == "Divergence") {
                      MGvar$dMeas <<- "Euclidean.Distance"
                    }
                  }
                  else {
                    tkentryconfigure(MDSMenuDistCal, 10, state = "active")
                    tkentryconfigure(MDSMenuDistCal, 6, state = "active")
                  }
                  new.dissim.meas(MGvar$activedata)
                  MGvar$originaldistmat <<- MGvar$distmat
                  MGvar$distmat.T1 <<- MGvar$distmat
                  MGvar$distmat.T2 <<- MGvar$distmat
                  MGvar$distmat.T3 <<- MGvar$distmat
                  MGvar$distmat.T4 <<- MGvar$distmat
                  MGvar$distmat.T5 <<- MGvar$distmat
                  MGvar$maxdims <<- nrow(MGvar$distmat) - 1
                  MGvar$removedpointsactivedata <<- MGvar$activedata
                  tkentryconfigure(functionMenu, 5, state = "active")
                  tkentryconfigure(MainPlotMenu1, 15, state = "active")
                  tkentryconfigure(MainPlotMenu2, 15, state = "active")
                  tkentryconfigure(MainPlotMenu3, 15, state = "active")
                  tkentryconfigure(MainPlotMenu4, 15, state = "active")
                  tkentryconfigure(MainPlotMenu5, 15, state = "active")
                }
                else {
                  tkmessageBox(message = "Non-Numeric values in the data. Please retry data upload.", 
                    type = "ok")
                  MGvar$activedata <<- as.matrix(0)
                  tclvalue(labelText) <- paste("No Active Dataset")
                  MGvar$MDSmat.Cols.T1 <<- as.vector(0)
                  MGvar$MDSmat.Cols.T2 <<- as.vector(0)
                  MGvar$MDSmat.Cols.T3 <<- as.vector(0)
                  MGvar$MDSmat.Cols.T4 <<- as.vector(0)
                  MGvar$MDSmat.Cols.T5 <<- as.vector(0)
                  tkentryconfigure(dataMenu, 7, state = "disabled")
                }
                tkdestroy(namingtt)
                if (nrow(MGvar$activedata) > 50) {
                  LargeDataOps()
                }
            }
            tkplace(tkbutton(namingtt, text = "OK", width = 10, 
                command = function() OnOk.Name()), relx = 0.38, 
                rely = 0.925, `in` = namingtt)
            tkbind(namingtt, "<Return>", OnOk.Name)
            tkentryconfigure(EditDataMenu, 0, state = "active")
            MGvar$tShepx <<- as.vector(0)
            ClearRemindex()
        }
    }
	LoadDataSetcsv = function() {
        fileName <- tclvalue(tkgetOpenFile())
        if (!nchar(fileName)) 
            tkmessageBox(message = "No file was selected!")
        else {
            loadeddata = read.csv(fileName)
            MGvar$activedata <<- loadeddata
		rownames(MGvar$activedata) <<- MGvar$activedata[,1]
            MGvar$activedata <<- MGvar$activedata[, -1]
            namingtt <- tktoplevel()
            tkwm.resizable(namingtt, "0", "0")
            tkwm.deiconify(namingtt)
            tkwm.title(namingtt, "New Active Dataset Options")
            tkwm.geometry(namingtt, "350x400")
            Loadcanvas = tkcanvas(namingtt, width = "1128", height = "756", 
                bg = col.sec)
            tkplace(Loadcanvas, relx = 0, rely = 0, relwidth = 1, 
                relheight = 1, `in` = namingtt)
            frameNaming <- tkwidget(namingtt, "TitleFrame", text = "Dataset Name", 
                background = "white")
            tkplace(frameNaming, relx = 0.02, rely = 0.02, relwidth = 0.96, 
                relheight = 0.16, `in` = namingtt)
            tkplace(tklabel(frameNaming, text = "Enter the name of your DataSet", 
                background = "white"), relx = 0.08, rely = 0.4, 
                `in` = frameNaming)
            ChangingName = tclVar("")
            NewNameBox = tkentry(namingtt, width = 15, textvariable = ChangingName)
            tkplace(NewNameBox, relx = 0.65, rely = 0.4, `in` = frameNaming)
            frameTrans <- tkwidget(namingtt, "TitleFrame", text = "Dataset Transpose", 
                background = "white")
            tkplace(frameTrans, relx = 0.02, rely = 0.19, relwidth = 0.96, 
                relheight = 0.3, `in` = namingtt)
            fontsmall <- tkfont.create(family = "times", size = 9)
            tkplace(tklabel(frameTrans, text = "All procedures in this package require that the active data have\n objects as rows and variables as columns. If your data is not\n in this format then please transpose.", 
                font = fontsmall), relx = 0.05, rely = 0.15, 
                `in` = frameTrans)
            tkplace(tklabel(frameTrans, text = "Transpose Active Data?", 
                background = "white"), relx = 0.08, rely = 0.65, 
                `in` = frameTrans)
            cbtrans <- tk2checkbutton(namingtt)
            cbTValue <- tclVar("0")
            tkconfigure(cbtrans, variable = cbTValue)
            tkplace(cbtrans, relx = 0.75, rely = 0.65, `in` = frameTrans)
            frameScale <- tkwidget(namingtt, "TitleFrame", text = "Dataset Scale", 
                background = "white")
            tkplace(frameScale, relx = 0.02, rely = 0.5, relwidth = 0.96, 
                relheight = 0.2, `in` = namingtt)
            tkplace(tklabel(frameScale, text = "Scaling Data will scale the columns of your data between 0 and 1.", 
                font = fontsmall), relx = 0.04, rely = 0.25, 
                `in` = frameScale)
            tkplace(tklabel(frameScale, text = "Scale your active data?", 
                background = "white"), relx = 0.08, rely = 0.6, 
                `in` = frameScale)
            ScDat.val <- tclVar(0)
            ScDat.CB <- tk2checkbutton(namingtt)
            tkconfigure(ScDat.CB, variable = ScDat.val)
            tkplace(ScDat.CB, relx = 0.75, rely = 0.6, `in` = frameScale)
            frameCol <- tkwidget(namingtt, "TitleFrame", text = "Dataset Colours", 
                background = "white")
            tkplace(frameCol, relx = 0.02, rely = 0.71, relwidth = 0.96, 
                relheight = 0.2, `in` = namingtt)
            tkplace(tklabel(frameCol, text = "Does the data contain a column of object category information?", 
                font = fontsmall), relx = 0.02, rely = 0.25, 
                `in` = frameCol)
            tkplace(tklabel(frameCol, text = "Yes", background = "white"), 
                relx = 0.1, rely = 0.6, `in` = frameCol)
            ColDat <- tclVar(0)
            ColDat.CB <- tk2checkbutton(namingtt)
            tkconfigure(ColDat.CB, variable = ColDat)
            tkplace(ColDat.CB, relx = 0.25, rely = 0.6, `in` = frameCol)
            tkplace(tklabel(frameCol, text = "Which Column?", 
                background = "white"), relx = 0.4, rely = 0.6, 
                `in` = frameCol)
            ColColumn <- tclVar("First")
            ColColumn.ComboBox <- tkwidget(namingtt, "ComboBox", 
                editable = FALSE, values = c("First", "Last"), 
                width = 6, textvariable = ColColumn)
            tkplace(ColColumn.ComboBox, relx = 0.7, rely = 0.6, 
                `in` = frameCol)
            OnOk.Name <- function() {
                MGvar$ClasTabCols <<- c()
                NName = as.character(tclvalue(ChangingName))
                MGvar$datatitle <<- NName
                tclvalue(labelText) <- paste("Active Dataset is", 
                  MGvar$datatitle)
                tkentryconfigure(dataMenu, 7, state = "disabled")
                YesCol <- as.character(tclvalue(ColDat))
                if (YesCol == "1") {
                  if (as.character(tclvalue(ColColumn)) == "First") {
                    MGvar$ClasVec <<- MGvar$activedata[, 1]
                    MGvar$activedata <<- MGvar$activedata[, -1]
                  }
                  if (as.character(tclvalue(ColColumn)) == "Last") {
                    MGvar$ClasVec <<- MGvar$activedata[, ncol(MGvar$activedata)]
                    MGvar$activedata <<- MGvar$activedata[, -ncol(MGvar$activedata)]
                  }
                  MGvar$ClasTab <<- table(MGvar$ClasVec)
                  potcols <- c(brewer.pal(9, "Set1"), brewer.pal(12, 
                    "Paired"))
                  for (i in 1:nrow(MGvar$activedata)) {
                    for (j in 1:length(MGvar$ClasTab)) {
                      if (MGvar$ClasVec[i] == names(MGvar$ClasTab)[j]) {
                        if (j == length(potcols)) {
                          num = length(potcols)
                        }
                        if (j != length(potcols)) {
                          num = j%%length(potcols)
                        }
                        MGvar$MDSmat.Cols[i] <<- potcols[num]
                      }
                    }
                  }
                  for (i in 1:length(MGvar$ClasTab)) {
                    MGvar$ClasTabCols <<- c(MGvar$ClasTabCols, 
                      potcols[i])
                    names(MGvar$ClasTabCols)[i] <<- names(MGvar$ClasTab)[i]
                  }
                  MGvar$MDSmat.Cols.T1 <<- MGvar$MDSmat.Cols
                  MGvar$MDSmat.Cols.T2 <<- MGvar$MDSmat.Cols
                  MGvar$MDSmat.Cols.T3 <<- MGvar$MDSmat.Cols
                  MGvar$MDSmat.Cols.T4 <<- MGvar$MDSmat.Cols
                  MGvar$MDSmat.Cols.T5 <<- MGvar$MDSmat.Cols
                  tkentryconfigure(dataMenu, 7, state = "active")
                }
                else {
                  FirstPointColInitialise()
                  PointColInitialise()
                }
                TOp = as.character(tclvalue(cbTValue))
                if (TOp == "1") {
                  MGvar$activedata <<- t(MGvar$activedata)
                  tkmessageBox(message = paste("Your data has been transposed"))
                }
                Scl <- as.character(tclvalue(ScDat.val))
                if (Scl == "1") {
                  MGvar$activedata <<- stand.1.range(MGvar$activedata)
                }
                if (is.numeric(as.matrix(MGvar$activedata))) {
                  if (0 %in% as.matrix(MGvar$activedata)) {
                    tkentryconfigure(MDSMenuDistCal, 10, state = "disabled")
                    if (MGvar$dMeas == "Wave-Hedges") {
                      MGvar$dMeas <<- "Euclidean.Distance"
                    }
                    tkentryconfigure(MDSMenuDistCal, 6, state = "disabled")
                    if (MGvar$dMeas == "Divergence") {
                      MGvar$dMeas <<- "Euclidean.Distance"
                    }
                  }
                  else {
                    tkentryconfigure(MDSMenuDistCal, 10, state = "active")
                    tkentryconfigure(MDSMenuDistCal, 6, state = "active")
                  }
                  new.dissim.meas(MGvar$activedata)
                  MGvar$originaldistmat <<- MGvar$distmat
                  MGvar$distmat.T1 <<- MGvar$distmat
                  MGvar$distmat.T2 <<- MGvar$distmat
                  MGvar$distmat.T3 <<- MGvar$distmat
                  MGvar$distmat.T4 <<- MGvar$distmat
                  MGvar$distmat.T5 <<- MGvar$distmat
                  MGvar$maxdims <<- nrow(MGvar$distmat) - 1
                  MGvar$removedpointsactivedata <<- MGvar$activedata
                  tkentryconfigure(functionMenu, 5, state = "active")
                  tkentryconfigure(MainPlotMenu1, 15, state = "active")
                  tkentryconfigure(MainPlotMenu2, 15, state = "active")
                  tkentryconfigure(MainPlotMenu3, 15, state = "active")
                  tkentryconfigure(MainPlotMenu4, 15, state = "active")
                  tkentryconfigure(MainPlotMenu5, 15, state = "active")
                }
                else {
                  tkmessageBox(message = "Non-Numeric values in the data. Please retry data upload.", 
                    type = "ok")
                  MGvar$activedata <<- as.matrix(0)
                  tclvalue(labelText) <- paste("No Active Dataset")
                  MGvar$MDSmat.Cols.T1 <<- as.vector(0)
                  MGvar$MDSmat.Cols.T2 <<- as.vector(0)
                  MGvar$MDSmat.Cols.T3 <<- as.vector(0)
                  MGvar$MDSmat.Cols.T4 <<- as.vector(0)
                  MGvar$MDSmat.Cols.T5 <<- as.vector(0)
                  tkentryconfigure(dataMenu, 7, state = "disabled")
                }
                tkdestroy(namingtt)
                if (nrow(MGvar$activedata) > 50) {
                  LargeDataOps()
                }
            }
            tkplace(tkbutton(namingtt, text = "OK", width = 10, 
                command = function() OnOk.Name()), relx = 0.38, 
                rely = 0.925, `in` = namingtt)
            tkbind(namingtt, "<Return>", OnOk.Name)
            tkentryconfigure(EditDataMenu, 0, state = "active")
            MGvar$tShepx <<- as.vector(0)
            ClearRemindex()
        }
    }
    LoadDistSet <- function() {
        fileName <- tclvalue(tkgetOpenFile())
        if (!nchar(fileName)) 
            tkmessageBox(message = "No file was selected!")
        else {
            loadeddata = read.table(fileName)
            MGvar$activedata <<- loadeddata
            MGvar$distmat <<- loadeddata
            namingtt <- tktoplevel()
            tkwm.resizable(namingtt, "0", "0")
            tkwm.deiconify(namingtt)
            tkwm.title(namingtt, "New Active Dissimilarity Matrix Options")
            tkwm.geometry(namingtt, "350x300")
            Loadcanvas = tkcanvas(namingtt, width = "1128", height = "756", 
                bg = col.sec)
            tkplace(Loadcanvas, relx = 0, rely = 0, relwidth = 1, 
                relheight = 1, `in` = namingtt)
            frameNaming <- tkwidget(namingtt, "TitleFrame", text = "Dataset Name", 
                background = "white")
            tkplace(frameNaming, relx = 0.02, rely = 0.02, relwidth = 0.96, 
                relheight = 0.25, `in` = namingtt)
            tkplace(tklabel(frameNaming, text = "Enter the name of your DataSet", 
                background = "white"), relx = 0.08, rely = 0.4, 
                `in` = frameNaming)
            ChangingName = tclVar("")
            NewNameBox = tkentry(namingtt, width = 15, textvariable = ChangingName)
            tkplace(NewNameBox, relx = 0.65, rely = 0.4, `in` = frameNaming)
            fontsmall <- tkfont.create(family = "times", size = 9)
            frameScale <- tkwidget(namingtt, "TitleFrame", text = "Dataset Scale", 
                background = "white")
            tkplace(frameScale, relx = 0.02, rely = 0.29, relwidth = 0.96, 
                relheight = 0.25, `in` = namingtt)
            tkplace(tklabel(frameScale, text = "Scaling Data will scale the columns of your data between 0 and 1.", 
                font = fontsmall), relx = 0.04, rely = 0.25, 
                `in` = frameScale)
            tkplace(tklabel(frameScale, text = "Scale your active data?", 
                background = "white"), relx = 0.08, rely = 0.6, 
                `in` = frameScale)
            ScDat.val <- tclVar(0)
            ScDat.CB <- tk2checkbutton(namingtt)
            tkconfigure(ScDat.CB, variable = ScDat.val)
            tkplace(ScDat.CB, relx = 0.75, rely = 0.6, `in` = frameScale)
            frameCol <- tkwidget(namingtt, "TitleFrame", text = "Dataset Colours", 
                background = "white")
            tkplace(frameCol, relx = 0.02, rely = 0.56, relwidth = 0.96, 
                relheight = 0.27, `in` = namingtt)
            tkplace(tklabel(frameCol, text = "Does the data contain a column of object category information?", 
                font = fontsmall), relx = 0.02, rely = 0.25, 
                `in` = frameCol)
            tkplace(tklabel(frameCol, text = "Yes", background = "white"), 
                relx = 0.1, rely = 0.6, `in` = frameCol)
            ColDat <- tclVar(0)
            ColDat.CB <- tk2checkbutton(namingtt)
            tkconfigure(ColDat.CB, variable = ColDat)
            tkplace(ColDat.CB, relx = 0.25, rely = 0.6, `in` = frameCol)
            tkplace(tklabel(frameCol, text = "Which Column?", 
                background = "white"), relx = 0.4, rely = 0.6, 
                `in` = frameCol)
            ColColumn <- tclVar("First")
            ColColumn.ComboBox <- tkwidget(namingtt, "ComboBox", 
                editable = FALSE, values = c("First", "Last"), 
                width = 6, textvariable = ColColumn)
            tkplace(ColColumn.ComboBox, relx = 0.7, rely = 0.6, 
                `in` = frameCol)
            OnOk.Name <- function() {
                MGvar$ClasTabCols <<- c()
                NName = as.character(tclvalue(ChangingName))
                MGvar$datatitle <<- NName
                tclvalue(labelText) <- paste("Active Dataset is", 
                  MGvar$datatitle)
                tkentryconfigure(dataMenu, 7, state = "disabled")
                YesCol <- as.character(tclvalue(ColDat))
                if (YesCol == "1") {
                  if (as.character(tclvalue(ColColumn)) == "First") {
                    MGvar$ClasVec <<- MGvar$distmat[, 1]
                    MGvar$activedata <<- MGvar$activedata[, -1]
                    MGvar$distmat <<- MGvar$distmat[, -1