#!/bin/sh
# we need to find the tcl dir, it was exported from emc.run \
export EMC2_TCL_DIR

# the next line restarts using iosh \
exec $EMC2_EMCSH "$0" "$@"

####################################################################
# Description:  ProbeBuddy.tcl
#               This file, ' ProbeBuddy.tcl', is a script that lets
#               the user chose between different preset probe areas/speeds
#
# AuthorS: Fred Proctor, Ray Henry, fenn
# License: GPL Version 2
#    
# Copyright (c) 2005 All rights reserved.
#
# Last change: 
# $Revision: 1.6 $
# $Author: fenn $
# $Date: 2006/07/30 16:32:59 $
####################################################################
# A dirty dirty hack to provide some probing presets
####################################################################

# Load the emc.tcl file, which defines variables for various useful paths
#source [file join [file dirname [info script]] .. emc.tcl]

#emc.tcl seems to have disappeared. wtf! instead we will just dump the contents here
#wheee!!!
################
set emc2dir /usr/share/emc
namespace eval emc {
    variable TCL_DIR $emc2dir/tcl
    variable TCL_BIN_DIR  $emc2dir/tcl/bin
    variable TCL_SCRIPT_DIR $emc2dir/tcl/scripts
    variable NCFILES_DIR $emc2dir/ncfiles
    variable IMAGEDIR /etc/emc2/

    variable _langinit 1
}

if {[string first $::emc::BIN_DIR: $env(PATH)] != 0} {
    set env(PATH) $::emc::BIN_DIR:$env(PATH)
}

proc emc::image_search i {
    set paths "$emc::HOME $emc::HOME/etc/emc2 /etc/emc2 ."
    foreach f $paths {
        if [file exists $f/$i] {
            return [image create photo -file $f/$i]
        }
        if [file exists $f/$i.gif] {
            return [image create photo -file $f/$i.gif]
        }
    }
    error "image $i is not available"
}

# Internationalisation (i18n)
# in order to use i18n, all the strings will be called [msgcat::mc "string-foo"]
# instead of "string-foo".
# Thus msgcat searches for a translation of the string, and in case one isn't 
# found, the original string is used.
# In order to properly use locale's the env variable LANG is queried.
# If LANG is defined, then the folder src/po is searched for files
# called *.msg, (e.g. en_US.msg).
package require msgcat
if {$emc::_langinit && [info exists env(LANG)]} {
    msgcat::mclocale $env(LANG)
    msgcat::mcload $emc::LANG_DIR
    set emc::_langinit 0
}
################
#end emc.tcl

wm title . [msgcat::mc "EMC ProbeBuddy"]

set top [frame .frame -borderwidth 2 -relief raised]
label $top.l1 -text [msgcat::mc "ProbeBuddy version 0.001 gamma"]
pack $top.l1 -side top
label $top.l2 -text [msgcat::mc "Happy probing!"]
pack $top.l2 -side top

#grid $logo $top.l1
#grid $top.l1 $top.logo -sticky news
#pack $top.logo -side left -expand yes

set paramfilename [emc_ini "PARAMETER_FILE" "RS274NGC"]
if {[string length $paramfilename] == 0} {
    set paramfilename "emc.var"
}

# Reads the number of axi from ini
#set numparam [emc_ini "AXES" "TRAJ"]
set numparam 10

set paramList [list feedrate xstart xstep xstop ystart ystep ystop zsafeheight zprobeheight]

# put the parm file into an invisible widget
set vartext [text $top.vartext]
$vartext config -state normal
$vartext delete 1.0 end
if {[catch {open $paramfilename} programin]} {
    return
} else {
    $vartext insert end [read $programin]
    catch {close $programin}
}

set bottom [frame $top.row]
# Build the coordinates radio buttons.
set presets [frame $bottom.selectors -borderwidth 2 -relief groove]
radiobutton $presets.preset1 -text preset1 -variable coordsys -value 2010 -anchor w \
    -command getVarAddress
radiobutton $presets.preset2 -text preset2 -variable coordsys -value 2020 -anchor w \
    -command getVarAddress
radiobutton $presets.preset3 -text preset3 -variable coordsys -value 2030 -anchor w \
    -command getVarAddress
