# JUICE-R R.exe JUICE.short.head JUICE.head
library (tcltk)
 if (!require(rgl)) if (tclvalue (tkmessageBox (type = 'yesnocancel', message = 'Library rgl is not installed on your computer. Do you want to download and install it now? (Active internet connection required)'))=='yes') install.packages ('rgl')
 if (!require(lattice)) if (tclvalue (tkmessageBox (type = 'yesnocancel', message = 'Library lattice is not installed on your computer. Do you want to download and install it now? (Active internet connection required)'))=='yes') install.packages ('lattice')
 

have_ttk <- as.character(tcl("info", "tclversion")) >= "8.5"
    if(have_ttk) {
        tkbutton <- ttkbutton
        tkframe <- ttkframe
        tklabel <- ttklabel
        tkradiobutton <- ttkradiobutton
        tkcheckbutton <- ttkcheckbutton
        #tklistbox <- ttklistbox
        tkscrollbar <- ttkscrollbar
     }

cancel <- tclVar (1)
JUICE.head <- JUICE.head[order (JUICE.head[,1]),]
short.head <- JUICE.short.head[order (JUICE.short.head[,1]),]
JUICE.head.temp <- JUICE.head [, -1]
rownames (JUICE.head.temp) <- JUICE.head[, 1]
base <- tktoplevel (padx = 10, pady = 10)
releves.to.keep <- rownames (JUICE.head.temp)
releves.to.delete <- vector ('character')


vars <- paste ('var', seq (1, length (names (JUICE.head.temp))), sep = '')
for (v in seq (1, length (vars))) assign (vars[v], tclVar ('0'))

frame.a <- tkframe (base)
frame.b <- tkframe (base)
frame.c <- tkframe (base)
frame.listbox1 <- tkframe (frame.a)
frame.listbox2 <- tkframe (frame.b)
frame.listbox3 <- tkframe (frame.c)
frame.a.radio <- tkframe (frame.listbox1)
frame.listbox1.sub <- tkframe (frame.listbox1)
frame.listbox2.sub <- tkframe (frame.listbox2)
frame.listbox3.sub <- tkframe (frame.listbox3)
scatt.options <- tkframe (frame.b, relief= 'groove', borderwidth=2)
scatt.options.1 <- tkframe (scatt.options)
scatt.options.2 <- tkframe (scatt.options)
latt.options <- tkframe (frame.c, relief = 'groove', borderwidth = 2)


tkwm.title (base, 'Plot JUICE header data')

# frame.a
sc1 <- tkscrollbar (frame.listbox1.sub, command = function (...) tkyview (lb1,...))
lb1 <- tklistbox (frame.listbox1.sub, activestyle = 'none', selectmode = 'browse', exportselection = F, yscrollcommand = function (...) tkset(sc1, ...))
for (i in seq (1, dim (JUICE.head.temp)[2])) tkinsert (lb1, i, paste (if (is.factor (JUICE.head.temp[,i])) 'F' else 'N', names (JUICE.head.temp) [i], sep = '  '))

tkpack (tklabel (frame.listbox1, text = 'X variable', font = 2))
tkpack (lb1, side = 'left', expand = T, fill = 'both')
tkpack (sc1, side = 'right', fill = 'y')
tkpack (frame.listbox1.sub)

gr.no.x <- tclVar (0)
tkpack (tkcheckbutton (frame.listbox1, text = 'group number as X var.', variable = gr.no.x, command = function (...) if (as.character (tkcget (lb1, '-state')) == 'normal')
  {tkconfigure (lb1, state = 'disabled'); tkconfigure (scatterplot.button, state = 'disabled'); tkconfigure (edit.butt, state = 'disabled'); tkconfigure (transf.butt, state = 'disabled'); tkconfigure (ident.butt, state = 'disabled'); tkconfigure (del.butt, state= 'disabled')
  } else {
  tkconfigure (lb1, state = 'normal'); tkconfigure (scatterplot.button, state = 'active'); tkconfigure (edit.butt, state = 'active'); tkconfigure (transf.butt, state = 'active'); tkconfigure (ident.butt, state = 'active'); tkconfigure (del.butt, state= 'active')
  }))
tkpack (frame.listbox1)

edit.butt <- ttkbutton (frame.a, text = 'Edit (X)', width = 15, command = function (...) {
  check.listbox ('x')
  edit.JUICE.head <- as.matrix (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep, as.numeric (tkcurselection (lb1))+1])
  rownames (edit.JUICE.head) <- rownames (JUICE.head.temp)[rownames (JUICE.head.temp) %in% releves.to.keep]
  colnames (edit.JUICE.head) <- names (JUICE.head.temp[as.numeric (tkcurselection (lb1))+1])
  JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep, as.numeric (tkcurselection (lb1))+1] <<- edit (edit.JUICE.head)
  })
tkpack (edit.butt, padx = 2, pady= 2)

