#!/bin/sh
# engdraw - ABACUS engineering interface 
# the next line restarts using wish \
exec nice wish "$0" "$@" -geometry +0+0

#exec nice wish4.1 "$0" "$@" -geometry +0+0

#$Id: engdraw 0.1a3 1999/11/03 11:00:00 abacus Exp $

#set engdraw(library) "/usr/lib/engdraw"
set engdraw(in_development) 0
set engdraw(debug) 1

set engdraw(date) "991103"
set engdraw(version) "0.1a3"
#
#
catch { set engdraw(abacusversion) [exec ls -c /home/abacus/ | grep "\*" | sed 's/\*//' | xargs ident -q | grep Id 2> /dev/null | sed -e 's/.*c,v//' | sort -rn] }
catch { puts stdout "engdraw(abacusversion) $engdraw(abacusversion)" }
#
#

#wm geom . [winfo screenwidth .]x[winfo screenheight .]+0+0

#
# -----------------------------------------------------------------------------
#
# Proc:    dsk_welcome
# Desc:    Shows an informational "welcome" window when starting up.
# In:      cmd: "show" or "hide"
# Out:     ""
# Side FX: none
#

proc dsk_welcome {cmd} {
    global engdraw

    set bgcol gray
    #set bgcol gray82
    set t .dsk_welcome

    if {$cmd == "hide"} {
	catch "destroy $t"
	return ""
    }
    
    toplevel $t -bg $bgcol
    wm withdraw $t

    frame $t.f -bd 2 -relief raised -bg $bgcol
    pack $t.f

    frame $t.f1 -bd 2 -relief groove -bg $bgcol
    pack $t.f1 -in $t.f -padx 8 -pady 8

    label $t.lLabel -text "Welcome to..." -anchor center \
	    -font -*-helvetica-medium-r-*-*-14-* -bg $bgcol
    pack $t.lLabel -in $t.f1 -padx 8 -pady 8 -fill x -expand yes

    label $t.lengdraw -text "engdraw" -font -adobe-utopia-regular-i-*-*-25-*-*-*-*-*-*-* \
	    -width 16 -bg $bgcol
#    label $t.lengdraw -text "engdraw" -font -*-helvetica-bold-r-*-*-24-* \
#	    -width 16 -bg $bgcol
#    image create bitmap welcome_bm -data $engdraw(welcome_bm) -foreground black -background white
#    label $t.lengdraw -image welcome_bm -bg $bgcol
    pack $t.lengdraw -in $t.f1 -padx 6 -pady 2 -fill x -expand yes

    message $t.lVersion -text \
"Version $engdraw(version), dated $engdraw(date) tk:[info patchlevel]
Copyright (C) 1997 Frank McNamara

I hope that you will find this 
interesting and useful

ABACUS 4 blocks may be edited and documented with this program
on any running system within network reach of this machine.


" \
	    -font -*-helvetica-medium-r-*-*-14-* -bg $bgcol \
	    -aspect 1000 -justify center

    pack $t.lVersion -in $t.f1 -padx 8 -pady 8 -fill x -expand yes

    if $engdraw(in_development) {
	label $t.lDevel -text "...in Development..." \
		-font -*-helvetica-bold-o-*-*-14-* -bg $bgcol
	pack $t.lDevel -in $t.f1 -padx 8 -pady 8 -fill x -expand yes
    }

    frame $t.f2 -bd 2 -relief groove -bg $bgcol
    pack $t.f2 -in $t.f -fill x -padx 8 -pady 8
    
    label $t.lProgress -text "Loading please wait..." -anchor w -bg $bgcol -width 25
    pack $t.lProgress -in $t.f2 -fill x -anchor w -padx 8

    update idletasks
    set x [expr [winfo screenwidth $t]/2 - [winfo reqwidth $t]/2 \
	    - [winfo vrootx [winfo parent $t]]]
    set y [expr [winfo screenheight $t]/2 - [winfo reqheight $t]/2 \
	    - [winfo vrooty [winfo parent $t]]]
    wm geom $t +$x+$y
    wm title $t "Starting..."
    wm deiconify $t
    update

    return ""
}
proc dsk_progress {string} {
    if ![winfo exists .dsk_welcome] return
    
    .dsk_welcome.lProgress config -text $string
    update idletasks
}



dsk_welcome show

set w .
cd /home/abacus/

#wm maxsize .

set font  -adobe-helvetica-medium-r-*-*-12-*-*-*-*-*-*-*
set c ${w}frame.c
set tagnames xaxistext
set blockno 0
set thetextfile	"/dev/null"

label ${w}msg -font -adobe-times-bold-r-*-*-12-*-*-*-*-*-*-* -justify left -width 130\
 -text "watch this space" -wraplength 850 
pack ${w}msg -side bottom

frame ${w}t
pack ${w}t  -side top -fill x


######################## Page size stuff #############################

set title_program_version	"[exec /bin/ls -l [info script] | cut  -c 43-90]"
set title_program_version	"[info script] V 0.1 980626 tk:[info patchlevel]"
set title_program_version	"$engdraw(version), dated $engdraw(date) tk:[info patchlevel]"
set pageh	 800
set pageh	1200
set pageh	1100
set no_of_pages_h 1
set no_of_pages_w 1
set pagewidth_	10i
set pageheight_	6.5i
set thetagfile "/home/abacus/tagfiles/spares.tagfile"
set thetagfile ""
set title_thenode [info hostname]
# set title_thenode c2co
set print_dev   pslaser
set print_dev   lp0
set print_dev   lp
set grid_size	10

#catch { set pageh [lindex $argv 0] }
if { $argc > 0 } { set title_thenode       [lindex $argv 0] }
if { $argc > 1 } { set thetagfile    [lindex $argv 1] }
if { $argc > 2 } { set pageh               [lindex $argv 2] }
if { $argc > 3 } { set print_dev           [lindex $argv 3] }

## if { $argc > 3 } { set no_of_pages_h [lindex $argv 3] }
## if { $argc > 4 } { set no_of_pages_w [lindex $argv 4] }
## if { $argc > 5 } { set pagewidth_   "[lindex $argv 5]" }
## if { $argc > 6 } { set pageheight_  "[lindex $argv 6]" }

set title_Customer_Kund "McHedlund / Bristol Babcock AB"
set title_Customer_Kund "Customer Name"
set title_Customer_Kund_2  "Site"
set title_Date_Datum    [exec date "+%y-%m-%d"]
set title_DrawnBy_RitadAv  "Abacus User"
set title_Title_Titel   "The Drawing Title"
set title_REV  "1"
set title_REV_2  "2"
set title_REV_3  "3"
set title_REV_4  "4"
set title_REV_5  "5"

wm title . "ABACUS Engineering Interface at $title_thenode ($thetagfile)"
#puts stdout "[info script] \"$thetagfile\" $pageh $no_of_pages_h $no_of_pages_w $pagewidth_ $pageheight_"
puts stdout "[info script] $title_thenode \"$thetagfile\" $pageh $print_dev"

#puts stdout "pageh=$pageh, no_of_pages_h=$no_of_pages_h, no_of_pages_w=$no_of_pages_w, pagewidth_=$pagewidth_, pageheight_=$pageheight_"

proc set_constants {} {
	global  pageh pagew no_of_pages_h no_of_pages_w pagehsize pagewsize 
	
	set pagew	[expr $pageh * 11 / 8 ]
	set pagehsize [expr $pageh * $no_of_pages_h]
	set pagewsize [expr $pagew * $no_of_pages_w]
}
set_constants

######################## file menu stuff #############################
menubutton ${w}t.file -text "file" -menu ${w}t.file.m -underline 0
menu ${w}t.file.m -tearoff 0
${w}t.file.m add command -label "Restart this program" -command {
 exec nice /home/abacus/engdraw $title_thenode $thetagfile \
   $pageh -geometry +0+0 &
 exit
 }

${w}t.file.m add command -label "Start another program" -command {
 exec nice /home/abacus/engdraw  -geometry +20+20 &
# exit
 }

${w}t.file.m add separator

${w}t.file.m add command -label "Load tag file" -command {
 global thetagfile
 	if { $numberofitems != 0 } {
	 if { [tk_messageBox -type yesno -default yes \
	   -message "clear all objects from display" -icon question] } {
		foreach ttt [$c find all] {
			$c delete $ttt
		}
		catch { unset commands }
		set thetagfile [tk_getOpenFile -initialdir /home/abacus/tagfiles/ -initialfile $thetagfile]
		if { $thetagfile != ""} { source $thetagfile }
		catch { eval $commands(title_thenode) }
		foreach comm [ array names commands] { eval $commands($comm) }
		fix_names
	 }
	} else {
	       catch { unset commands }
	       set thetagfile [tk_getOpenFile -initialdir /home/abacus/tagfiles/ -initialfile $thetagfile]
	       if { $thetagfile != ""} { source $thetagfile }
	       foreach comm [ array names commands] { eval $commands($comm) }
	       fix_names
	
	}
}