radiobutton $presets.preset4 -text preset4 -variable coordsys -value 2040 -anchor w \
    -command getVarAddress
radiobutton $presets.preset5 -text preset5 -variable coordsys -value 2050 -anchor w \
    -command getVarAddress
radiobutton $presets.preset6 -text preset6 -variable coordsys -value 2060 -anchor w \
    -command getVarAddress
radiobutton $presets.preset7 -text preset7 -variable coordsys -value 2070 -anchor w \
    -command getVarAddress
radiobutton $presets.preset8 -text preset8 -variable coordsys -value 2080 -anchor w \
    -command getVarAddress
radiobutton $presets.preset9 -text preset9 -variable coordsys -value 2090 -anchor w \
    -command getVarAddress
pack $presets.preset1 $presets.preset2 $presets.preset3 $presets.preset4 $presets.preset5 \
    $presets.preset6 $presets.preset7 $presets.preset8 $presets.preset9 -side top -fill x
#pack $presets -side left -padx 10 -pady 10


# Build the variable numbers and value entry widgets.
set fields [frame $bottom.coord]
label $fields.name -text [msgcat::mc "Parameter "]
#label $fields.varnum -text [msgcat::mc "Var # "]
label $fields.varval -text [msgcat::mc "Value "]
#label $fields.difference -text [msgcat::mc "Teach Offset"]
#grid $fields.name $fields.varnum $fields.varval $fields.difference -sticky news
grid $fields.name $fields.varval -sticky news
for {set i 0} {$i < $numparam} {incr i} {
    label  $fields.l$i -text [lindex $paramList $i ]  -anchor e
   # label $fields.l1$i -textvariable "num$i"  -anchor e
    entry $fields.e$i -textvariable val$i -takefocus 1
   # entry $fields.fv$i -textvariable difference$i
    button $fields.b$i -text [msgcat::mc "Teach"] -command "getLocation $i"
#    grid $fields.l$i $fields.l1$i $fields.e$i $fields.fv$i $fields.b$i -sticky news
    grid $fields.l$i $fields.e$i $fields.b$i -sticky news
    bind $fields.e$i <Down>  {shiftFocus 1}
    bind $fields.e$i <Up> {shiftFocus -1}
}
focus $fields.e0

# Build the control button widgets.
set buttons [frame $top.buttons]
set wizard_image $::emc::IMAGEDIR/probe-buddy.gif
 if { [file exists $wizard_image] } {
        set logo [image create photo -file $wizard_image]
	set logo [label $buttons.logo -image $logo ]
}

button $buttons.b1 -text [msgcat::mc "Probe"] -width 12 -command {doProbe} -background green -takefocus 0
button $buttons.b2 -text [msgcat::mc "Use last values"] -width 12 -command {getLast}
button $buttons.b3 -text [msgcat::mc "Abort"] -width 12 -command {doAbort} -background red
button $buttons.b4 -text [msgcat::mc "Save this preset"] -width 12 -command {doSave}
grid $buttons.logo 
grid ^              $buttons.b1 $buttons.b2 
grid ^              $buttons.b3 $buttons.b4 
pack $fields -side right -fill x -expand yes
pack $presets -side left -padx 10 -pady 10
pack $bottom -side bottom
pack $buttons -side top -fill x -expand yes
#pack $right -side left -fill both
pack $top

# Initialize values
for {set i 0} {$i < $numparam} {incr i} {
    set val$i 0.000000
    set difference$i 0.000000
}

proc getVarAddress {} {
    global coordsys
    global numparam num0 num1 num2 num3 num4 num5 num6 num7 num8 num9
    for {set i 0} {$i < $numparam} {incr i} {
        set num$i [expr $coordsys +$i]
    }
    getVarValues
}

proc getVarValues {} {
    global vartext
    global numparam val0 val1 val2 val3 val4 val5 val6 val7 val8 val9
    global num0 num1 num2 num3 num4 num5 num6 num7 num8 num9
    global numparam oval0 oval1 oval2 oval3 oval4 oval5 oval6 oval7 oval8 oval9
    set locate "1.0"
    for {set i 0} {$i < $numparam} {incr i} {
        set oval$i [set val$i]
        set locate [$vartext search [set num$i] 1.0 ]
        set locate [expr int($locate)]
        set valtemp [$vartext get $locate.4 "$locate.end"]
        set val$i [string trim $valtemp]
    }
}