ident.butt <- tkbutton (frame.a, text = 'Identify (X)', width = 15, command = function () {
  check.listbox ('x')
  cursel <- as.numeric (tkcurselection (lb1))
  if (length (cursel) == 1)
    {
    par (mfrow = c(1,1))
    if (dev.cur () == 1) windows ()
    plot (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep, cursel+1], ylab = names (JUICE.head.temp)[cursel+1], main = '')
    identify (x = 1:dim (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep,])[1], y = JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep,cursel+1], rownames (JUICE.head.temp)[rownames (JUICE.head.temp) %in% releves.to.keep])
    }
  })
tkpack (ident.butt, padx = 2, pady= 2)

transf.butt <- tkbutton (frame.a, text = 'Transform (X)', width = 15, command = function () transform.button ())
tkpack (transf.butt, padx = 2, pady = 2)

del.butt <- tkbutton (frame.a, text = 'Delete variable(s)', width = 15, command = function () delete.button ())
tkpack (del.butt, padx = 2, pady = 2)

del.releve.but <- tkbutton (frame.a, text = 'Remove releve(s)', width = 15, command = function () delete.releves.button ())
tkpack (del.releve.but, padx = 2, pady = 2)

# frame.b
sc2 <- tkscrollbar (frame.listbox2.sub, command = function (...) tkyview (lb2,...))
lb2 <- tklistbox (frame.listbox2.sub, state = 'normal', activestyle = 'none', selectmode = 'extended', exportselection = F, yscrollcommand = function (...) tkset(sc2, ...))
for (i in seq (1, dim (JUICE.head.temp)[2])) tkinsert (lb2, i, paste (if (is.factor (JUICE.head.temp[,i])) 'F' else 'N', names (JUICE.head.temp) [i], sep = '  '))

tkpack (tklabel (frame.listbox2, text = 'Y variable', font = 2))
tkpack (lb2, side = 'left', expand = T, fill = 'both')
tkpack (sc2, side = 'right', fill = 'y')
tkpack (frame.listbox2.sub)
tkpack (tklabel (frame.listbox2, text = ''))
tkpack (frame.listbox2)

tkpack (tkbutton (frame.b, text = 'histogram (Y)', width = 15, command = function (...)
  {
  check.listbox ('y')
  cursel <- as.numeric (tkcurselection (lb2))
  if (length (cursel) == 1) {if (dev.cur () == 1) windows ();par (mfrow = c(1,1)); hist (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep,cursel+1], xlab = names (JUICE.head.temp)[cursel+1], main = '')}
  if (length (cursel) > 1) {if (dev.cur () == 1) windows ();par (mfrow = c(rep (ceiling (sqrt (length (cursel))), 2))); for (ii in seq (1, length (cursel))) hist (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep, cursel[ii]+1], xlab = names (JUICE.head.temp[cursel[ii]+1]), main = '')}
  }
  ), pady = 2, padx = 2)

scatterplot.button <- (tkbutton (frame.b, text = 'scatterplot (XY)', width = 15, command = function (...)
  {
  check.listbox ('xy')
  if (dev.cur () == 1) windows ()
  par (mfrow = c(rep (ceiling (sqrt (length (as.numeric (tkcurselection (lb2))))), 2)))
  for (iii in seq (1, length (as.numeric (tkcurselection (lb2)))))
    {
    y.var <-as.numeric (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep,as.numeric(tkcurselection(lb2))[iii]+1])
    x.var <- as.numeric (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep,as.numeric (tkcurselection (lb1))+1])
    z.var <- if (as.logical (as.numeric (tclvalue (gr.no.z)))) short.head$Group_Number[rownames (JUICE.head.temp) %in% releves.to.keep] else as.numeric (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep,as.numeric (tkcurselection(lb3))+1])
    plot (y.var ~ x.var, ylab = names (JUICE.head.temp)[as.numeric (tkcurselection (lb2))[iii]+1], xlab = names (JUICE.head.temp)[as.numeric(tkcurselection (lb1))+1], type = 'n')
    if (as.logical (as.numeric (tclvalue (add.z.variable)))) {check.listbox ('z'); points (y.var ~ x.var, pch = as.numeric (as.factor (z.var)), col = as.numeric (as.factor (z.var))); if (as.logical (as.numeric (tclvalue (legend.yes.no)))) legend (x = 'topright', legend = levels (as.factor (z.var)), pch = unique (as.numeric (as.factor (z.var))), col = unique (as.numeric (as.factor (z.var)) ))}  else points (y.var ~ x.var)
    if (as.logical (as.numeric (tclvalue (add.regr.line))))
      {
      polynom <- switch (tclvalue (linear.quadratic), linear = 1, quadratic = 2)
      lm.model <- lm (y.var ~ poly (x.var, polynom))
      lines (x = seq (min (x.var), max (x.var), length = 100), y = predict (lm.model, list (x.var = seq (min (x.var), max (x.var), length = 100))), col = 'red', lwd = 2)
     title (main = paste (expression (R2), '=', formatC (summary (lm.model)$r.squared, digits = 3, format = 'f'), ', p=', formatC (summary (lm.model)$coefficients[2,4], digits = 3, format = 'f'), sep = ' '))
      }
    }
  }
  ))