${w}t.file.m add command -label "Merge tag file" -command {
 global thetagfile
 set thetagfile [tk_getOpenFile -initialdir /home/abacus/tagfiles/ -initialfile $thetagfile]
 if { $thetagfile != ""} { source $thetagfile }
 foreach comm [ array names commands] { eval $commands($comm) }
 fix_names
}

${w}t.file.m add command -label "Save tag file" -command {
 global thetagfile
 #puts stdout "thetagfile $thetagfile"
 set thetagfile [tk_getSaveFile -initialfile $thetagfile -initialdir /home/abacus/tagfiles/ ]
 if { $thetagfile != ""} { 
   set fileId [open $thetagfile w]
   puts $fileId [format "#  /home/abacus/engdraw"]
   puts $fileId "# $thetagfile created by /home/abacus/engdraw\n# at [exec date]\n"
   
   foreach comm [ array names commands] {
   	puts $fileId "set commands($comm) \{$commands($comm)\}"
	#puts $fileId $commands($comm)
	}
   
   foreach item [$c find withtag fline] {
     puts $fileId "\$c create [$c type $item] [$c coords $item] -tag fline"
     }
   foreach item [$c find withtag flinearrow] {
     puts $fileId "\$c create [$c type $item] [$c coords $item] -arrow last -tag flinearrow"
     }
   foreach item [$c find withtag flinecircle] {
     puts $fileId "\$c create [$c type $item] [$c coords $item] -arrow last -arrowshape {6 3 3} -tag flinecircle"
     }
   foreach item [$c find withtag flinedashed] {
     set line_x [lindex [$c coords $item] 0]
     set line_y [lindex [$c coords $item] 1]
     set xxx1 [lindex [$c coords $item] 2]
     set yyy1 [lindex [$c coords $item] 3]
     if { [expr abs( $line_x - $xxx1 ) - abs (  $yyy1 - $line_y ) ] > 0 } then { 
         puts $fileId "\$c create [$c type $item] [$c coords $item] -stipple @engdraw_dashed-h.xbm -tag flinedashed"
	 #$c create line $line_x $line_y $xxx1 $yyy1 -stipple @engdraw_dashed-h.xbm -tag flinedashed
       } else {
         puts $fileId "\$c create [$c type $item] [$c coords $item] -stipple @engdraw_dashed-v.xbm -tag flinedashed"
	 #$c create line $line_x $line_y $xxx1 $yyy1 -stipple @engdraw_dashed-v.xbm -tag flinedashed
       }

     #puts $fileId "\$c create [$c type $item] [$c coords $item] -stipple @engdraw_dashed-h.xbm -tag flinedashed"
     }
   
   close $fileId 
   fix_names
   }
 }
${w}t.file.m add separator

${w}t.file.m add command -label "Edit tag file in Nedit" -command {
 global thetagfile
 set thetagfile [tk_getOpenFile -initialdir /home/abacus/tagfiles/ -initialfile $thetagfile]
 if { $thetagfile != ""} { exec nedit $thetagfile & }
}

${w}t.file.m add separator

${w}t.file.m add command -label "New text file" -command {
 global thetextfile
	set filename [tk_getSaveFile -initialdir /home/abacus/tagfiles/textfiles/ \
 	 -initialfile $newtg.text]
 	if { $filename != ""} { 
		exec nedit -create $filename &
		set editmode text-file
		}
 	}

${w}t.file.m add command -label "Edit text file" -command {
 if { $thetextfile == ""} { set thetextfile $newtg.text }
 set thetextfile [tk_getOpenFile -initialdir /home/abacus/tagfiles/textfiles/ -initialfile $thetextfile]
 if { $thetextfile != ""} { 
       exec nedit $thetextfile &
       set editmode text-file
       }

}
${w}t.file.m add command -label "Select text file" -command {
 global thetextfile
 set thetextfile [tk_getOpenFile -initialdir /home/abacus/tagfiles/textfiles/ -initialfile $newtg.text]
 if { $thetextfile != ""} { set editmode text-file }

}

${w}t.file.m add separator
################ Postscript menu item stuff ###########################

${w}t.file.m add command -label "Create ps file" -command {
 $c postscript -file  \
 [tk_getSaveFile -initialdir /home/abacus/tagfiles/ -initialfile $thetagfile.ps]\
 -height $pageh -width $pagew -rotate 1 -pagewidth 10i -pageheight 6.5i\
  -x 0 -y 0 -colormode mono -pageanchor c

# -height $pageh -width $pagew -rotate 1 -pagewidth 11i -pageheight 8i\
# -height 800 -width 1100 -rotate 1 -pagewidth 10i -pageheight 7i
 # -x 0 -y 0
# -height 330 -width 500 -rotate 1 
 }
#${w}t.file.m add separator
 

${w}t.file.m add command -label "Print to $print_dev" -command {
 $c postscript -file engtk.temporary.postscript.file.ps\
 -height $pageh -width $pagew -rotate 1 -pagewidth 10i -pageheight 6.5i\
  -x 0 -y 0 -colormode mono -pageanchor c
  
  exec lpr -P$print_dev engtk.temporary.postscript.file.ps &

 }

${w}t.file.m add command -label "Print preview - Ghostview" -command {
 $c postscript -file engtk.temporary.postscript.file.ps\
 -height $pageh -width $pagew -rotate 1 -pagewidth 10i -pageheight 6.5i\
  -x 0 -y 0 -colormode mono -pageanchor c
  
  
  exec ghostview ./engtk.temporary.postscript.file.ps &

 }
${w}t.file.m add command -label "Print preview - gv" -command {
 $c postscript -file engtk.temporary.postscript.file.ps\
 -height $pageh -width $pagew -rotate 1 -pagewidth 10i -pageheight 6.5i\
  -x 0 -y 0 -colormode mono -pageanchor c
  
  
  exec gv ./engtk.temporary.postscript.file.ps &

 }
${w}t.file.m add separator

######################## title menu stuff #############################

${w}t.file.m add command -label "Title Box data" -command { 
	global  title_Customer_Kund title_Date_Datum title_DrawnBy_RitadAv title_Title_Titel 
	global title_Customer_Kund_2 title_REV  title_REV_2 title_REV_3 title_REV_4 title_REV_5
  
	toplevel .new 
	wm title .new "Title stuff"
	
	
	foreach field {title_Customer_Kund title_Customer_Kund_2 title_Title_Titel title_Date_Datum title_DrawnBy_RitadAv \
	  title_REV title_REV_2 title_REV_3 title_REV_4 title_REV_5} {
		label .new.l$field -text $field -anchor w
		entry .new.e$field -textvariable $field -relief sunken -width 30
		grid .new.l$field .new.e$field -sticky news
		bind .new.e$field <Return> "draw_boundries ; destroy .new"
		}
 	#button .new.b1 
 	button .new.b3 
 	#.new.b1 configure -text "Cancel" -command {destroy .new}
 	.new.b3 configure -text Enter \
 	   -command {	draw_boundries
 	   		
 			destroy .new }
 	#grid .new.b1 .new.b3 -sticky news
 	grid .new.b3 -sticky news
	
		
	}


${w}t.file.m add separator

############################ setup ##################################
${w}t.file.m add command -label "Setup parameters" -command { 
	global pageh no_of_pages_h no_of_pages_w pagewidth_ pageheight_	
	global print_dev grid_size
	  
	toplevel .setup 
	wm title .setup "Setup parameters"
	
	
	foreach field { print_dev title_thenode grid_size } {
		label .setup.ll$field -text $field -anchor w
		entry .setup.ee$field -textvariable $field -relief sunken -width 30
		grid .setup.ll$field .setup.ee$field -sticky news
		bind .setup.ee$field <Return> "draw_boundries ; destroy .setup"
		}
 	#button .setup.b1 
 	button .setup.b3 
 	#.setup.b1 configure -text "Cancel" -command {destroy .setup}
 	.setup.b3 configure -text Enter \
 	   -command {	buildtags ; fix_names ; draw_boundries
 	   		
 			destroy .setup }
 	#grid .setup.b1 .setup.b3 -sticky news
 	grid .setup.b3 -sticky news
	
		
	}


################ Close menu item stuff ###########################
${w}t.file.m add command -label "Close" -command { exit }


######################## listboxes stuff #############################
proc Scroll_Set {scrollbar geoCmd offset size} {
	if {$offset != 0.0 || $size != 1.0} {
		eval $geoCmd		  ;# Make sure it is visible
		$scrollbar set $offset $size
	} else {
		set manager [lindex $geoCmd 0]
		$manager forget $scrollbar								;# hide it
	}
}

proc Scroll_Set_2 {scrollbar geoCmd offset size} {
		eval $geoCmd		  ;# Make sure it is visible
		$scrollbar set $offset $size
}