proc doZero {} {
    global numparam 
    global val0 val1 val2 val3 val4 val5 val6 val7 val8 val9
    global difference0 difference1 difference2 difference3 difference4 difference5 difference6 difference7 difference8
    for {set i 0} {$i < $numparam} {incr i} {
        set val$i 0.000000
        set difference$i 0.000000
    }
}

proc getLast {} {
    global numparam 
    global oval0 oval1 oval2 oval3 oval4 oval5 oval6 oval7 oval8 oval9
    global val0 val1 val2 val3 val4 val5 val6 val7 val8 val9
    for {set i 0} {$i < $numparam} {incr i} {
        set val$i [set oval$i]
    }
}

proc getLocation {i} {
    global numparam 
    global val0 val1 val2 val3 val4 val5 val6 val7 val8 val9
    global difference0 difference1 difference2 difference3 difference4 difference5 difference6 difference7 difference8 difference9
    if {$i == 1} {set val$i [expr [emc_abs_act_pos 0] - [set difference$i]]} 
    if {$i == 3} {set val$i [expr [emc_abs_act_pos 0] - [set difference$i]]}
    if {$i == 4} {set val$i [expr [emc_abs_act_pos 1] - [set difference$i]]} 
    if {$i == 6} {set val$i [expr [emc_abs_act_pos 1] - [set difference$i]]} 
    if {$i == 7} {set val$i [expr [emc_abs_act_pos 2] - [set difference$i]]} 
    if {$i == 8} {set val$i [expr [emc_abs_act_pos 2] - [set difference$i]]} 


}

proc setVarValues {} {
    global vartext
    global numparam val0 val1 val2 val3 val4 val5 val6 val7 val8 val9
    global num0 num1 num2 num3 num4 num5 num6 num7 num8 num9
    for {set i 0} {$i < $numparam} {incr i} {
        set locate [$vartext search [set num$i] 1.0 ]
        $vartext mark set insert "$locate +5c"
        $vartext delete insert "insert lineend"
        $vartext insert insert [set val$i]
    }
}



proc shiftFocus {whichway} {
    global fields numparam
    set window [focus]
    set last [string trim [string length $window]]
    set last [expr $last - 1]
    set windowx [string index $window $last]
    set windownext [expr $windowx + $whichway]
    if {$windownext == $numparam} {
        set windownext 0
    } elseif {$windownext < 0} {
        set windownext [expr $numparam -1]
    }
    focus [string range $window 0 [expr $last - 1]]$windownext
}

proc saveVarFile {name} {
    global vartext
    catch {file copy -force $name $name.bak}
    if {[catch {open $name w} fileout]} {
        puts stdout [msgcat::mc "can't save %s" $name]
        return
    }
    puts $fileout [$vartext get 1.0 end]
    catch {close $fileout}
}

proc loadVarFile {} {
    global top paramfilename
    saveVarFile $paramfilename
    emc_task_plan_init
}

# loads parameter file into interpreter and closes window
proc closeWindow {} {
    loadVarFile
    destroy .
}

proc saveVarFile {name} {
    global vartext
    catch {file copy -force $name $name.bak}
    if {[catch {open $name w} fileout]} {
        puts stdout [msgcat::mc "can't save %s" $name]
        return
    }
    puts $fileout [$vartext get 1.0 end]
    catch {close $fileout}
}

proc doSave {} {
    setVarValues
    loadVarFile
}

proc doProbe {} {
    #copy the selected presets into our working "registers"
    #emc then reads the values from the .var file
    global coordsys coordsysCurrent
    set coordsys $coordsysCurrent
    getVarAddress
    getLast
    doSave

    #do it!
    emc_mode auto
    emc_abort
    emc_open $::emc::NCFILES_DIR/probebuddy.ngc
 #this is somewhat dangerous as it runs whatever program is open if it cant find probebuddy.ngc
    emc_run 
}

proc doAbort {}  { emc_abort }

# set the initial coordinate system and find values.
set coordsysCurrent 2000
set coordsys $coordsysCurrent
getVarAddress