tkpack (scatterplot.button, pady = 2, padx = 2)

tkpack (tkbutton (frame.b, text = 'boxplot (XY)', width = 15, command = function (...) {
  check.listbox ('xy')
  if (as.logical (as.numeric (tclvalue (gr.no.x))))
    {
    if (length (as.numeric (tkcurselection (lb2))) == 1) {if (dev.cur () == 1) windows ();par (mfrow = c(1,1)); boxplot (as.numeric (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep,as.numeric(tkcurselection(lb2))+1]) ~ as.factor (short.head$Group_Number)[rownames (JUICE.head.temp) %in% releves.to.keep], xlab = 'Group number', ylab = names (JUICE.head.temp)[as.numeric(tkcurselection (lb2))+1])}
    if (length (as.numeric (tkcurselection (lb2))) > 1) {if (dev.cur () == 1) windows ();par (mfrow = rep (ceiling (sqrt (length (as.numeric(tkcurselection (lb2))))),2)); for (iii in seq (1, length (as.numeric(tkcurselection (lb2))))) boxplot (as.numeric (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep, as.numeric(tkcurselection(lb2))[iii]+1]) ~ as.factor (short.head$Group_Number)[rownames (JUICE.head.temp) %in% releves.to.keep], xlab = 'Group number', ylab = names (JUICE.head.temp)[as.numeric(tkcurselection (lb2))[iii]+1])}
    } else
  {
    if (length (as.numeric (tkcurselection (lb2))) == 1)
    {
    if (dev.cur () == 1) windows ()
    par (mfrow = rep (ceiling (sqrt (length (as.numeric (tkcurselection(lb2))))), 2))
    boxplot (as.numeric (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep, as.numeric(tkcurselection(lb2))+1]) ~ as.factor (JUICE.head.temp [rownames (JUICE.head.temp) %in% releves.to.keep, as.numeric (tkcurselection (lb1))+1]), ylab = names (JUICE.head.temp)[as.numeric (tkcurselection (lb2))+1], xlab = names (JUICE.head.temp)[as.numeric(tkcurselection (lb1))+1])
    }
  if (length (as.numeric (tkcurselection (lb2))) > 1)
    {
    if (dev.cur () == 1) windows ()
    par (mfrow = c(rep (ceiling (sqrt (length (as.numeric (tkcurselection (lb2))))), 2)))
    for (iii in seq (1, length (as.numeric (tkcurselection (lb2))))) boxplot (as.numeric (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep, as.numeric(tkcurselection(lb2))[iii]+1]) ~ as.factor (JUICE.head.temp [rownames (JUICE.head.temp) %in% releves.to.keep, as.numeric (tkcurselection (lb1))+1]), ylab = names (JUICE.head.temp)[as.numeric (tkcurselection (lb2))[iii]+1], xlab = names (JUICE.head.temp)[as.numeric(tkcurselection (lb1))[iii]+1])
    }}}), pady = 2, padx = 2)

# scatterplot options
linear.quadratic <- tclVar ('linear')
add.regr.line <- tclVar (0)
add.z.variable <- tclVar (0)
legend.yes.no <- tclVar (0)

tkpack (tklabel (scatt.options, text = 'Scatterplot (XY) & (XY|Z) options:'), pady = 10)
tkpack (tkcheckbutton (scatt.options, text = 'add regr. line', var = add.regr.line, command = function (...) if (as.logical (as.numeric (tclvalue (add.regr.line)))) {tkconfigure (radio.linear, state = 'normal'); tkconfigure (radio.quadratic, state = 'normal')} else {tkconfigure (radio.linear, state = 'disabled'); tkconfigure (radio.quadratic, state = 'disabled')}), anchor = 'w')
radio.linear <- tkradiobutton (scatt.options.1, text = 'linear', var = linear.quadratic, value = 'linear', state = 'disabled')
radio.quadratic <- tkradiobutton (scatt.options.1, text = 'quadratic', var = linear.quadratic, value = 'quadratic', state = 'disabled')
tkpack (radio.linear, radio.quadratic, anchor = 'w', side = 'left')
tkpack (scatt.options.1, anchor = 'w')

tkpack (tkcheckbutton (scatt.options, text = 'add Z variable as symbol', var = add.z.variable, command = function (...) if (as.logical (as.numeric (tclvalue (add.z.variable)))) {tkconfigure (radio.legend.yes, state = 'normal'); tkconfigure (radio.legend.no, state = 'normal')} else {tkconfigure (radio.legend.yes, state = 'disabled'); tkconfigure (radio.legend.no, state = 'disabled')}), anchor = 'w')
radio.legend.no <- tkradiobutton (scatt.options.2, text = 'without legend', var = legend.yes.no, value = 0, state = 'disabled')
radio.legend.yes <- tkradiobutton (scatt.options.2, text = 'with legend', var = legend.yes.no, value = 1, state = 'disabled')
tkpack (radio.legend.no, radio.legend.yes, anchor = 'w', side = 'left')
tkpack (scatt.options.2, anchor = 'w')
tkpack (scatt.options, padx = 10, pady = 10, ipady = 5, ipadx = 5)