proc Scrolled_Listbox { f args width_15 height_12 } {
	frame $f
	listbox $f.list -width $width_15 -height $height_12 -font -adobe-courier-bold-r-*-*-12-*-*-*-*-*-*-*\
		-xscrollcommand [list Scroll_Set $f.xscroll \
			[list grid $f.xscroll -row 1 -column 0 -sticky we]] \
		-yscrollcommand [list Scroll_Set_2 $f.yscroll \
			[list grid $f.yscroll -row 0 -column 1 -sticky ns]]

	scrollbar $f.xscroll -orient horizontal -command [list $f.list xview]
	scrollbar $f.yscroll -orient vertical -command [list $f.list yview]
	grid $f.list $f.yscroll -sticky news
	grid $f.xscroll -sticky news
	grid rowconfigure $f 0 -weight 1
	grid columnconfigure $f 0 -weight 1
	return $f.list
}

proc Scrolled_Listbox_2 { f args width_15 height_12 } {
	frame $f
	listbox $f.list -width $width_15 -height $height_12 -font -adobe-courier-bold-r-*-*-12-*-*-*-*-*-*-*\
		-xscrollcommand [list Scroll_Set_2 $f.xscroll \
			[list grid $f.xscroll -row 1 -column 0 -sticky we]] \
		-yscrollcommand [list Scroll_Set_2 $f.yscroll \
			[list grid $f.yscroll -row 0 -column 1 -sticky ns]]

	scrollbar $f.xscroll -orient horizontal -command [list $f.list xview]
	scrollbar $f.yscroll -orient vertical -command [list $f.list yview]
	grid $f.list $f.yscroll -sticky news
	grid $f.xscroll -sticky news
	grid rowconfigure $f 0 -weight 1
	grid columnconfigure $f 0 -weight 1
	return $f.list
}

frame .tglist
frame .tglist.f
set listbox [Scrolled_Listbox .tglist.f.listbox  { tripe and custard } 15 8 ]
label .tglist.f.listboxlabel -text "tag list"


set newtg qwerty
set blocknolist qwerty
label .tglist.f.blocklistlabel -text "block list"

#set blocklist [Scrolled_Listbox .tglist.f.blocklist $blocknolist 15 4 ]
set blocklist [Scrolled_Listbox .tglist.f.blocklist $blocknolist 15 8 ]
#set blocklist [Scrolled_Listbox .tglist.f.blocklist $blocknolist 15 12 ]

set itemnolist qwerty
#set itemlist [Scrolled_Listbox_2 .tglist.f.itemlist $itemnolist 15 4 ]
set itemlist [Scrolled_Listbox_2 .tglist.f.itemlist $itemnolist 15 8 ]
#set itemlist [Scrolled_Listbox_2 .tglist.f.itemlist $itemnolist 15 12 ]
label .tglist.f.itemlistlabel -text "item list"

proc fix_names {} {
	global title_thenode c commands itemnolist itemlist thetagfile numberofitems
	set itemnolist [array names commands]

	$itemlist delete 0 end
	set numberofitems 0
	#foreach item $itemnolist { }
	foreach item [lsort $itemnolist] { 
	  if { [lindex [split $item "_"] 0] != "title" } { 
	    $itemlist insert end "$item" 
	    incr numberofitems
	    } 
	  }

	draw_boundries
}

#################### tglist packing stuff ##################
pack .tglist .tglist.f -side left
pack .tglist.f  -side bottom
pack	.tglist.f.listboxlabel .tglist.f.listbox \
	.tglist.f.blocklistlabel .tglist.f.blocklist \
	.tglist.f.itemlistlabel .tglist.f.itemlist \
	  -side top


##################### Block No entry stuff ##################
label .tglist.f.blocknolabel -text "Block No."
entry .tglist.f.blockno -textvariable blockno
pack  .tglist.f.blocknolabel .tglist.f.blockno -side top -pady 2 -anchor w


##################### Replace Change stuff #################
label .tglist.f.replacelabel -text "Replacement Block No."
entry .tglist.f.replace -textvariable newblockno
button .tglist.f.replaceb -text "Replace block" -command \
  {

    foreach item [$c find withtag tagarray($newitem)] {\
	$c itemconfig $item  -fill red }
    if { [tk_messageBox -type yesno -default yes \
	    -message "Replace $blockno with $newblockno" -icon question] } {

	eval $commands(${blockno}_block)  ;# setup xx & yy
	set blockno [string trim $blockno]
	puts stdout "${blockno}_block xx = $xx,  yy = $yy"
	
	foreach item [$c find withtag tagarray($newitem)] {\
		$c itemconfig $item  -fill black }

	 $c delete  -tag tagarray($newitem)
	 catch { unset commands($newitem) }
	fix_names

	#eval { unset commands(${blockno}_block) } ;
	set blockno [string trim $newblockno]
	set blkline [exec engnet $title_thenode b$blockno,p | \
	 tr ";" "\n" | sed "s/^B.* type /TY/" | \
	 sed "s/^B/bl/" | sed "s/\\(^..\\)/set \\1 {/" | sed "s/\\(.$\\)/\\1}/" | \
	 sed "s/\(.*\)//" | sed "s/   / /g" | sed "s/  / /g" ]

	set blkline2 [exec engnet $title_thenode b$blockno,p | \
	 tr ";" "\n" | sed "s/^B.* type /TY/" | \
	 sed "s/^B/bl/" | sed "s/\\(^..\\)/set \\1b {/" | sed "s/\\(.$\\)/\\1}/" | \
	 sed "s/   / /g" | sed "s/  / /g" ]

	eval $blkline
	eval $blkline2
	eval { draw_block }
  
     }
  foreach item [$c find withtag tagarray($newitem)] {\
	  $c itemconfig $item  -fill black }
  }
pack .tglist.f.replacelabel .tglist.f.replace .tglist.f.replaceb   -side top -pady 2 -anchor w
##################### Parameter entry stuff #################
#label .tglist.f.paralabel -text "parameter"
entry .tglist.f.para -textvariable para
button .tglist.f.parab -text "Enter parameter" -command \
  {
  #puts stdout "exec engnet $title_thenode \"b$blockno,con,$para\""
  exec engnet $title_thenode \"b$blockno,con,$para\"
  #exec eng2 "b$blockno\;con\;$para"
  #set para ""
  set blockno_save $blockno
  foreach comm [ array names commands] {
      eval $commands($comm)
      }
  set blockno [format "%d" $blockno_save]

  }
pack  .tglist.f.parab .tglist.f.para -side top -pady 2 -anchor w

##################### Update button stuff #################
#button .tglist.f.update -text "Update from ABACUS" -command update_blocks
set cont_update 0
## checkbutton .tglist.f.update  -text "cont.update"\
## 	 -variable cont_update -relief flat
## proc update_blocks {} {
##     global title_thenode c blockno commands cont_update
##     
##     if $cont_update {
## 	 catch { set blockno_save $blockno }
## 
## 	 foreach ttt [$c find all] { catch { $c delete $ttt } }
## 	 foreach comm [ array names commands] { catch { $commands($comm) } }
## 	 catch { set blockno [format "%d" $blockno_save] }
## 	 catch { draw_boundries }
## 
##     }
##     after 5000 update_blocks
##   }
## pack  .tglist.f.update -side top -pady 2 -anchor w

button .tglist.f.update  -text "update" -command update_blocks

proc update_blocks {} {
	global title_thenode c blockno commands cont_update
    
	catch { set blockno_save $blockno }

## 	foreach ttt [$c find all] { catch { $c delete $ttt } }
## 	foreach comm [ array names commands] { catch { $commands($comm) } }
## 	catch { set blockno [format "%d" $blockno_save] }
## 	catch { draw_boundries }

  foreach ttt [$c find all] { 
     if { [lsearch [$c gettags $ttt] fline* ] < 0 } { catch { $c delete $ttt } } }
  foreach comm [ array names commands] { eval $commands($comm)  }
  fix_names

  }
pack  .tglist.f.update -side top -pady 2 -anchor w


## set editstyle long
## foreach style { long short,nb1 } {
## 	radiobutton .tglist.f.$style  -text "$style print style "\
## 	 -variable editstyle -relief flat -value $style
##     pack  .tglist.f.$style -side top -pady 2 -anchor w
## 
## }


#################### tglist binding stuff ##################
bind $listbox <ButtonRelease-1> { set newtg [eval "%W get @%x,%y"]
 ## if { $newtg == "** rebuild taglist **" } { puts stdout "** rebuild taglist **" }
 ## if { $newtg == "** new tg **" } { puts stdout "** new tg **" }
 ## wm title . "ABACUS Engineering Interface - tag $newtg"

 if { $newtg == "tg   spare"} { eval {set blocknolist [exec  engnet $title_thenode b1,xb40000,long,.tg | grep "$newtg" | cut -c 2-6] }
 } else { eval { set blocknolist [exec  engnet $title_thenode b1,xb40000,.tg | grep "$newtg" | cut -c 2-6] } }
# if { $newtg == "tg   spare"} { eval {set blocknolist [exec  engnet $title_thenode b1,xb40000,long,.tg.nn | grep "$newtg" | sed -e "s/^b//" -e "s/;tg.........../ /"] }
# } else { eval { set blocknolist [exec  engnet $title_thenode b1,xb40000,.tg.nn | grep "$newtg" | sed -e "s/^b//" -e "s/;tg.........../ /"] } }


 $blocklist delete 0 end
 foreach blk $blocknolist { $blocklist insert end "$blk" }
 }
 