# frame.c
sc3 <- tkscrollbar (frame.listbox3.sub, command = function (...) tkyview (lb3,...))
lb3 <- tklistbox (frame.listbox3.sub, state = 'normal', activestyle = 'none', selectmode = 'browse', exportselection = F, yscrollcommand = function (...) tkset(sc3, ...))
for (i in seq (1, dim (JUICE.head.temp)[2])) tkinsert (lb3, i, paste (if (is.factor (JUICE.head.temp[,i])) 'F' else 'N', names (JUICE.head.temp) [i], sep = '  '))

tkpack (tklabel (frame.listbox3, text = 'Z variable', font = 2))
tkpack (lb3, side = 'left', expand = T, fill = 'both')
tkpack (sc3, side = 'right', fill = 'y')
tkpack (frame.listbox3.sub)

gr.no.z <- tclVar (0)
tkpack (tkcheckbutton (frame.listbox3, text = 'group number as Z var.', variable = gr.no.z, command = function (...) if (as.character (tkcget (lb3, '-state')) == 'normal') tkconfigure (lb3, state = 'disabled') else  tkconfigure (lb3, state = 'normal')))
tkpack (frame.listbox3)

tkpack (tkbutton (frame.c, text = 'Histogram (Y|Z)', width = 17, command = function () draw.lattice ('histogram')), padx = 2, pady = 2)
tkpack (tkbutton (frame.c, text = 'Scatterplot (XY|Z)', width = 17, command = function () draw.lattice ('xyplot')), padx = 2, pady = 2)
tkpack (tkbutton (frame.c, text = 'Boxplot (XY|Z)', width = 17, command = function () draw.lattice ('bw')), padx = 2, pady = 2)

tkpack (tkbutton (frame.c, text = '3D scatterplot (XYZ)', width = 17, command = function () draw.3d.scatterplot ()), padx = 2, pady = 2)

factor.or.shingle <- tclVar ('shingle')
no.of.panels <- tclVar (6)
tkpack (tklabel (latt.options, text = 'Lattice diagram options:'), pady = 5)
tkpack (tklabel (latt.options, text = 'if Z variable is NOT a factor, '))
tkpack (tkradiobutton (latt.options, text = 'convert it to factor', var = factor.or.shingle, value = 'factor'), anchor = 'w')
tkpack (tkradiobutton (latt.options, text = 'split it into', var = factor.or.shingle, value = 'shingle'), tkentry (latt.options, textvariable = no.of.panels, width = 2), tklabel (latt.options, text = 'panels'), side = 'left')
tkpack (latt.options, anchor = 'w', pady = 10, padx = 10, ipadx = 5, ipady = 5)


tkpack (frame.a, frame.b, frame.c, side = 'left', pady = 10, padx = 10, anchor = 'n')
tkbind (base, "<Destroy>", function() tclvalue(cancel)<-2)


# check listbox, if required selection has been done
check.listbox <- function (which.listbox)
 {
 which.listbox <- unlist (strsplit (which.listbox, split = ''))
 warning.message <- vector ('character')
 if ('x' %in% which.listbox) if (!as.logical (as.numeric (tclvalue (gr.no.x)))) if (length (as.numeric (tkcurselection (lb1))) == 0)  warning.message <- append (warning.message, 'X')
 if ('y' %in% which.listbox) if (length (as.numeric (tkcurselection (lb2))) == 0)  warning.message <- append (warning.message, 'Y')
 if ('z' %in% which.listbox) if (!as.logical (as.numeric (tclvalue (gr.no.z)))) if (length (as.numeric (tkcurselection (lb3))) == 0)  warning.message <- append (warning.message, 'Z')
 if (length (warning.message) > 0) {tkmessageBox (type = 'ok', message = paste ('You must select', paste (warning.message, collapse = ' and '), 'variable!', sep = ' ')); break}
 if ('1' %in% which.listbox) if (length (as.numeric (tkcurselection (lb2))) > 1) {tkmessageBox (type = 'ok', message = 'You must select only one Y variable!'); break}  
  }

# draw.lattice function
draw.lattice <- function (histogram.xyplot.bw)
  {
    check.listbox (if (histogram.xyplot.bw == 'histogram') 'y1z' else 'xy1z')
    if (histogram.xyplot.bw == 'xyplot' || histogram.xyplot.bw == 'bw') x.var <- if (as.logical (as.numeric (tclvalue (gr.no.x)))) short.head$Group_Number[rownames (JUICE.head.temp) %in% releves.to.keep] else as.numeric (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep, as.numeric (tkcurselection (lb1))+1])
    y.var <-as.numeric (JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep, as.numeric(tkcurselection(lb2))+1])
    z.var <- if (as.logical (as.numeric (tclvalue (gr.no.z)))) as.factor (short.head$Group_Number)[rownames (JUICE.head.temp) %in% releves.to.keep] else JUICE.head.temp[rownames (JUICE.head.temp) %in% releves.to.keep, as.numeric (tkcurselection(lb3))+1]
    x.var.name <- if (as.logical (as.numeric (tclvalue (gr.no.x)))) 'Group No.' else names (JUICE.head.temp)[as.numeric (tkcurselection (lb1))+1]
    y.var.name <- names (JUICE.head.temp)[as.numeric (tkcurselection (lb2))+1]
    z.var.name <- if (as.logical (as.numeric (tclvalue (gr.no.z)))) 'Group No.' else names (JUICE.head.temp)[as.numeric (tkcurselection (lb3))+1]
      
    if (!is.factor(z.var)) if (tclvalue (factor.or.shingle) == 'factor') z.var <- as.factor (z.var) else z.var <- equal.count (z.var, as.numeric (tclvalue (no.of.panels)), overlap = 0)
    if (dev.cur () == 1) windows ();
    if (histogram.xyplot.bw == 'xyplot') print (xyplot (y.var ~ x.var | z.var, as.table = T, xlab = x.var.name, ylab = y.var.name, strip = strip.custom (strip.names = T, strip.levels = TRUE, var.name = z.var.name), panel = function (x,y) {
    panel.xyplot (x,y)
    if (as.logical (as.numeric (tclvalue (add.regr.line)))) 
      {
      polynom <- switch (tclvalue (linear.quadratic), linear = 1, quadratic = 2)
      lm.model <- lm (y ~ poly (x, polynom))
      panel.lines (x = seq (min (x), max (x), length = 100), y = predict (lm.model, list (x = seq (min (x), max (x), length = 100))), col = 'red')
     panel.text (x = min (x.var), y = max (y.var), adj = 0, labels = paste (expression (R2), '=', formatC (summary (lm.model)$r.squared, digits = 3, format = 'f'), ', p=', formatC (summary (lm.model)$coefficients[2,4], digits = 3, format = 'f'), sep = ''))
      }
    }))
    if (histogram.xyplot.bw == 'histogram') print (histogram (~y.var | z.var, as.table = T, xlab = y.var.name, strip = strip.custom (strip.names = T, strip.levels = TRUE, var.name = z.var.name)))
    if (histogram.xyplot.bw == 'bw') print (bwplot (y.var ~ as.factor (x.var) | z.var, as.table = T, xlab = x.var.name, ylab = y.var.name, strip = strip.custom (strip.names = T, strip.levels = TRUE, var.name = z.var.name)))
  }
  
# Transformation window
transf.fun <- function (how.to.transf, to.be.transf)
  {
  assign ('transformed', env = .GlobalEnv, value = switch (how.to.transf, no = to.be.transf, sqrt = sqrt (to.be.transf), log = log (to.be.transf+1), x.2 = to.be.transf^2))
  }