bind $itemlist <ButtonRelease-1> { 
   set newitem [eval "%W get @%x,%y"]
   set itembits [split $newitem "_"]

   set blockno [string trim [lindex $itembits 0] ]
   set newblockno [string trim [lindex $itembits 0] ]
   set editmode [string trim [lindex $itembits 1] ]
   if { [lsearch $editmode /* ] != -1 } {
    set editmode text-file
    set thetextfile [lindex $itembits 1]
    }
}

proc do_msg {} {
  global c w editmode thetextfile blockno newtg tagslist title_thenode 
  if { $editmode == "text-file" } {
    ${w}msg configure -text "TAG: $newtg MODE: $editmode FILE: $thetextfile ([exec head -n 1 $thetextfile | cut -c 1-80]...)"
  } else {
    ${w}msg configure -text "TAG: $newtg MODE: $editmode BLOCK-NO: $blockno"
  }
  
  if { $tagslist == "" } {
    ${w}msg configure -text  "No server running on $title_thenode, use \"(cd /home/abacus ; faucet 9000 -ioe bash - )&\" "
    dsk_progress "No server running on $title_thenode"

  }
  catch { $c config -cursor "@./engdraw_$editmode.xbm black" }
  
  after 500 do_msg
}

#################### blocknolist binding stuff ##################
bind $blocklist <ButtonRelease-1> { set blockno [string trim [eval "%W get @%x,%y"] ]
 
 if { $editmode == "text-file" } { set editmode block }
 ## wm title . "ABACUS Engineering Interface - tag $newtg, block $blockno"
 
 }


######################## help menu stuff #############################
menubutton ${w}t.help -text "Help Hjlp" -menu ${w}t.help.m -underline 0
menu ${w}t.help.m -tearoff 0


catch { ${w}t.help.m delete 0 end }
${w}t.help.m  add command -label "Help in English" -command { do_help English }
${w}t.help.m  add command -label "Hjlp p Svenska" -command { do_help Svenska }

proc do_help { language } {
	
	catch { destroy .helpbox }
	toplevel .helpbox
	frame .helpbox.f
	pack .helpbox.f -side top -fill both -expand true
	button .helpbox.dismiss -text dismiss -command { destroy .helpbox }
	set t [text .helpbox.f.t -setgrid true -wrap word \
		-height 30 -width 90 \
		-yscrollcommand ".helpbox.f.sy set" ]
	scrollbar .helpbox.f.sy -orient vert -command ".helpbox.f.t yview"
	pack .helpbox.f.sy -side right -fill y
	pack .helpbox.f.t -side left -fill both -expand true
	
	wm title .helpbox "helpfile /home/abacus/engdraw.help.$language\n\n"

	catch { .helpbox.f.t insert end "[exec cat /home/abacus/engdraw.help.$language]" }
	
	pack .helpbox.dismiss -side bottom

#	wm geom .helpbox 800x500+50+50
	wm geom .helpbox +50+50

	wm deiconify .helpbox
	update
}

######################## type menu stuff #############################
menubutton ${w}t.type -text "type of item" -menu ${w}t.type.m -underline 0
menu ${w}t.type.m -tearoff 0


catch { ${w}t.type.m delete 0 end }

set editmode block
foreach edito { block xref {short-print} {long-print} text-file line {line-arrow} {line-circle} {line-dashed} } {
	${w}t.type.m add radiobutton -label  "$edito"\
	 -variable editmode -value $edito

}

######################## util menu stuff #############################
menubutton ${w}t.util -text "utilities" -menu ${w}t.util.m -underline 0
menu ${w}t.util.m -tearoff 0


catch { ${w}t.util.m delete 0 end }

${w}t.util.m add command -label "undo" -command { pop_commands }

${w}t.util.m add command -label "run text mode engineers mode" -command { exec xterm -e eng & }
##catch { source /home/abacus/engtk_nodes.tcl }
${w}t.util.m add separator
${w}t.util.m add command -label "rebuild taglist" -command { buildtags ; fix_names }

${w}t.util.m add separator
${w}t.util.m add command -label "show block number ranges" -command { 
 catch { destroy .eng }
 toplevel .eng
 #label .eng.look -height 25 -width 80 -text [exec engnet $title_thenode look] -font -adobe-courier-medium-r-*-*-10-*-*-*-*-*-*-*
 text .eng.look -height 25 -width 80 -font -adobe-courier-medium-r-*-*-10-*-*-*-*-*-*-*
 .eng.look insert end [exec engnet $title_thenode look]
 button .eng.close -text "close" -command { destroy .eng }
 pack .eng.look .eng.close 
 }

${w}t.util.m add command -label "open block print" -command { 
 catch { destroy .bprint }
 toplevel .bprint
 #label .bprint.look -height 25 -width 80 -text [exec engnet $title_thenode look] -font -adobe-courier-medium-r-*-*-10-*-*-*-*-*-*-*
 text .bprint.look -height 25 -width 80 -font -adobe-courier-medium-r-*-*-10-*-*-*-*-*-*-*
 .bprint.look insert end [exec engnet $title_thenode b$blockno,short,nb1,p ]
 button .bprint.close -text "close" -command { destroy .bprint }
 button .bprint.exec -text "exec" -command {
  
  set thearg [.bprint.look get 1.0 end ]

  set tfile [open temporary.engdraw.file.will.be.deleted w ]
  puts $tfile [format "echo \"\nfrank\nxb99\n"]
  puts $tfile $thearg
  puts $tfile [format "\" | eng  ; echo\n"]
  close $tfile


  catch { exec sh temporary.engdraw.file.will.be.deleted > temporary.engdraw.file.will.be.deleted.lst }
  
  set tfile [open temporary.engdraw.file.will.be.deleted.lst r ]

##   .bprint.look delete 1.0 end
##   while  {[gets $tfile line] >= 0} {
##   	.bprint.look insert end "$line\n"
##   	
##   }
##   close $tfile
  
  catch { file delete temporary.engdraw.file.will.be.deleted }
  catch { file delete temporary.engdraw.file.will.be.deleted.lst }
  update_blocks
  
  destroy .bprint }
  
 pack .bprint.look .bprint.close  .bprint.exec
 }


${w}t.util.m add separator
${w}t.util.m add command -label "clear item" -command { 

    foreach item [$c find withtag tagarray($newitem)] {\
	    $c itemconfig $item  -fill red }
    if { [tk_messageBox -type yesno -default yes \
	    -message "remove $newitem" -icon question] } {
	     $c delete  -tag tagarray($newitem)
  	     catch { unset commands($newitem) }
     }
    foreach item [$c find withtag tagarray($newitem)] {\
	    $c itemconfig $item  -fill black }

    fix_names

}

${w}t.util.m add command -label "clear all items" -command { 
	if { [tk_messageBox -type yesno -default yes \
		-message "clear all objects from display" -icon question] } {
	 	foreach ttt [$c find all] {
		 	$c delete $ttt
	 	}
  		unset commands
	 }
 fix_names
 }
${w}t.util.m add separator

${w}t.util.m add command -label "enter tcl/tk command" -command { 
 toplevel .tcl
 entry .tcl.enter -textvariable command_ -width 80
 button .tcl.doit -text "doit" -command {puts stdout $command_ ; catch { eval $command_ }; }
 button .tcl.quit -text "quit" -command {destroy .tcl}
 pack .tcl.enter .tcl.doit .tcl.quit
 }

######################## find unallocated blocks menu stuff #############################
menubutton ${w}t.find -text "list unallocated blocks" -menu ${w}t.find.m -underline 0
menu ${w}t.find.m -tearoff 0


catch { ${w}t.find.m delete 0 end }

${w}t.find.m add command -label "list unallocated index block" -command { find_free_block "index" }
${w}t.find.m add command -label "list unallocated checklist block" -command { find_free_block "checklist" }
${w}t.find.m add command -label "list unallocated switch block" -command { find_free_block "switch" }
${w}t.find.m add command -label "list unallocated pattern block" -command { find_free_block "pattern" }
${w}t.find.m add separator
${w}t.find.m add command -label "list unallocated control block" -command { find_free_block "control" }
${w}t.find.m add command -label "list unallocated p.i.d. block" -command { find_free_block "p.i.d." }

${w}t.find.m add separator
${w}t.find.m add command -label "list unallocated alarm code block" -command { find_free_block "alarm code" }
${w}t.find.m add separator
${w}t.find.m add command -label "list unallocated pibus ai block" -command { find_free_block "pibus ai" }
${w}t.find.m add command -label "list unallocated K48 point block" -command { find_free_block "K48 point" }
${w}t.find.m add command -label "list unallocated N45 module block" -command { find_free_block "N45 module" }
${w}t.find.m add command -label "list unallocated analogue out block" -command { find_free_block "analogue out" }
${w}t.find.m add command -label "list unallocated indata I/O block" -command { find_free_block "indata I/O" }
${w}t.find.m add separator
${w}t.find.m add command -label "list unallocated dig output block" -command { find_free_block "dig output" }
${w}t.find.m add command -label "list unallocated p.d.o. block" -command { find_free_block "p.d.o." }
${w}t.find.m add command -label "list unallocated dig input block" -command { find_free_block "dig input" }
${w}t.find.m add command -label "list unallocated pulse counter block" -command { find_free_block "pulse counter" }
${w}t.find.m add separator
${w}t.find.m add command -label "list unallocated scan control block" -command { find_free_block "scan control" }
${w}t.find.m add command -label "list unallocated sequencer block" -command { find_free_block "sequencer" }
${w}t.find.m add command -label "list unallocated subroutine block" -command { find_free_block "subroutine" }
${w}t.find.m add separator
${w}t.find.m add command -label "list unallocated disc block" -command { find_free_block "disc " }
${w}t.find.m add command -label "list unallocated data link block" -command { find_free_block "data link" }
${w}t.find.m add separator
${w}t.find.m add command -label "list unallocated i/p code block" -command { find_free_block "i/p code" }
${w}t.find.m add command -label "list unallocated o/p code block" -command { find_free_block "o/p code" }

#${w}t.find.m add command -label "list unallocated alarm block" -command { find_free_block "alarm" }
#${w}t.find.m add command -label "list unallocated scratchpad block" -command { find_free_block "scratchpad" }
#${w}t.find.m add command -label "list unallocated system block" -command { find_free_block "system" }
#${w}t.find.m add command -label "list unallocated units block" -command { find_free_block "units" }

proc buildtags { } {
 global title_thenode w thetagfile tagslist m listbox
 
 set tagslist "no contact with $title_thenode"
 set tagslist ""
 catch { set tagslist [exec engnet $title_thenode b99,xb40000,.tg | grep -v "type scratchpad"  | grep -v "tg   spare" | \
   cut -c 8-55 | sort | uniq  | cut -c 1-55 | sed -e "s/^/\"/" -e "s/$/\"/" ] }
 

 $listbox delete 0 end
 #$listbox insert end "** rebuild taglist **"
 #$listbox insert end "** new tg **"
 foreach tg $tagslist {
 	#${w}t.find.m add command -label $tg -command { }
 	$listbox insert end $tg
 	}
}
buildtags

proc find_free_block { type } {
 global w thetagfile tagslist m blockno title_thenode

 set blrange [exec grep "$type" /home/abacus/abacus.sys]

 set spareblox [exec  engnet $title_thenode b[lindex $blrange 0],xb[lindex $blrange 1],long,.tg.nn  | grep "spare"  | cut -c 2-60 | sed -e "s/^/{/" -e "s/$/}/"  ]
 
 
 catch { destroy .spareblocks }
 toplevel .spareblocks
 wm title .spareblocks "Spare $type blocks"

 set sparelistblox [Scrolled_Listbox .spareblocks.sparelistblox  $spareblox  35 12]
 $sparelistblox delete 0 end
 foreach blk $spareblox {
 	$sparelistblox insert end $blk
 	}
# $sparelistblox delete 0 1
 
 button .spareblocks.close -text "close" -command { destroy .spareblocks }
 pack .spareblocks.sparelistblox .spareblocks.close 
 
 bind $sparelistblox <ButtonRelease-1> { 
 	set blockno_temp [string trim [eval "%W get @%x,%y"] ]
 	eval { scan $blockno_temp { %%d} blockno }
	catch { destroy $sparelistblox }
  
	}
}

######################## find all blocks menu stuff #############################
menubutton ${w}t.findall -text "list all blocks" -menu ${w}t.findall.m -underline 0
menu ${w}t.findall.m -tearoff 0


catch { ${w}t.findall.m delete 0 end }

${w}t.findall.m add command -label "list all index block" -command { find_all_block "index" }
${w}t.findall.m add command -label "list all checklist block" -command { find_all_block "checklist" }
${w}t.findall.m add command -label "list all switch block" -command { find_all_block "switch" }
${w}t.findall.m add command -label "list all pattern block" -command { find_all_block "pattern" }
${w}t.findall.m add separator
${w}t.findall.m add command -label "list all control block" -command { find_all_block "control" }
${w}t.findall.m add command -label "list all p.i.d. block" -command { find_all_block "p.i.d." }

${w}t.findall.m add separator
${w}t.findall.m add command -label "list all alarm code block" -command { find_all_block "alarm code" }
${w}t.findall.m add separator
${w}t.findall.m add command -label "list all pibus ai block" -command { find_all_block "pibus ai" }
${w}t.findall.m add command -label "list all K48 point block" -command { find_all_block "K48 point" }
${w}t.findall.m add command -label "list all N45 module block" -command { find_all_block "N45 module" }
${w}t.findall.m add command -label "list all analogue out block" -command { find_all_block "analogue out" }
${w}t.findall.m add command -label "list all indata I/O block" -command { find_all_block "indata I/O" }
${w}t.findall.m add separator
${w}t.findall.m add command -label "list all dig output block" -command { find_all_block "dig output" }
${w}t.findall.m add command -label "list all p.d.o. block" -command { find_all_block "p.d.o." }
${w}t.findall.m add command -label "list all dig input block" -command { find_all_block "dig input" }
${w}t.findall.m add command -label "list all pulse counter block" -command { find_all_block "pulse counter" }
${w}t.findall.m add separator
${w}t.findall.m add command -label "list all scan control block" -command { find_all_block "scan control" }
${w}t.findall.m add command -label "list all sequencer block" -command { find_all_block "sequencer" }
${w}t.findall.m add command -label "list all subroutine block" -command { find_all_block "subroutine" }
${w}t.findall.m add separator
${w}t.findall.m add command -label "list all disc block" -command { find_all_block "disc " }
${w}t.findall.m add command -label "list all data link block" -command { find_all_block "data link" }
${w}t.findall.m add separator
${w}t.findall.m add command -label "list all i/p code block" -command { find_all_block "i/p code" }
${w}t.findall.m add command -label "list all o/p code block" -command { find_all_block "o/p code" }

#${w}t.findall.m add command -label "list all alarm block" -command { find_all_block "alarm" }
#${w}t.findall.m add command -label "list all scratchpad block" -command { find_all_block "scratchpad" }
#${w}t.findall.m add command -label "list all system block" -command { find_all_block "system" }
#${w}t.findall.m add command -label "list all units block" -command { find_all_block "units" }

proc find_all_block { type } {
 global w thetagfile tagslist m blockno title_thenode

 set blrange [exec grep "$type" /home/abacus/abacus.sys]

 set allblox [exec  engnet $title_thenode b[lindex $blrange 0],xb[lindex $blrange 1],long,.tg.nn  | cut -c 2-60 | sed -e "s/^/{/" -e "s/$/}/"  ]
 
 catch { destroy .allblocks }
 toplevel .allblocks
 wm title .allblocks "$type blocks"

 set alllistblox [Scrolled_Listbox .allblocks.alllistblox  $allblox  45 12]
 $alllistblox delete 0 end
 foreach blk $allblox {
 	$alllistblox insert end $blk
 	}
 $alllistblox delete 0 1
 
 button .allblocks.close -text "close" -command { destroy .allblocks }
 pack .allblocks.alllistblox .allblocks.close 
 
 bind $alllistblox <ButtonRelease-1> { 
 	set blockno 0
 	set blockno_temp [string trim [eval "%W get @%x,%y"] ]
 	eval { scan $blockno_temp { %%d} blockno }
	catch { destroy $alllistblox }
  
}

}

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



## proc newtg {} {
##  global w thetagfile tagslist m
## 
##  bell
## }

##################### menu packing list #######################
pack ${w}t.file ${w}t.find ${w}t.findall ${w}t.util ${w}t.type  -side left
pack ${w}t.help  -side right


##################### main frame stuff #######################
frame ${w}frame
pack ${w}frame -side top -fill both -expand yes
set canvasbg #d9d9d9


canvas $c -scrollregion "0 0 $pagewsize $pagehsize" -width 800 -height 530  \
	-relief sunken -borderwidth 2 \
	-xscrollcommand "${w}frame.hscroll set" \
	-yscrollcommand "${w}frame.vscroll set" -background $canvasbg
scrollbar ${w}frame.vscroll -orient vertical   -command "$c yview" -width 10 -jump 1
scrollbar ${w}frame.hscroll -orient horizontal -command "$c xview" -width 10 -jump 1

#-in ${w}frame
grid $c   -row 0 -column 0 -rowspan 1 -columnspan 1 -sticky news
grid ${w}frame.vscroll -row 0 -column 1 -rowspan 1 -columnspan 1 -sticky news
grid ${w}frame.hscroll -row 1 -column 0 -rowspan 1 -columnspan 1 -sticky news

grid rowconfig    ${w}frame 0 -weight 1 -minsize 0
grid columnconfig ${w}frame 0 -weight 1 -minsize 0

#$c config -cursor "@./source.xbm black"

######## Setup the initial scroll position ########
$c yview moveto 1.0
$c xview moveto 1.0
$c yview moveto 0.5
$c xview moveto 0.5
$c yview moveto 0.0
$c xview moveto 0.0
######################## draw page boundry lines #######################

set thedate [exec date "+%Y-%m-%d %H:%M:%S"]
proc draw_boundries {} {
  global title_thenode c thedate pagew pageh  no_of_pages_h no_of_pages_w commands title_program_version
	global  title_Customer_Kund title_Date_Datum title_DrawnBy_RitadAv title_Title_Titel title_thenode thetagfile
	global title_Customer_Kund_2 title_REV  title_REV_2 title_REV_3 title_REV_4 title_REV_5
  
  foreach ttt [$c find withtag boundry] { catch { $c delete $ttt } }

  set_constants
  
  for {set xx1 1} {$xx1 <= $no_of_pages_h} {incr xx1} {
    for {set yy1 1} {$yy1 <= $no_of_pages_w} {incr yy1} {
      set x1 [expr $xx1 * $pagew]
      set y1 [expr $yy1 * $pageh]
      $c create rectangle [expr $x1 - $pagew] [expr $y1 - $pageh] \
        [expr $x1 - 1] [expr $y1 - 1] -outline blue -width 4 -tags boundry

      $c create rectangle [expr $x1 - 4 * $pagew / 4 ] [expr $y1 - $pageh / 8] \
        [expr $x1 - 1] [expr $y1 - 1] -outline blue -tags boundry
      $c create rectangle [expr $x1 - 3 * $pagew / 4 ] [expr $y1 - $pageh / 8] \
        [expr $x1 - 1] [expr $y1 - 1] -outline blue -tags boundry
      $c create rectangle [expr $x1 - 2 * $pagew / 4 ] [expr $y1 - $pageh / 8] \
        [expr $x1 - 1] [expr $y1 - 1] -outline blue -tags boundry
      $c create rectangle [expr $x1 - 1 * $pagew / 4 ] [expr $y1 - $pageh / 8] \
        [expr $x1 - 1] [expr $y1 - 1] -outline blue -tags boundry


	################## Company Name & Address #####################
set bbabname	0	;# MCH Konsutling
set bbabname	1	;# Bristol Babcock AB
      if { $bbabname } {
	$c create text [expr 5 + $x1 - 4 * $pagew / 4 ] [expr 5 + $y1 - $pageh / 8] \
	  -text "Bristol Babcock AB" -fill blue -tags boundry \
	  -anchor nw -font -adobe-times-bold-r-*-*-24-*-*-*-*-*-*-*
	$c create text [expr 10 + $x1 - 4 * $pagew / 4 ] [expr 30 + $y1 - $pageh / 8] \
	 -text "Fallhammargatan 2a\n721 33 Vsters\nSWEDEN\ntel:+46 21 350450\nfax:+46 21 350455\neMail: bristol.babcock@winseasy.se" -fill blue -tags boundry \
	 -anchor nw -font -adobe-times-medium-r-*-*-12-*-*-*-*-*-*-*
      } else {
	$c create text [expr 5 + $x1 - 4 * $pagew / 4 ] [expr 5 + $y1 - $pageh / 8] \
	 -text "MCH Konsulting" -fill blue -tags boundry \
	 -anchor nw -font -adobe-times-bold-r-*-*-24-*-*-*-*-*-*-*
	$c create text [expr 10 + $x1 - 4 * $pagew / 4 ] [expr 30 + $y1 - $pageh / 8] \
	 -text "Fallhammargatan 2a\n721 33 Vsters\nSWEDEN\ntel:+46 21 350450\nfax:+46 21 350455\neMail: MCHKonsulting@hotmail.com" -fill blue -tags boundry \
	 -anchor nw -font -adobe-times-medium-r-*-*-12-*-*-*-*-*-*-*
      }
      
	################## Customer Name etc. ########################
      $c create text [expr 0 + $x1 - 2.5 * $pagew / 4 ] [expr 35 + $y1 - $pageh / 8] \
       -text "$title_Customer_Kund\n$title_Customer_Kund_2" -fill blue -tags boundry \
       -anchor n -font -adobe-times-bold-r-*-*-24-*-*-*-*-*-*-*

	################## Title #####################################
      $c create text [expr 5 + $x1 - 2 * $pagew / 4 ] [expr 5 + $y1 - $pageh / 8] \
       -text "TITLE/TITEL:" -fill blue -tags boundry \
       -anchor nw -font -adobe-times-bold-r-*-*-12-*-*-*-*-*-*-*
      
      $c create text [expr 5 + $x1 - 1.5 * $pagew / 4 ] [expr 35 + $y1 - $pageh / 8] \
       -text "$title_Title_Titel" -fill blue -tags boundry \
       -anchor n -font -adobe-times-bold-r-*-*-18-*-*-*-*-*-*-*
      
      	################## Date Revission etc. ############################
      $c create text [expr 5 + $x1 - $pagew / 4 ] [expr 10 + $y1 - $pageh / 8] \
       -text "PROGRAM REV:\nDATE/DATUM:\nNAME/NAMN:\nREV:" -fill blue -tags boundry \
       -anchor nw -justify right -font -adobe-times-medium-r-*-*-12-*-*-*-*-*-*-*
      

      $c create text [expr 5 + $x1 - 1.4 * $pagew / 8 ] [expr 10 + $y1 - $pageh / 8] \
       -text "$title_program_version\n$title_Date_Datum\n$title_DrawnBy_RitadAv\n$title_REV\n$title_REV_2\n$title_REV_3\n$title_REV_4" \
       -fill blue -tags boundry \
       -anchor nw -font -adobe-times-medium-r-*-*-12-*-*-*-*-*-*-*
      

      
      
#      $c create text [expr 5 + $x1 - $pagew / 4 ] [expr 120 + $y1 - $pageh / 8] \
#       -text "NODE: $title_thenode  FILE: [exec uname -n]::$thetagfile" -fill blue -tags boundry \
#       -anchor nw -font -adobe-times-medium-i-*-*-12-*-*-*-*-*-*-*
      
      $c create text [expr 5 + $x1 - 2 * $pagew / 4 ] [expr 105 + $y1 - $pageh / 8] \
       -text "NODE: $title_thenode\nFILE: [exec uname -n]::$thetagfile" -fill blue -tags boundry \
       -anchor nw -font -adobe-times-medium-i-*-*-12-*-*-*-*-*-*-*
      
      }
    }
    foreach field {title_Customer_Kund title_Date_Datum title_DrawnBy_RitadAv title_Title_Titel 
       title_Customer_Kund_2 title_REV title_REV_2 title_REV_3 title_REV_4 title_REV_5 title_thenode } {
 	    set field2 ""
 	    catch { eval "set field2 $$field" }
 	    set commands($field) "set $field \"$field2\""
 	    }
    wm title . "ABACUS Engineering Interface at $title_thenode ($thetagfile)"
}
draw_boundries

#################### main frame binding stuff ##################
 
#bind $c <Any-Enter> fix_names



#$c bind line <Any-Enter> "$c itemconfig current -fill red"
#$c bind line <Any-Leave> "$c itemconfig current -fill SkyBlue2"

bind $c <3> { 
   #puts stdout "<3>"
   switch -exact -- $editmode {
      {block}       { set editmode {line}	 }
      {line}        { set editmode {line-arrow}  }
      {line-arrow}  { set editmode {line-circle} }
      {line-circle} { set editmode {line-dashed} }
      {line-dashed} { set editmode {text-file}   }
      {text-file}   { set editmode {text}	 }
      {text}        { set editmode {long-print}  }
      {long-print}  { set editmode {short-print} }
      {short-print} { set editmode {xref}	 }
      {xref}	    { set editmode {block}	 }
   }
}

bind $c <Shift-3> { 
   #puts stdout "<Shift-3>"
   switch -exact -- $editmode {
      {line}	    { set editmode {block}	 }
      {line-arrow}  { set editmode {line}	 }
      {line-circle} { set editmode {line-arrow}  }
      {line-dashed} { set editmode {line-circle} }
      {text-file}   { set editmode {line-dashed} }
      {text}	    { set editmode {text-file}   }
      {long-print}  { set editmode {text}	 }
      {short-print} { set editmode {long-print}  }
      {xref}	    { set editmode {short-print} }
      {block}	    { set editmode {xref}	 }
   }
}

set line_x 0 ; set line_y 0 ;

bind $c <1> { 
 
 set xx [$c canvasx %x $grid_size ]
 set yy [$c canvasy %y $grid_size ]
 set xxx1 [$c canvasx %x]
 set yyy1 [$c canvasy %y]
#puts stdout "xxx1 $xxx1, xxx $xxx, xx $xx\nxxx1 $yyy1, yyy $yyy, yy $yy"


 set blkline [exec engnet $title_thenode b$blockno,p | \
  tr ";" "\n" | sed "s/^B.* type /TY/" | \
  sed "s/^B/bl/" | sed "s/\\(^..\\)/set \\1 {/" | sed "s/\\(.$\\)/\\1}/" | \
  sed "s/\(.*\)//" | sed "s/   / /g" | sed "s/  / /g" ]

 set blkline2 [exec engnet $title_thenode b$blockno,p | \
  tr ";" "\n" | sed "s/^B.* type /TY/" | \
  sed "s/^B/bl/" | sed "s/\\(^..\\)/set \\1b {/" | sed "s/\\(.$\\)/\\1}/" | \
  sed "s/   / /g" | sed "s/  / /g" ]
 
# puts stdout $blkline
 
 eval $blkline
 eval $blkline2
 if { $editmode == "block" } { draw_block
 } elseif { $editmode == "xref" }  { draw_xref 
 } elseif { $editmode == "line" || $editmode == "line-arrow"\
   || $editmode == "line-circle" || $editmode == "line-dashed" }  {
          set line_x $xxx1 ; set line_y $yyy1 ; ;#draw_line 
 } elseif { $editmode == "text" }  { draw_text 
 } elseif { $editmode == "text-file" }  { draw_text-file 
 } elseif { $editmode == "short-print" }  { print_block tagarray($\{blockno\}_$editmode) short $xx $yy 
 } elseif { $editmode == "long-print" }  { print_block tagarray($\{blockno\}_$editmode) long $xx $yy 
 }
 
 fix_names

}
bind $c <B1-Motion> { 
 set xx [$c canvasx %x $grid_size ]
 set yy [$c canvasy %y $grid_size ]
 set xxx1 [$c canvasx %x]
 set yyy1 [$c canvasy %y]

 set xxxfinal $xxx1
 set yyyfinal $yyy1

 if { $editmode == "line" } { 
   #puts stdout "line from $line_x $line_y to $xxx1 $yyy1"
   $c delete lines -tag flinetemp
   $c create line $line_x $line_y $xxx1 $yyy1 -tag flinetemp
   }
 if { $editmode == "line-arrow" } { 
   #puts stdout "line-arrow from $line_x $line_y to $xxx1 $yyy1"
   $c delete lines -tag flinetemp
   $c create line $line_x $line_y $xxx1 $yyy1 -arrow last -tag flinetemp
   }
 if { $editmode == "line-circle" } { 
   #puts stdout "line-circle from $line_x $line_y to $xxx1 $yyy1"
   $c delete lines -tag flinetemp
   $c create line $line_x $line_y $xxx1 $yyy1 -arrow last -arrowshape {6 3 3} -tag flinetemp
   }
 if { $editmode == "line-dashed" } { 
   #puts stdout "line-dashed from $line_x $line_y to $xxx1 $yyy1"
   $c delete lines -tag flinetemp
   if { [expr abs( $line_x - $xxx1 ) - abs (  $yyy1 - $line_y ) ] > 0 } then { 
       $c create line $line_x $line_y $xxx1 $yyy1 -stipple @engdraw_dashed-h.xbm -tag flinetemp
     } else {
       $c create line $line_x $line_y $xxx1 $yyy1 -stipple @engdraw_dashed-v.xbm -tag flinetemp
     }
#   $c create line $line_x $line_y $xxx1 $yyy1 -stipple @engdraw_dashed-h.xbm -tag flinetemp
   }
}

bind $c <Shift-B1-Motion> { 
 set xx [$c canvasx %x $grid_size ]
 set yy [$c canvasy %y $grid_size ]
 set xxx1 [$c canvasx %x]
 set yyy1 [$c canvasy %y]
 
 if { ( $xxx1 - $line_x ) > 0 } then { set modxdiff [expr ( $xxx1 - $line_x )] } else { set modxdiff [expr ( -$xxx1 + $line_x )] }
 if { ( $yyy1 - $line_y ) > 0 } then { set modydiff [expr ( $yyy1 - $line_y )] } else { set modydiff [expr ( -$yyy1 + $line_y )] }
 
 if { $modxdiff < $modydiff } then { set xxx1 $line_x } else { set yyy1 $line_y }
 
 set xxxfinal $xxx1
 set yyyfinal $yyy1

 if { $editmode == "line" } { 
   #puts stdout "line from $line_x $line_y to $xxx1 $yyy1"
   $c delete lines -tag flinetemp
   $c create line $line_x $line_y $xxx1 $yyy1 -tag flinetemp
   }
 if { $editmode == "line-arrow" } { 
   #puts stdout "line-arrow from $line_x $line_y to $xxx1 $yyy1"
   $c delete lines -tag flinetemp
   $c create line $line_x $line_y $xxx1 $yyy1 -arrow last -tag flinetemp
   }
 if { $editmode == "line-circle" } { 
   #puts stdout "line-circle from $line_x $line_y to $xxx1 $yyy1"
   $c delete lines -tag flinetemp
   $c create line $line_x $line_y $xxx1 $yyy1 -arrow last -arrowshape {6 3 3} -tag flinetemp
   }
 if { $editmode == "line-dashed" } { 
   #puts stdout "line-dashed from $line_x $line_y to $xxx1 $yyy1"
   $c delete lines -tag flinetemp
   if { [expr abs( $line_x - $xxx1 ) - abs (  $yyy1 - $line_y ) ] > 0 } then { 
       $c create line $line_x $line_y $xxx1 $yyy1 -stipple @engdraw_dashed-h.xbm -tag flinetemp
     } else {
       $c create line $line_x $line_y $xxx1 $yyy1 -stipple @engdraw_dashed-v.xbm -tag flinetemp
     }
#   $c create line $line_x $line_y $xxx1 $yyy1 -stipple @engdraw_dashed-h.xbm -tag flinetemp
   }
}

bind $c <Motion> { 
 set xx [$c canvasx %x $grid_size ]
 set yy [$c canvasy %y $grid_size ]
 set xxx1 [$c canvasx %x]
 set yyy1 [$c canvasy %y]

# if { $editmode == "line" } { 
#   puts stdout "line from $line_x $line_y to  [expr $xxx1 - 3] [expr $yyy1 - 3]"
#   $c delete lines -tag flinetemp
#   $c create line $line_x $line_y [expr $xxx1 - 3] [expr $yyy1 - 3] -tag flinetemp
#   }
}

bind $c <ButtonRelease-1> { 
 set xx [$c canvasx %x $grid_size ]
 set yy [$c canvasy %y $grid_size ]
 set xxx1 [$c canvasx %x]
 set yyy1 [$c canvasy %y]

 catch { set xxx1 $xxxfinal }
 catch { set yyy1 $yyyfinal }

 if { $editmode == "line" } { 
   #puts stdout "line from $line_x $line_y to  $xxx1 $yyy1"
   $c delete lines -tag flinetemp
   
   $c create line $line_x $line_y  $xxx1 $yyy1 -tag fline
   }
 if { $editmode == "line-arrow" } { 
   #puts stdout "line from $line_x $line_y to  $xxx1 $yyy1"
   $c delete lines -tag flinetemp
   $c create line $line_x $line_y  $xxx1 $yyy1 -arrow last -tag flinearrow
   }
 if { $editmode == "line-circle" } { 
   #puts stdout "line from $line_x $line_y to  $xxx1 $yyy1"
   $c delete lines -tag flinetemp
   $c create line $line_x $line_y  $xxx1 $yyy1 -arrow last -arrowshape {6 3 3} -tag flinecircle
   }
 if { $editmode == "line-dashed" } { 
   #puts stdout "line-dashed from $line_x $line_y to $xxx1 $yyy1"
   $c delete lines -tag flinetemp
   if { [expr abs( $line_x - $xxx1 ) - abs (  $yyy1 - $line_y ) ] > 0 } then { 
       $c create line $line_x $line_y $xxx1 $yyy1 -stipple @engdraw_dashed-h.xbm -tag flinedashed
     } else {
       $c create line $line_x $line_y $xxx1 $yyy1 -stipple @engdraw_dashed-v.xbm -tag flinedashed
     }
   }
}

bind $c <2> "itemStartDrag $c %x %y"
bind $c <B2-Motion> "itemDrag $c %x %y"

$c bind fline <Any-Enter> "itemEnter $c"
$c bind fline <Any-Leave> "itemLeave $c"
$c bind flinearrow <Any-Enter> "itemEnter $c"
$c bind flinearrow <Any-Leave> "itemLeave $c"
$c bind flinecircle <Any-Enter> "itemEnter $c"
$c bind flinecircle <Any-Leave> "itemLeave $c"
$c bind flinedashed <Any-Enter> "itemEnter $c"
$c bind flinedashed <Any-Leave> "itemLeave $c"

bind . <Delete> {del_line}
bind . <BackSpace> {del_line}
proc del_line {} {
  global c 
  #puts stdout {%%K=%K %%A=%A}
    #puts stdout "del_line  $c gettags current = [$c gettags current]"
    set ftag1 [lsearch [$c gettags current] fline*]
    #puts stdout "ftag1 $ftag1"
    if { $ftag1 >= 0 } {
      $c delete line current
    }
  }

#$c bind flinearrow <Any-Enter> "itemEnter $c"
#$c bind flinecircle <Any-Enter> "itemEnter $c"

# Utility procedures for highlighting the item under the pointer:

proc itemEnter {c} {
    global restoreCmd

    if {[winfo depth $c] == 1} {
	set restoreCmd {}
	return
    }
    set type [$c type current]
    if {$type == "window"} {
	set restoreCmd {}
	return
    }
    if {$type == "bitmap"} {
	set bg [lindex [$c itemconf current -background] 4]
	set restoreCmd [list $c itemconfig current -background $bg]
	$c itemconfig current -background SteelBlue2
	return
    }
    set fill [lindex [$c itemconfig current -fill] 4]
    if {(($type == "rectangle") || ($type == "oval") || ($type == "arc"))
	    && ($fill == "")} {
	set outline [lindex [$c itemconfig current -outline] 4]
	set restoreCmd "$c itemconfig current -outline $outline"
	$c itemconfig current -outline SteelBlue2
    } else {
	set restoreCmd "$c itemconfig current -fill $fill"
	$c itemconfig current -fill SteelBlue2
    }
}

proc itemLeave {c} {
    global restoreCmd

    eval $restoreCmd
}

# Utility procedures to support dragging of items.

proc itemStartDrag {c x y} {
    global lastX lastY
    set lastX [$c canvasx $x]
    set lastY [$c canvasy $y]
}

proc itemDrag {c x y} {
    global lastX lastY
    global editmode
    set x [$c canvasx $x]
    set y [$c canvasy $y]
    #puts stdout "itemDrag $c gettags current = [$c gettags current]  [expr $x-$lastX] [expr $y-$lastY]"
    #if {[$c gettags current] == "fline" } {
    	$c move current [expr $x-$lastX] [expr $y-$lastY] ;#}
    set lastX $x
    set lastY $y
}

############################## push & pop ( undo ) stuff #################
proc push_commands {} {
  global commands commands_stack 
  
  foreach index [array names commands] {
    set commands_stack($index) $commands($index)
    }
}

proc pop_commands {} {
  global c commands commands_stack 
  global title_thenode c editmode xx yy TY bl nm tg sn ra am vn ss \
  	blkline blkline2 blockno tagarray editstyle thetextfile commands

  foreach index [array names commands] {
    set commands_temp($index) $commands($index)
    unset commands($index)
    }
  foreach index [array names commands_stack] {
    set commands($index) $commands_stack($index)
    }
  foreach index [array names commands_temp] {
    set commands_stack($index) $commands_temp($index)
    #unset commands_temp($index)
    }

  foreach ttt [$c find all] { catch { $c delete $ttt } }
  foreach comm [ array names commands] { eval $commands($comm)  }
  fix_names
  
}

########################## drawing stuff ############################

set line_id 0
proc draw_line {} {
  global title_thenode c editmode xx yy TY bl nm tg sn ra am vn ss \
  	blkline blkline2 blockno tagarray editstyle line_id commands

  push_commands	
#	bgerror "This facility is not yet available"
  
}

set textid 0
proc draw_text {} {
  global title_thenode c editmode xx yy TY bl nm tg sn ra am vn ss \
  	blkline blkline2 blockno tagarray editstyle textid commands

  push_commands	
  set textid $blockno

  set commands(${textid}_text) \
  	"set textid \"$textid\"; set xx $xx ; set yy $yy ;\
  	$c delete text -tag tagarray(${textid}_text);\
  	$c create text $xx $yy \
  	-text \"textid_$textid\" -tag tagarray(${textid}_text) -anchor nw  \
  	-font -adobe-courier-medium-r-*-*-10-*-*-*-*-*-*-* ;"

  eval $commands(${textid}_text)

}


proc draw_text-file {} {
  global title_thenode c editmode xx yy TY bl nm tg sn ra am vn ss \
  	blkline blkline2 blockno tagarray editstyle thetextfile commands

  push_commands
  set commands(0_$thetextfile) \
  	"set thetextfile \"$thetextfile\"; set xx $xx ; set yy $yy ;\
  	$c delete text -tag tagarray(0_$thetextfile);\
  	set thetext \[exec cat \"$thetextfile\" ] ;\
  	$c create text $xx $yy \
  	-text \"\$thetext\" -tag tagarray(0_$thetextfile) -anchor nw  \
  	-font -adobe-courier-medium-r-*-*-10-*-*-*-*-*-*-* ;"

  eval $commands(0_$thetextfile)

}

proc print_block { thetag shortlong x0 y0 } {
  global title_thenode c editmode xx yy TY bl nm tg sn ra am vn ss \
  	blkline blkline2 blockno tagarray editstyle commands

  set blockprint [exec engnet $title_thenode b$blockno,$shortlong,p | tr ";" "\n" ] 

  set blockno [ string trim $blockno ]
  
  push_commands
  set commands(${blockno}_$editmode) \
  	"set blockno \[format \"%d\" $blockno \]; set xx $xx ; set yy $yy ;
  	$c delete text -tag tagarray($\{blockno\}_$editmode);
  	set blockprint \[exec engnet $title_thenode b$blockno,$shortlong,p | tr \";\" \"\\\\n\"  \] ;
  	$c create text $xx $yy \
  	-text \"\$blockprint\" -tag tagarray($\{blockno\}_$editmode) -anchor nw  \
  	-font -adobe-courier-medium-r-*-*-10-*-*-*-*-*-*-* ; $c bind tagarray($\{blockno\}_$editmode)"

  eval $commands(${blockno}_$editmode)
}

proc draw_xref {} {
  global title_thenode c editmode xx yy TY bl nm tg sn ra am vn ss \
  	blkline blkline2 blockno tagarray editstyle commands

  set blockprint [exec engnet $title_thenode b$blockno,xref  ] 
  $c delete text -tag tagarray($\{blockno\}_$editmode)
 
  set blockno [ string trim $blockno ]
  
  push_commands
  set commands(${blockno}_$editmode) \
  	"set blockno \[format \"%d\" $blockno\]; set xx $xx ; set yy $yy ; $c delete text -tag tagarray($\{blockno\}_$editmode);\
  	set blockprint \[exec engnet $title_thenode b$blockno,xref  \] ;\
  	$c create text $xx $yy \
  	-text \"\$blockprint\" -tag tagarray($\{blockno\}_$editmode) -anchor nw  \
  	-font -adobe-courier-medium-r-*-*-10-*-*-*-*-*-*-* ;"
  	
  eval $commands(${blockno}_$editmode)
  	
	
}

proc draw_block {} {
  global title_thenode c editmode w xx yy TY bl nm tg sn ra am vn ss \
  	blkline blkline2 blockno tagarray editstyle commands

  #set extras1 $editstyle
  
  if { $blockno == 0 } { return }
  
  set blockno [ string trim $blockno ]
  
  set extras1 long
#puts stdout "TY = $TY"
  push_commands
  if { $TY == "switch"  } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; sw.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "control" } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; cb.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "alarm code"   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; acb.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "index"   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; ix.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "motor"   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; mb.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "checklist"   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; cl.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "pattern"   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; pt.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "p.i.d."   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; pid.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "pibus ai"   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; ai.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "analogue out"   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; ao.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "dig input"   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; di.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "dig output"   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; do.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == ""   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; do.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "p.d.o."   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; pdo.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "scratchpad"   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; spad.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "indata I/O"   } then {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; indata.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "pulse counter"	} then {
       set commands(${blockno}_$editmode) \
	"set blockno $blockno; set xx $xx ; set yy $yy ; pcnt.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"

    } elseif { $TY == "K48 point"	} then {
       set commands(${blockno}_$editmode) \
	"set blockno $blockno; set xx $xx ; set yy $yy ; k48.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"
    } elseif { $TY == "N45 module"	} then {
       set commands(${blockno}_$editmode) \
	"set blockno $blockno; set xx $xx ; set yy $yy ; n45.fig tagarray($\{blockno\}_$editmode) $xx $yy ;"

    } else {
       set commands(${blockno}_$editmode) \
        "set blockno $blockno; set xx $xx ; set yy $yy ; print_block tagarray($\{blockno\}_$editmode) long $xx $yy ;"
         
       
  }
  
  eval $commands(${blockno}_$editmode)

  }

#################### Load up the procs for block drawing #############
foreach fil [ glob /home/abacus/*_fig.tk ] {
	catch { source $fil }
	#puts stdout "sourcing $fil"
}

update_blocks
do_msg

 if { $thetagfile != ""} { source $thetagfile }
 foreach comm [ array names commands] { eval $commands($comm) }
 fix_names

dsk_progress "Started."
after 3000 dsk_welcome hide