transform.button <- function ()
  {
  check.listbox ('x')
  to.be.transf <- JUICE.head.temp[,as.numeric (tkcurselection (lb1))+1]
  name.to.be.transf <- names (JUICE.head.temp) [as.numeric (tkcurselection (lb1))+1]
  transf.name <- tclVar (paste (name.to.be.transf, 'transf'))
  how.to.transf <- tclVar ('no')
  transf.to.new <- tclVar (1)
  assign ('transformed', env = .GlobalEnv, value = to.be.transf)

  transf <- tktoplevel (padx = 10, pady = 10)
  transf.12 <- tkframe (transf)
  transf.1 <- tkframe (transf.12)
  transf.2 <- tkframe (transf.12)
  transf.3 <- tkframe (transf)
  transf.2.3 <- tkframe (transf)
  num.char <- if (is.numeric (to.be.transf)) tclVar ('numeric') else tclVar ('factor')
  tkpack (tklabel (transf, text = paste ('Transform variable', name.to.be.transf)))
  tr.but1 <- tkradiobutton (transf.1, text = 'no transformation', var = how.to.transf, value = 'no', state = if (tclvalue (num.char) == 'numeric') 'normal' else 'disabled', command = function (...) transf.fun ('no', to.be.transf))
  tr.but2 <- tkradiobutton (transf.1, text = 'sqrt (x)', var = how.to.transf, value = 'sqrt', state = if (tclvalue (num.char) == 'numeric') 'normal' else 'disabled', command = function (...) transf.fun ('sqrt', to.be.transf))
  tr.but3 <- tkradiobutton (transf.1, text = 'log (x+1)', var = how.to.transf, value = 'log', state = if (tclvalue (num.char) == 'numeric') 'normal' else 'disabled', command = function (...) transf.fun ('log', to.be.transf))
  tr.but4 <- tkradiobutton (transf.1, text = 'x^2', var = how.to.transf, value = 'x.2', state = if (tclvalue (num.char) == 'numeric') 'normal' else 'disabled', command = function (...) transf.fun ('x.2', to.be.transf))
  tkpack (tr.but1, tr.but2, tr.but3, tr.but4, anchor = 'w')

  tkpack (tkradiobutton (transf.2, text = 'as numeric', var = num.char, value = 'numeric', command = function () {assign ('transformed', env = .GlobalEnv, as.numeric (as.character (to.be.transf))); tkconfigure (tr.but1, state = 'normal'); tkconfigure (tr.but2, state = 'normal'); tkconfigure (tr.but3, state = 'normal'); tkconfigure (tr.but4, state = 'normal'); tkconfigure (draw.hist.transf, state = 'active')}), anchor = 'w')
  tkpack (tkradiobutton (transf.2, text = 'as factor', var = num.char, value = 'factor', command = function() {assign ('transformed', env = .GlobalEnv, as.factor (to.be.transf)); ; tkconfigure (tr.but1, state = 'disabled'); tkconfigure (tr.but2, state = 'disabled'); tkconfigure (tr.but3, state = 'disabled'); tkconfigure (tr.but4, state = 'disabled'); tkconfigure (draw.hist.transf, state = 'disabled')}), anchor = 'w')
  tkpack (transf.1, transf.2, side = 'left', anchor = 'n', padx = 5, pady = 5)
  tkpack (transf.12)
  
  draw.hist.transf <-  tkbutton (transf.3, text = 'Draw histogram', state = if (tclvalue (num.char) == 'numeric') 'normal' else 'disabled', command = function () {par (mfrow = c (1,1)); hist (get ('transformed', env = .GlobalEnv)[rownames (JUICE.head.temp) %in% releves.to.keep], main = '', xlab = paste (name.to.be.transf, '(', switch (tclvalue (how.to.transf), no = 'no transformation', log = 'log', sqrt = 'sqrt', x.2 = expression (x^2)), ')'))})
  tkpack (draw.hist.transf, side = 'left', padx = 5, pady = 5)

  tkpack (tkcheckbutton (transf.2.3, text = 'save as new variable', var = transf.to.new))

  tkpack (tkentry (transf.2.3, textvariable = transf.name, width = 15))
  tkpack (transf.2.3, padx = 5, pady = 5)

  tkpack (tkbutton (transf.3, text = 'Transform', command = function ()
  {if (as.logical (as.numeric (tclvalue (transf.to.new))))
    {
    delete.lists ();
    pos.split <- seq (1, dim (JUICE.head.temp)[2])[names (JUICE.head.temp) == name.to.be.transf];
    JUICE.head.temp.temp <- cbind (JUICE.head.temp[, 1:pos.split], nvar547 = get ('transformed', env = .GlobalEnv), JUICE.head.temp[, (pos.split+1):dim (JUICE.head.temp)[2]]);
    if (pos.split == 1) names (JUICE.head.temp.temp)[1] <- names (JUICE.head.temp)[1]
    JUICE.head.temp <- JUICE.head.temp.temp
    names (JUICE.head.temp)[names (JUICE.head.temp)=='nvar547'] <- tclvalue (transf.name);
    assign ('JUICE.head.temp', value = JUICE.head.temp, env = .GlobalEnv)
    reinsert.lists ()
    } else
    {JUICE.head.temp[,name.to.be.transf] <- get ('transformed', env = .GlobalEnv); assign ('JUICE.head.temp', value = JUICE.head.temp, env = .GlobalEnv)};
    tkdestroy (transf)
  }), side = 'left', padx = 5, pady = 5)
  tkpack (tkbutton (transf.3, text = 'Cancel', command = function () tkdestroy (transf)), side = 'left', padx = 5, pady = 5)
  tkpack (transf.3, side = 'bottom', anchor = 's')
  }

# Deletion window
delete.button <- function ()
  {
  del <- tktoplevel ()
  del.listbox.1 <- tkframe (del)
  del.but <- tkframe (del)

  del.sc <- tkscrollbar (del.listbox.1, command = function (...) tkyview (del.lb,...))
  del.lb <- tklistbox (del.listbox.1, state = 'normal', activestyle = 'none', selectmode = 'extended', exportselection = F, yscrollcommand = function (...) tkset(del.sc, ...))
  for (i in seq (1, dim (JUICE.head.temp)[2])) tkinsert (del.lb, i, names (JUICE.head.temp) [i])
  tkpack (tklabel (del.listbox.1, text = 'Select variable(s):'), anchor = 'n')
  tkpack (del.lb, side = 'left', expand = T, fill = 'both')
  tkpack (del.sc, side = 'right', fill = 'y')
  tkpack (del.listbox.1, padx = 10, pady = 10, side = 'top')
  lapply (as.numeric (tkcurselection (lb1)), FUN = function (x) tkselection.set (del.lb, x))

  tkpack (tkbutton (del.but, text = 'Delete', command = function () delete.data ()), side = 'left', padx = 5, pady = 5)
  tkpack (tkbutton (del.but, text = 'Cancel', command = function () tkdestroy (del)), side = 'right', padx = 5, pady = 5)
  tkpack (del.but, side = 'bottom')
  
delete.data <- function ()
  {
  del.yesno <- tkmessageBox (type = 'yesno', default = 'no', message = paste ('Following data will be permanently removed:',
    if (length (as.numeric (tkcurselection (del.lb))) > 0) paste (c('\n\nvariable(s)', names (JUICE.head.temp)[as.numeric (tkcurselection (del.lb))+1]), collapse = ' ')))
   if (tclvalue (del.yesno) == 'yes') {delete.lists (); JUICE.head.temp.temp <- JUICE.head.temp[, !seq (1, dim (JUICE.head.temp)[2]) %in% c(as.numeric (tkcurselection (del.lb))+1)]; assign ('JUICE.head.temp', env = .GlobalEnv, value = JUICE.head.temp.temp); reinsert.lists (); tkdestroy (del)
  }
 }
}

# this will delete the listbox  
delete.lists <- function ()
  {
  assign ('selected.lb1', env = .GlobalEnv,  value = names (JUICE.head.temp)[as.numeric (tkcurselection (lb1))+1])
  assign ('selected.lb2', env = .GlobalEnv, value = names (JUICE.head.temp)[as.numeric (tkcurselection (lb2))+1])
  assign ('selected.lb3', env = .GlobalEnv, value = names (JUICE.head.temp)[as.numeric (tkcurselection (lb3))+1])
  tkdelete (lb1, 0, dim (JUICE.head.temp)[2])
  tkdelete (lb2, 0, dim (JUICE.head.temp)[2])
  if (as.character (tkcget (lb3, '-state')) == 'disabled') {tkconfigure (lb3, state = 'normal');   tkdelete (lb3, 0, dim (JUICE.head.temp)[2]); tkconfigure (lb3, state = 'disabled')} else   tkdelete (lb3, 0, dim (JUICE.head.temp)[2])

  }

# and this will reinsert values into the listbox according to actual values  
reinsert.lists <- function ()
  {
  if (as.character (tkcget (lb3, '-state')) == 'disabled') {tkconfigure (lb3, state = 'normal'); lb3.state <- 'disabled'} else lb3.state <- 'normal'
  for (i in seq (1, dim (JUICE.head.temp)[2])) tkinsert (lb1, i, paste (if (is.factor (JUICE.head.temp[,i])) 'F' else 'N', names (JUICE.head.temp) [i], sep = '  '))
  for (i in seq (1, dim (JUICE.head.temp)[2])) tkinsert (lb2, i, paste (if (is.factor (JUICE.head.temp[,i])) 'F' else 'N', names (JUICE.head.temp) [i], sep = '  '))
  for (i in seq (1, dim (JUICE.head.temp)[2])) tkinsert (lb3, i, paste (if (is.factor (JUICE.head.temp[,i])) 'F' else 'N', names (JUICE.head.temp) [i], sep = '  '))
  lapply (seq (1, dim (JUICE.head.temp)[2])[names (JUICE.head.temp) %in% selected.lb1], FUN = function (x) tkselection.set (lb1, x-1))
  lapply (seq (1, dim (JUICE.head.temp)[2])[names (JUICE.head.temp) %in% selected.lb2], FUN = function (x) tkselection.set (lb2, x-1))
  lapply (seq (1, dim (JUICE.head.temp)[2])[names (JUICE.head.temp) %in% selected.lb3], FUN = function (x) tkselection.set (lb3, x-1))
  if (lb3.state == 'disabled') tkconfigure (lb3, state = 'disabled')
  }

delete.releves.button <- function ()
  {
  del.rel.base <- tktoplevel ()
  del.rel <- tkframe (del.rel.base)
  del.rel.listbox.1 <- tkframe (del.rel)
  del.rel.listbox.2 <- tkframe (del.rel)
  del.rel.buttons <- tkframe (del.rel)
  tkwm.title (del.rel.base, 'Temporary remove releves from plotting')
  del.rel.sc1 <- tkscrollbar (del.rel.listbox.1, command = function (...) tkyview (del.rel.lb1,...))
  del.rel.lb1 <- tklistbox (del.rel.listbox.1, state = 'normal', activestyle = 'none', selectmode = 'extended', exportselection = F, yscrollcommand = function (...) tkset(del.rel.sc1, ...))
  lapply (rev (as.character (sort (as.numeric (releves.to.keep)))), FUN = function (x) tkinsert (del.rel.lb1, 0, x))
  tkpack (tklabel (del.rel.listbox.1, text = 'To be used:'))
  tkpack (del.rel.lb1, side = 'left', expand = T, fill = 'both')
  tkpack (del.rel.sc1, side = 'right', fill = 'y')
 # tkpack (del.rel.listbox.1, padx = 10, pady = 10, side = 'left')

  del.rel.sc2 <- tkscrollbar (del.rel.listbox.2, command = function (...) tkyview (del.rel.lb2,...))
  del.rel.lb2 <- tklistbox (del.rel.listbox.2, state = 'normal', activestyle = 'none', selectmode = 'extended', exportselection = F, yscrollcommand = function (...) tkset(del.rel.sc2, ...))
  lapply (rev (as.character (sort (as.numeric (releves.to.delete)))), FUN = function (x) tkinsert (del.rel.lb2, 0, x))
  tkpack (tklabel (del.rel.listbox.2, text = 'To be removed:'))
  tkpack (del.rel.lb2, side = 'left', expand = T, fill = 'both')
  tkpack (del.rel.sc2, side = 'right', fill = 'y')
#  tkpack (del.rel.listbox.2, padx = 10, pady = 10, side = 'right')
  
  tkpack (tkbutton (del.rel.buttons, text = '>>', command = function (...) {
    if (length (as.numeric (tkcurselection (del.rel.lb1))) > 0) 
    {
    cursel.lb1 <- as.numeric (tkcurselection (del.rel.lb1))+1
    tkdelete (del.rel.lb1, 0, length (releves.to.keep)-1)
    tkdelete (del.rel.lb2, 0, length (releves.to.delete)-1)
    assign ('releves.to.delete', env = .GlobalEnv, as.character (sort (as.numeric (append (releves.to.delete, releves.to.keep[releves.to.keep %in% releves.to.keep [cursel.lb1]])))))
    assign ('releves.to.keep', env = .GlobalEnv, releves.to.keep[!releves.to.keep %in% releves.to.keep [cursel.lb1]])
    lapply (rev (as.character (sort (as.numeric (releves.to.keep)))), FUN = function (x) tkinsert (del.rel.lb1, 0, x))
    lapply (rev (as.character (sort (as.numeric (releves.to.delete)))), FUN = function (x) tkinsert (del.rel.lb2, 0, x))
    }}))
    
  tkpack (tkbutton (del.rel.buttons, text = '<<', command = function () {
  if (length (as.numeric (tkcurselection (del.rel.lb2))) > 0) 
    {
    cursel.lb2 <- as.numeric (tkcurselection (del.rel.lb2))+1
    tkdelete (del.rel.lb1, 0, length (releves.to.keep)-1)
    tkdelete (del.rel.lb2, 0, length (releves.to.delete)-1)
    assign ('releves.to.keep', env = .GlobalEnv, as.character (sort (as.numeric (append (releves.to.keep, releves.to.delete[releves.to.delete %in% releves.to.delete [cursel.lb2]])))))
    assign ('releves.to.delete', env = .GlobalEnv, releves.to.delete[!releves.to.delete %in% releves.to.delete [cursel.lb2]])
    
    lapply (rev (as.character (sort (as.numeric (releves.to.keep)))), FUN = function (x) tkinsert (del.rel.lb1, 0, x))
    lapply (rev (as.character (sort (as.numeric (releves.to.delete)))), FUN = function (x) tkinsert (del.rel.lb2, 0, x))
    }}))
  tkpack (del.rel.listbox.1, del.rel.buttons, del.rel.listbox.2, side = 'left', padx = 10, pady = 10)
  tkpack (del.rel)
  tkpack (tkbutton (del.rel.base, text = 'Ok', command = function () tkdestroy (del.rel.base)), side = 'right', padx = 10, pady = 10)
  }

draw.3d.scatterplot <- function ()
  {
  check.listbox ('xy1z')
  for.3d <- JUICE.head.temp [rownames (JUICE.head.temp) %in% releves.to.keep, c(as.numeric (tkcurselection (lb1))+1, as.numeric (tkcurselection (lb2))+1, as.numeric (tkcurselection (lb3))+1)]
  rgl.scatterplot (for.3d, polynom = switch (tclvalue (linear.quadratic), linear = 1, quadratic = 2), add.regr.line = as.logical (as.numeric (tclvalue (add.regr.line))))
  }

rgl.scatterplot <- function (x, ax.col = 'red', polynom = 1, add.regr.line = FALSE) 
{
    
    open3d ()
    par3d (windowRect = c (300, 100, 600, 400))
    rgl.bg (col = c ('white', 'black'))
    rgl.clear()
    x <- apply (x, 2, FUN = function (st) (st-min (st))/(max (st)-min (st)))
    rgl.points(x[, 1], x[, 3], x[, 2], col = 'black')
    rgl.lines(range(x[, 1]), c(0, 0), c(0, 0), col = ax.col)
    rgl.lines(c(0, 0), range(x[, 2]), c(0, 0), col = ax.col)
    rgl.lines(c(0, 0), c(0, 0), range(x[, 3]), col = ax.col)
    rgl.texts(1.1 * max(x[, 1]), 0, 0, paste ('X:', colnames(x)[1]), col = ax.col, 
        adj = 0.5)
    rgl.texts(0, 1.1 * max(x[, 2]), 0, paste ('Z:', colnames(x)[3]), col = ax.col, 
        adj = 0.5)
    rgl.texts(0, 0, 1.1 * max(x[, 3]), paste ('Y:', colnames(x)[2]), col = ax.col, 
        adj = 0.5)
    if (add.regr.line)
      {
      xx <- x[,1]
      yy <- x[,2]
      zz <- x[,3]
      lm.model <- lm (zz ~ poly (xx, polynom) + poly (yy, polynom))
      xxx <- seq (min (xx), max (xx), length = 100)
      yyy <- seq (min (yy), max (yy), length = 100)
      xxx.yyy <- expand.grid (xxx, yyy)
      rgl.surface (xxx, yyy, matrix (predict (lm.model, list (xx = xxx.yyy[,1], yy = xxx.yyy[,2])), ncol = 100))
      }
      rgl.bringtotop ()
}

tkwait.variable (cancel)
  


