#!/usr/local/bin/wish4.2 -f
#!/usr/local/bin/wish8.0 -f
#
# DrawP - Drawing Pattern Application (Tcl/Tk Script)
#
#       Version     : 2.1 
#       Create Date : 18 Apr. 1997
#       System      : Unix, Windows3.1/95, Machintosh
#
#       Copyright (C) 1996,1997 UEDA Hiroyuki. All Rights Reserved.
#                           
#       Author: UEDA Hiroyuki  (hueda@kamome.or.jp)
#
#       This file is free; you can redistribute it and/or
#       modify it under the term of the GNU General Public License
#       (GPL) as published by the Free Software Foundation;
#       either version 1.0, or (at your option) any later version.
#
#       This file is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
#       GNU General Public License for more details.


# Version Check
if {$tk_version < 4.2} {
        puts "\n\tDrawP ver.2.1 needs Tcl7.6p2/Tk4.2p2 or later version."
        puts "\t\t... Please get Tcl7.6p2/Tk4.2p2 or later version!\n"
        exit
}

####################################
# You can edit following variables :
####################################
set fontSize   "16 17 18 19 20 24 25 26 30 33 34"
set fontSlant  "roman italic" ; set fontWeight "Medium Bold"
set outTgif   "DrawP.obj" ; set outPS "DrawP.ps"
set colors "black red blue green yellow pink purple"
set widths "1 2 3 4 5"
set axisLabel(1) "\[dB\]" ; set axisLabel(2) "\[deg.\]"
set psSize   0.6 

###############################################
# You had not better edit following variables : 
###############################################
if {$tk_version < 8.0 } {
    set fontFamily "Charter Clean Courier Helvetica Times Utopia"
} else {
    set fontFamily [font families]
}
set sizeCanvas  500 ; set sizeCanvasX 700 ; set sizeCanvasY 500
set centerX "" ; set centerY ""
set stepScale(1) "" ; set x0Canvas   80 ; set y0Canvas 80
set xmCanvas   [expr $sizeCanvas - $x0Canvas]
set ymCanvas   [expr $sizeCanvas - $y0Canvas]
set curDir     [pwd]
set font(1) -*-helvetica-bold-r-Normal--*-140-*-*-*-*-*-*
set font(2) -*-helvetica-bold-r-Normal--*-160-*-*-*-*-*-*
set font(3) -*-helvetica-bold-r-Normal--*-180-*-*-*-*-*-*
set font(4) -*-helvetica-bold-r-Normal--*-240-*-*-*-*-*-*
set isKey     "" ; set isFrame   "" ; set nowX "" ; set nowY ""
set keyWidth  "" ; set keyHeight "" ; set keyColors "Color"
set fontAngle $font(4); set fontAxis  $font(3); set fontNote  $font(3)
set deg2rad  [expr 3.1415926/180.0] ; set version 2.1


# Check default file(~/.drawp)
set isDrawP invalid
if {[file exists ~/.drawp] == 1 && [file size ~/.drawp] != 0} {
    set in_fd [open ~/.drawp r] ; set line  [gets $in_fd] ; close $in_fd

    set frameType [lindex [split $line ,] 0] 
    set orderType [lindex [split $line ,] 1]
    set graphForm [lindex [split $line ,] 2]
    set stepAxis1 [lindex [split $line ,] 3]
    set stepAxis2 [lindex [split $line ,] 4]
    set stepAngle [lindex [split $line ,] 5]
    set startValue [lindex [split $line ,] 6]
    set endValue   [lindex [split $line ,] 7]
    set startAngle [lindex [split $line ,] 8]
    set endAngle   [lindex [split $line ,] 9]
    set ext        [lindex [split $line ,] 10]
    set CSV        [lindex [split $line ,] 11]
    set angleNum   [lindex [split $line ,] 12]
    set valueNum   [lindex [split $line ,] 13]

    if {[catch {expr $frameType*$orderType*$stepAxis1*$stepAxis2*$stepAngle*$startValue*$endValue*$startAngle*$endAngle*$angleNum*$valueNum}] != 0} {} elseif {$graphForm != "full" && $graphForm != "semi"} {} elseif {$CSV != "YES" && $CSV != "NO"} {} else {set isDrawP valid}
}

# Case of not having ~/.drawp or invalid ~/.drawp file
if {$isDrawP == "invalid"} {
    set frameType    1 ; set orderType   1 ; set graphForm full
    set stepAxis1   10 ; set stepAxis2   5 ; set stepAngle   30
    set startValue   0 ; set endValue  -40 ; set startAngle   0
    set endAngle   360 ; set ext       cvt ; set CSV         NO
    set angleNum     1 ; set valueNum    2
}

foreach i {1 2 3 4} { 
    set file($i)      ""; set value($i,0)   ""; set angle($i,0)   ""
    set dataOK($i)    ""; set isDraw($i)    0 ; set isAngleLine   "YES"
    set isLine($i)    ""
    set angleRow($i)  $angleNum ; set valueRow($i)  $valueNum
    set lineColor($i) [lindex $colors [expr $i - 1]]
    set keyColor($i)  $lineColor($i) ; set Key($i) "Data No.$i"
    set lineWidth($i) 3 ; set isSubCircle ""
} 

# File Extensions Lists for File Treating Procedure
set readtypes {
    {"Data files"        {.dat .csv .cvt} }
    {"All files"           * }
}

set tgiftypes {
    {"Tgif Object files" {.obj} }
    {"All files"           * }
}

set pstypes {
    {"PS,EPS files"      {.ps .eps} }
    {"All files"           * }
}


#
# Widgets Definition
#
wm title . "DrawP ver. 2.1 Release for X11"
if {$graphForm == "full"} {
    wm aspect . 508 543 508 543
} else {
    wm aspect . 708 543 708 543
}

# Frames
frame .menu -bd 3 -relief raised

# Canvas
if {$graphForm == "full"} {
    canvas .canvas -width $sizeCanvas -height $sizeCanvas -relief groove \
	    -bg white -bd 2 -closeenough 0.1
} else {
    canvas .canvas -width $sizeCanvasX -height $sizeCanvasY -relief groove \
	    -bg white -bd 2 -closeenough 0.1
}

# MenuButtons
menubutton .file   -text "File"   -menu .file.m   -font $font(3) -bd 3
menubutton .edit   -text "Edit"   -menu .edit.m   -font $font(3) -bd 3
menubutton .option -text "Option" -menu .option.m -font $font(3) -bd 3

# Menus #

# File Menu
menu .file.m -tearoff 0
.file.m add command -label "Read" -accelerator "Ctrl+r" \
	-underline 0 -command {readDataFile . READ} -font $font(2)
.file.m add cascade -label "Save as " -menu .file.m.s -font $font(2)
.file.m add command -label "Print " -accelerator "Ctrl+p" \
	-underline 0 -command {printCanvas .} -font $font(2)
.file.m add separator
.file.m add command -label "Quit  " -accelerator "Ctrl+q" \
	-underline 0 -command {really_quit} -font $font(2)

menu .file.m.s -tearoff 0
.file.m.s add command -label "PS File" -accelerator "Ctrl+s" \
	-underline 1 -command {outputFile . PS} -font $font(2)
.file.m.s add command -label "Tgif Object File" -accelerator "Ctrl+t" \
	-underline 0 -command {outputFile . TGIF} -font $font(2)

# Edit Menu
menu .edit.m -tearoff 0
.edit.m add command -label "Data  " -accelerator "Ctrl+d" \
	-underline 0 -command {config_data .} -font $font(2)
.edit.m add command -label "Graph " 	   -accelerator "Ctrl+g" \
	-underline 0 -command {selectGraphForm .} -font $font(2)

# Option Menu
menu .option.m -tearoff 0
.option.m add command -label "Fonts       " \
	-command {change_fonts .} -font $font(2)
.option.m add command -label "Notes       " \
	-command {change_Notes .} -font $font(2)
.option.m add command -label "Convert     " \
	-command {readDataFile . CONV } -font $font(2)
.option.m add command -label "Customize   " \
	-command {setup .} -font $font(2) 
.option.m add separator
.option.m add command -label "Information " -command {about_drawp .} \
	-font $font(2)

# Packing Menu
pack .file .edit .option -side left -in .menu -padx 4

# Packing All Widget
pack .menu -side top -fill x
pack .canvas -side top -pady 1 -fill both -expand yes

tk_menuBar .menu .file .edit .option

#
# Binding ShortCut Keys
#
bind all <Control-q> {exit}
bind . <Control-r> {readDataFile . READ}
bind . <Control-c> {readDataFile . CONV}
bind . <Control-s> {outputFile . PS}
bind . <Control-t> {outputFile . TGIF}
bind . <Control-p> {printCanvas .}     ; bind . <Control-d> {config_data .}
bind . <Control-g> {selectGraphForm .} ; bind . <Control-c> {}

bind .canvas <Double-3> {
    if {$isKey == ""} {
	drawNotes %x %y ; set old_x %x; set old_y %y
    } else {
	.canvas delete keys ; set isKey ""
    }
}

.canvas bind keys <ButtonPress-1> {
    if {$isKey != ""} {
	.canvas delete keys
	set isFrame [.canvas create rectangle [expr %x-10] [expr %y-10] \
		[expr %x+$keyWidth-10] [expr %y+$keyHeight-10] -outline blue \
		-tags frame]
	set isKey "" ; set old_x %x ; set old_y %y
    }
}
bind .canvas <ButtonRelease-1> {
    if {$isFrame != ""} {
	.canvas delete frame ; drawNotes %x [expr %y-20] 
	set isFrame "" ; set old_x "" ; set old_y ""
    }
}
bind .canvas <B1-Motion> {
    if {$isFrame != ""} {
	.canvas move frame [expr %x-$old_x] [expr %y-$old_y]
	set old_x %x ; set old_y %y
    }
}

bind .canvas <Configure> {
    if {$graphForm == "full"} {
	set sizeCanvas [expr %h-8]
    } else {
	set sizeCanvasX [expr %w-8] ; set sizeCanvasY [expr %h-8]
    }

    drawAxis
    for {set i 1} {$i < 5} {incr i} {
	global dataOK isDraw
	if {$dataOK($i) == "OK" && $isDraw($i) == 1} { drawData $i } 
	if {$isKey != ""} { set isKey "" ; drawNotes $nowX $nowY }
    }
}


# drawAxis -- Drawing Axis
#
# Arguments    : None
# Return Value : None
#
proc drawAxis {} {
    global font fontAxis fontAngle
    global sizeCanvas sizeCanvasX sizeCanvasY  axisLabel
    global x0Canvas y0Canvas xmCanvas ymCanvas centerX centerY 
    global stepAxis1 stepAxis2 stepScale stepAngle isAngleLine isSubCircle
    global graphForm startValue endValue startAngle endAngle tmpMaxLabel
    global deg2rad

    set div1    [expr double($startValue-$endValue)/$stepAxis1]
    set div2    [expr double($stepAxis1)/$stepAxis2]

    .canvas delete axis axisT angleAxis angleAxisT
    for {set i 0} {$i < 20} {incr i} {.canvas delete Axis($i)}

    if {$graphForm == "full"} {
	set xmCanvas     [expr $sizeCanvas - $x0Canvas]
	set ymCanvas     [expr $sizeCanvas - $y0Canvas]
	set centerX      [expr double($sizeCanvas)/2.0]
	set centerY      $centerX
	set stepScale(1) [expr double($ymCanvas-$y0Canvas)/(2*$div1)]
	set stepScale(2) [expr double($stepScale(1))/$div2]
	set radius       [expr $centerX - $x0Canvas]

	if {[expr int(abs($endAngle-$startAngle))] != 360} {
	    set startAngle 0 ; set endAngle   360
	}

	.canvas create oval $x0Canvas $y0Canvas $xmCanvas $ymCanvas \
		-outline black -tags axis -width 2.0

	if {$isSubCircle == "YES"} {
	    for {set i 1} {$i <= $div1*$div2} {incr i} {
		set startX [expr $x0Canvas + $stepScale(2)*$i]
		set startY [expr $y0Canvas + $stepScale(2)*$i]
		set endX   [expr $xmCanvas - $stepScale(2)*$i]
		set endY   [expr $ymCanvas - $stepScale(2)*$i]
		.canvas create oval $startX $startY $endX $endY \
			-outline gray70 -tag axis
	    }
	}
	for {set i 1} {$i <= $div1} {incr i} {
	    set startX [expr $x0Canvas + $stepScale(1)*$i]
	    set startY [expr $y0Canvas + $stepScale(1)*$i]
	    set endX   [expr $xmCanvas - $stepScale(1)*$i]
	    set endY   [expr $ymCanvas - $stepScale(1)*$i]
	    .canvas create oval $startX $startY $endX $endY \
		    -outline black -tag axis 
	}

	# Sub Line indicating Angle
	if {$isAngleLine == "YES"} {
	    set angleStep [expr $stepAngle*$deg2rad]
	    set tmp [expr int(180.0/$stepAngle)]
	    for {set i 1} {$i < $tmp} {incr i} {
		set sublineX  [expr $centerX + $radius*cos($i*$angleStep)]
		set sublineY  [expr $centerY + $radius*sin($i*$angleStep)]
		set sublineX2 [expr $centerX - $radius*cos($i*$angleStep)]
		set sublineY2 [expr $centerY - $radius*sin($i*$angleStep)]
		.canvas create line $sublineX $sublineY \
			$sublineX2 $sublineY2 -fill dimgray -tags axis
	    }
	}
	for {set i 0} {$i <= $div1} {incr i} {
	    .canvas create text \
		    $centerX [expr $y0Canvas + $i*$stepScale(1)+7] \
		    -text "[expr int($startValue-$stepAxis1*$i)]"  \
		    -font $fontAxis -tags Axis($i) -anchor e
	}
	.canvas create text \
		[expr $centerX+$stepScale(1)/2.0] \
		[expr $y0Canvas+$stepScale(1)/4.0] \
		-text "$axisLabel(1)" -font $fontAxis -tags axisT

	.canvas create line $x0Canvas $centerY $xmCanvas $centerY -tags axis
	.canvas create line $centerX $y0Canvas $centerX $ymCanvas -tags axis

	set tmpDif [expr double($endAngle-$startAngle)/4]
	.canvas create text $centerX $y0Canvas -font $fontAngle \
		-text "[expr int($startAngle)]" -tags angleAxis -anchor s
	.canvas create text [expr $xmCanvas+5] $centerY -font $fontAngle \
		-text "[expr int($startAngle+$tmpDif)]" -tags angleAxis \
		-anchor w
	.canvas create text $centerX $ymCanvas -font $fontAngle \
		-text "[expr int($startAngle+$tmpDif*2)]" -tags angleAxis \
		-anchor n
	.canvas create text [expr $x0Canvas-5] $centerY -font $fontAngle \
		-text "[expr int($startAngle+$tmpDif*3)]" -tags angleAxis \
		-anchor e
	.canvas create text [expr $centerX+$stepScale(1)*2.0/3.0] \
		[expr $ymCanvas] -text "$axisLabel(2)" -font $fontAngle \
		-tags angleAxisT -anchor nw
    } else {
	set xmCanvas     [expr $sizeCanvasX - $x0Canvas]
	set ymCanvas     [expr $sizeCanvasY - $y0Canvas]
	set centerX      [expr double($sizeCanvasX)/2.0]
	set centerY      [expr double($sizeCanvasY)*4.0/5.0]
	set offsetY      [expr double($xmCanvas-$x0Canvas)/2.0]
	set topY         [expr $centerY - $offsetY]
	set bottomY      [expr $centerY + $offsetY]
	set stepScale(1) [expr double($centerY-$topY)/$div1]
	set stepScale(2) [expr double($stepScale(1))/$div2]
	set radius       [expr $centerX - $x0Canvas]

	if {$isAngleLine == "YES"} {
	    set angleStep [expr $stepAngle*$deg2rad]
	    set tmp       [expr int(180.0/$stepAngle)]
	    for {set i 1} {$i < $tmp} {incr i} {
		set sublineX  [expr $centerX - $radius*cos($i*$angleStep)]
		set sublineY  [expr $centerY - $radius*sin($i*$angleStep)]
		.canvas create line $sublineX $sublineY $centerX $centerY \
			-fill dimgray -tags axis 
	    }
	}

	.canvas create line $centerX $topY $centerX $centerY \
		-fill black -tags axis

	if {$isSubCircle == "YES"} {
	    for {set i 1} {$i < $div1*$div2} {incr i} {
		set startX [expr $x0Canvas + $stepScale(2)*$i]
		set startY [expr $topY + $stepScale(2)*$i]
		set endX   [expr $xmCanvas - $stepScale(2)*$i]
		set endY   [expr $bottomY - $stepScale(2)*$i]
		.canvas create arc $startX $startY $endX $endY \
			-outline gray70 -tags axis -extent 180
	    }
	}

	for {set i 1} {$i < $div1} {incr i} {
	    set startX [expr $x0Canvas + $stepScale(1)*$i]
	    set startY [expr $topY + $stepScale(1)*$i]
	    set endX   [expr $xmCanvas - $stepScale(1)*$i]
	    set endY   [expr $bottomY - $stepScale(1)*$i]
	    .canvas create arc $startX $startY $endX $endY \
		    -outline black -tags axis -extent 180
	}
	.canvas create arc $x0Canvas $topY $xmCanvas $bottomY \
		-outline black -tags axis -extent 180 -width 2.0
	for {set i 0} {$i <= $div1} {incr i} {
	    .canvas create text $centerX [expr $topY + $i*$stepScale(1)+7] \
		    -text "[expr int($startValue-$stepAxis1*$i)]"  \
		    -font $fontAxis -tags Axis($i) -anchor e
	}
	.canvas create text [expr $centerX+50] $topY -text "$axisLabel(2)" \
		-font $fontAngle -tags angleAxisT -anchor s

	set tmpDif [expr double($endAngle-$startAngle)/2]
	.canvas create text [expr $xmCanvas+5] $centerY -font $fontAngle \
		-text "[expr int($endAngle)]" -tags angleAxis -anchor w
	.canvas create text $centerX $topY -font $fontAngle -anchor s \
		-text "[expr int($endAngle-$tmpDif)]" -tags angleAxis 
	.canvas create text [expr $x0Canvas-5] $centerY -font $fontAngle \
		-text "[expr int($startAngle)]" -tags angleAxis -anchor e
	.canvas create text [expr $centerX+$stepScale(1)/2.0] \
		[expr $centerY+$stepScale(1)/4.0] -text "$axisLabel(1)" \
		-font $fontAxis -tags axisT
    }
}


# drawData -- Drawing Data Line on Canvas
#
# Arguments    : Data Number
# Return Value : None
#
proc drawData {num} {
    global angle value isDraw isLine graphForm centerX centerY stepScale
    global stepAxis1 stepAxis2 lineColor lineWidth startValue endValue 
    global startAngle endAngle lineTag deg2rad

    set magnif  [expr double($stepScale(1))/$stepAxis1]

    .canvas delete lineTag($num); set isLine($num) ""
    set j 0 ; set datas "" ; set offAngle ""

    if {$graphForm == "full"} {	set offAngle 90 } else { set offAngle -180 }
    while {$angle($num,$j) < $startAngle} {incr j}

    while {$angle($num,$j) != "END"} {
	if {$angle($num,$j) > $endAngle} { break }
	set tmpValue ""
	if {$value($num,$j) < $endValue} {
	    set tmpValue $endValue
	} elseif {$value($num,$j) > $startValue} {
	    set tmpValue $startValue
	} else { set tmpValue $value($num,$j) }

	set realAngle [expr ($startAngle-$angle($num,$j)+$offAngle)*$deg2rad]
	set realValue [expr ($tmpValue-$endValue)*$magnif]
	set realX [expr $realValue*cos($realAngle)+$centerX]
	set realY [expr $centerY-$realValue*sin($realAngle)]

	lappend datas $realX $realY ; incr j
    }

    # Drawing Data 
    if {[llength $datas] >= 4} {
	set temp [eval .canvas create line $datas -width $lineWidth($num)\
		-fill $lineColor($num) -tags lineTag($num)]
    }
    set isLine($num) "YES"
}


# drawNotes -- Drawing Notes on Canvas
#
# Arguments    : x, y of position 
# Return Value : None
#
proc drawNotes {keyX keyY} {
    global font fontNote
    global isKey Key dataOK lineColor keyColors isDraw keyWidth keyHeight 
    global nowX nowY halfFrameX halfFrameY okKey frameType orderType 

    if {$isKey != ""} { return }
    .canvas delete keys

    # Number of notes
    set numKey 0 
    for {set i 1} {$i < 5} {incr i} {
	set okKey($i) 0
	if {$isDraw($i) == 1 && $dataOK($i) == "OK"} {
	    incr numKey ; set okKey($i) 1
	}
    }

    if {$numKey == 0} { return }

    set maxLetter 0
    for {set i 1} {$i < 5} {incr i} {
	set tmp [string length $Key($i)]
	if {$tmp > $maxLetter} { set maxLetter $tmp}
	if {$keyColors == "Black"} {
	    set keyColor($i) black
	} else {
	    set keyColor($i) $lineColor($i)
	}	   
    }

    if {$orderType == 1} {
	set j 1
	for {set i 1} {$i < 5} {incr i} {
	    if {$okKey($i) == 1} {
		set isKey [.canvas create line $keyX [expr $keyY+$j*25] \
			[expr $keyX+50] [expr $keyY+$j*25] \
			-fill $lineColor($i) -width 2.0 -tags keys]
		.canvas create text [expr $keyX+60] \
			[expr $keyY+$j*25] -text $Key($i) -font $fontNote \
			-fill black -anchor w -tags keys
		incr j
	    }
	}
    } elseif {$orderType == 2} {
	set tmpWidth "" ; set j 1
	for {set i 1} {$i < 5} {incr i} {
	    if {$okKey($i) == 1} {
		if {$tmpWidth != ""} {
		    set tmpW [expr ($tmpWidth+10)*$j] ; incr j
		} else {
		    set tmpW 0
		}
		set isKey [.canvas create line [expr $keyX+$tmpW] \
			[expr $keyY+25] [expr $keyX+$tmpW+50] [expr $keyY+25] \
			-fill $lineColor($i) -width 2.0 -tags keys]
		.canvas create text [expr $keyX+$tmpW+60] [expr $keyY+25] \
			-text $Key($i) -font $fontNote -fill $lineColor($i) \
			-anchor w -tags keys
		if {$tmpWidth == ""} {
		    set tmpWidth [expr [lindex [.canvas bbox keys] 2] \
			    - [lindex [.canvas bbox keys] 0]]
		}
	    }
	}
    } else {
	set tmpWidth "" ; set tmpHeight 0 ; set j 0 ; set k 0
	for {set i 1} {$i < 5} {incr i} {
	    if {$okKey($i) == 1} {
		if {$tmpWidth != ""} {
		    set tmpW [expr ($tmpWidth+10)*$j] 
		} else {
		    set tmpW 0
		}
		set isKey [.canvas create line [expr $keyX+$tmpW] \
			[expr $keyY+25+$tmpHeight*$k] [expr $keyX+$tmpW+50] \
			[expr $keyY+25+$tmpHeight*$k] \
			-fill $lineColor($i) -width 2.0 -tags keys]
		.canvas create text [expr $keyX+$tmpW+60] \
			[expr $keyY+25+$tmpHeight*$k] -text $Key($i) \
			-font $fontNote -fill $lineColor($i) \
			-anchor w -tags keys
		if {$tmpWidth == ""} {
		    set tmpWidth [expr [lindex [.canvas bbox keys] 2] \
			    - [lindex [.canvas bbox keys] 0]]
		    set tmpHeight [expr [lindex [.canvas bbox keys] 3] \
			    - [lindex [.canvas bbox keys] 1]]
		}
		incr j
		if {$j == 2} { set k 1 ; set j 0 }
	    }
	}
    }

    set x1 [lindex [.canvas bbox keys] 0]
    set y1 [lindex [.canvas bbox keys] 1]
    set x2 [lindex [.canvas bbox keys] 2]
    set y2 [lindex [.canvas bbox keys] 3]
    set keyWidth [expr $x2-$x1+20] ; set keyHeight [expr $y2-$y1+20]
    
    if {$frameType == 1} {
	.canvas create rectangle [expr $x1-5] [expr $y1-5] [expr $x2+15] \
		[expr $y2+15] -fill black -outline black -tags keys
	.canvas create rectangle [expr $x1-10] [expr $y1-10] [expr $x2+10] \
		[expr $y2+10] -fill white -outline black -tags keys
    } elseif {$frameType == 2} {
	.canvas create rectangle [expr $x1-10] [expr $y1-10] [expr $x2+10] \
		[expr $y2+10] -fill white -outline black -tags keys
    } else {
	;# No Frame
    }

    if {$orderType == 1} {
	set j 1
	for {set i 1} {$i < 5} {incr i} {
	    if {$okKey($i) == 1} {
		.canvas create line $keyX [expr $keyY+$j*25] [expr $keyX+50] \
			[expr $keyY+$j*25] -fill $lineColor($i) -width 2.0 \
			-tags keys
		.canvas create text [expr $keyX+60] [expr $keyY+$j*25] \
			-text $Key($i) -font $fontNote -fill $keyColor($i) \
			-anchor w -tags keys
		incr j
	    }
	}
    } elseif {$orderType == 2} {
	set j 1
	for {set i 1} {$i < 5} {incr i} {
	    if {$okKey($i) == 1} {
		set tmpW [expr ($tmpWidth+10)*($j-1)] ; incr j
		set isKey [.canvas create line [expr $keyX+$tmpW] \
			[expr $keyY+25] [expr $keyX+$tmpW+50] [expr $keyY+25] \
			-fill $lineColor($i) -width 2.0 -tags keys]
		.canvas create text [expr $keyX+$tmpW+60] [expr $keyY+25] \
			-text $Key($i) -font $fontNote \
			-fill $keyColor($i) -anchor w -tags keys
	    }
	}
    } else {
	set j 0 ; set k 0
	for {set i 1} {$i < 5} {incr i} {
	    if {$okKey($i) == 1} {
		if {$tmpWidth != ""} {
		    set tmpW [expr ($tmpWidth+10)*$j] 
		} else {
		    set tmpW 0
		}
		set isKey [.canvas create line [expr $keyX+$tmpW] \
			[expr $keyY+25+$tmpHeight*$k] [expr $keyX+$tmpW+50] \
			[expr $keyY+25+$tmpHeight*$k] -fill $lineColor($i) \
			-width 2.0 -tags keys]
		.canvas create text [expr $keyX+$tmpW+60] \
			[expr $keyY+25+$tmpHeight*$k] -text $Key($i) \
			-font $fontNote -fill $keyColor($i) -anchor w \
			-tags keys
		if {$tmpWidth == ""} {
		    set tmpWidth [expr [lindex [.canvas bbox keys] 2] \
			    - [lindex [.canvas bbox keys] 0]]
		    set tmpHeight [expr [lindex [.canvas bbox keys] 3] \
			    - [lindex [.canvas bbox keys] 1]]
		}
		incr j
		if {$j == 2} { set k 1 ; set j 0 }
	    }
	}
    }
    set nowX $keyX ; set nowY $keyY
}

# Binding for moving numbers and axis labels
.canvas bind Axis(0) <ButtonPress-1> {set xd(0) %x; set yd(0) %y}
.canvas bind Axis(1) <ButtonPress-1> {set xd(1) %x; set yd(1) %y}
.canvas bind Axis(2) <ButtonPress-1> {set xd(2) %x; set yd(2) %y}
.canvas bind Axis(3) <ButtonPress-1> {set xd(3) %x; set yd(3) %y}
.canvas bind Axis(4) <ButtonPress-1> {set xd(4) %x; set yd(4) %y}
.canvas bind Axis(5) <ButtonPress-1> {set xd(5) %x; set yd(5) %y}
.canvas bind Axis(6) <ButtonPress-1> {set xd(6) %x; set yd(6) %y}
.canvas bind Axis(7) <ButtonPress-1> {set xd(7) %x; set yd(7) %y}
.canvas bind Axis(8) <ButtonPress-1> {set xd(8) %x; set yd(8) %y}
.canvas bind Axis(9) <ButtonPress-1> {set xd(9) %x; set yd(9) %y}
.canvas bind Axis(10) <ButtonPress-1> {set xd(10) %x; set yd(10) %y}
.canvas bind Axis(11) <ButtonPress-1> {set xd(11) %x; set yd(11) %y}
.canvas bind Axis(12) <ButtonPress-1> {set xd(12) %x; set yd(12) %y}
.canvas bind Axis(13) <ButtonPress-1> {set xd(13) %x; set yd(13) %y}
.canvas bind Axis(14) <ButtonPress-1> {set xd(14) %x; set yd(14) %y}
.canvas bind Axis(15) <ButtonPress-1> {set xd(15) %x; set yd(15) %y}
.canvas bind Axis(16) <ButtonPress-1> {set xd(16) %x; set yd(16) %y}
.canvas bind Axis(17) <ButtonPress-1> {set xd(17) %x; set yd(17) %y}
.canvas bind Axis(18) <ButtonPress-1> {set xd(18) %x; set yd(18) %y}
.canvas bind Axis(19) <ButtonPress-1> {set xd(19) %x; set yd(19) %y}
.canvas bind angleAxisT <ButtonPress-1> {set xd(angleT) %x; set yd(angleT) %y}
.canvas bind axisT <ButtonPress-1> {set xd(axisT) %x; set yd(axisT) %y}
.canvas bind Axis(0) <B1-Motion> {
	.canvas move Axis(0) [expr %x-$xd(0)] [expr %y-$yd(0)]
	set xd(0) %x; set yd(0) %y
}
.canvas bind Axis(1) <B1-Motion> {
	.canvas move Axis(1) [expr %x-$xd(1)] [expr %y-$yd(1)]
	set xd(1) %x; set yd(1) %y
}
.canvas bind Axis(2) <B1-Motion> {
	.canvas move Axis(2) [expr %x-$xd(2)] [expr %y-$yd(2)]
	set xd(2) %x; set yd(2) %y
}
.canvas bind Axis(3) <B1-Motion> {
	.canvas move Axis(3) [expr %x-$xd(3)] [expr %y-$yd(3)]
	set xd(3) %x; set yd(3) %y
}
.canvas bind Axis(4) <B1-Motion> {
	.canvas move Axis(4) [expr %x-$xd(4)] [expr %y-$yd(4)]
	set xd(4) %x; set yd(4) %y
}
.canvas bind Axis(5) <B1-Motion> {
	.canvas move Axis(5) [expr %x-$xd(5)] [expr %y-$yd(5)]
	set xd(5) %x; set yd(5) %y
}
.canvas bind Axis(6) <B1-Motion> {
	.canvas move Axis(6) [expr %x-$xd(6)] [expr %y-$yd(6)]
	set xd(6) %x; set yd(6) %y
}
.canvas bind Axis(7) <B1-Motion> {
	.canvas move Axis(7) [expr %x-$xd(7)] [expr %y-$yd(7)]
	set xd(7) %x; set yd(7) %y
}
.canvas bind Axis(8) <B1-Motion> {
	.canvas move Axis(8) [expr %x-$xd(8)] [expr %y-$yd(8)]
	set xd(8) %x; set yd(8) %y
}
.canvas bind Axis(9) <B1-Motion> {
	.canvas move Axis(9) [expr %x-$xd(9)] [expr %y-$yd(9)]
	set xd(9) %x; set yd(9) %y
}
.canvas bind Axis(10) <B1-Motion> {
	.canvas move Axis(10) [expr %x-$xd(10)] [expr %y-$yd(10)]
	set xd(10) %x; set yd(10) %y
}
.canvas bind Axis(11) <B1-Motion> {
	.canvas move Axis(11) [expr %x-$xd(11)] [expr %y-$yd(11)]
	set xd(11) %x; set yd(11) %y
}
.canvas bind Axis(12) <B1-Motion> {
	.canvas move Axis(12) [expr %x-$xd(12)] [expr %y-$yd(12)]
	set xd(12) %x; set yd(12) %y
}
.canvas bind Axis(13) <B1-Motion> {
	.canvas move Axis(13) [expr %x-$xd(13)] [expr %y-$yd(13)]
	set xd(13) %x; set yd(13) %y
}
.canvas bind Axis(14) <B1-Motion> {
	.canvas move Axis(14) [expr %x-$xd(14)] [expr %y-$yd(14)]
	set xd(14) %x; set yd(14) %y
}
.canvas bind Axis(15) <B1-Motion> {
	.canvas move Axis(15) [expr %x-$xd(15)] [expr %y-$yd(15)]
	set xd(15) %x; set yd(15) %y
}
.canvas bind Axis(16) <B1-Motion> {
	.canvas move Axis(16) [expr %x-$xd(16)] [expr %y-$yd(16)]
	set xd(16) %x; set yd(16) %y
}
.canvas bind Axis(17) <B1-Motion> {
	.canvas move Axis(17) [expr %x-$xd(17)] [expr %y-$yd(17)]
	set xd(17) %x; set yd(17) %y
}
.canvas bind Axis(18) <B1-Motion> {
	.canvas move Axis(18) [expr %x-$xd(18)] [expr %y-$yd(18)]
	set xd(18) %x; set yd(18) %y
}
.canvas bind Axis(19) <B1-Motion> {
	.canvas move Axis(19) [expr %x-$xd(19)] [expr %y-$yd(19)]
	set xd(19) %x; set yd(19) %y
}


.canvas bind axisT <B1-Motion> {
	.canvas move axisT [expr %x-$xd(axisT)] [expr %y-$yd(axisT)]
	set xd(axisT) %x; set yd(axisT) %y
}
.canvas bind angleAxisT <B1-Motion> {
	.canvas move angleAxisT [expr %x-$xd(angleT)] [expr %y-$yd(angleT)]
	set xd(angleT) %x; set yd(angleT) %y
}


# change_color -- Change color of line bitmap and the number of width
#
# Argument     : Path of frame and Frame Number
# Return Value : None
#
proc change_color {w i} {
    global tmpColor

    set value [tk_chooseColor] ; if {$value == ""} {return}
    $w.color configure -fg $value -activeforeground $value -text $value
    $w.width configure -fg $value -activeforeground $value
    set tmpColor($i) $value
}


# change_width -- Change color of line bitmap and the number of width
#
# Argument     : Path of frame and line width
# Return Value : None
#
proc change_width {w value} { $w configure -text $value }


# normData -- Normalizing Data on Memory(The Data has been read)
#
# Argument     : Path of Top
# Return Value : None
#
proc normData {w num} {
    global font dataOK

    if {[winfo exist .top2]}   {return}
    if {$dataOK($num) != "OK"} {return}
    
    toplevel .top2 ; wm group .top2 $w
    wm title .top2 "Normalize Data" ; grab set .top2

    global toValue type wait_var2
    set toValue "0.0" ; set type  $num ; set wait_ver2 ""

    frame .top2.max1 -bd 3 -width 300 ; frame .top2.max2 -bd 3 -width 300
    frame .top2.arb  -bd 3 -width 300
    frame .top2.bottom -bd 3 -relief ridge -width 300 -height 100

    label .top2.title -text "Normalizing Data No.$num with" -font $font(3)

    for {set i 1} {$i < 5} {incr i} {
	radiobutton .top2.b$i -text "Data No.$i" -font $font(2) -bd 2\
		-variable type -value "$i" -justify left \
		-command {.top2.value configure -state disabled -fg gray50} 
    }
    radiobutton .top2.bArb -text "Arbitrary Value" -font $font(2) -bd 2\
	    -variable type -value "ARB" -justify left \
	    -command { .top2.value configure -state normal -fg black} 

    entry .top2.value -font $font(2) -textvariable toValue -width 5 -bd 3 \
	    -state disabled -fg gray50
    bind .top2.value <Return> {
	if {[catch {expr double($toValue)}]} { set toValue 0.0 } \
		else { focus .top2.ok	}
    }
    bind .top2.value <Leave> {
	if {[catch {expr double($toValue)}]} {
	    set toValue 0.0 ; focus .top2.ok
	} else { focus .top2.ok	}
    }

    if {$type != "ARB"} { .top2.value configure -state disabled }
    for {set i 1} {$i < 5} {incr i} {
	if {$dataOK($i) != "OK"} { .top2.b$i configure -state disabled }
    }

    button .top2.ok -text "Okay" -font $font(4) -width 7 \
	    -activeforeground blue -bd 3 -command {set wait_var2 1} 
    button .top2.cancel -text "Cancel" -font $font(4) -width 7 \
	    -activeforeground red -bd 3 -command {set wait_var2 0 }

    pack .top2.title -anchor w -side top
    pack .top2.b1 .top2.b2 -side left -in .top2.max1
    pack .top2.b3 .top2.b4 -side left -in .top2.max2
    pack .top2.bArb .top2.value -side left -in .top2.arb -padx 2
    pack .top2.ok .top2.cancel -side left -in .top2.bottom -fill x -expand yes
    pack .top2.max1 .top2.max2 .top2.arb .top2.bottom -side top -fill x

    tkwait variable wait_var2

    if {$wait_var2 == 1} { normalizer $num $type $toValue }
    if {[winfo exist .top2]} { destroy .top2 } ; grab release .top2
}


# config_data -- Configuration Drawing Datas
#
# Argument     : Path of Top 
# Return Value : none
#
proc config_data {w} {
    global font colors widths file dataOK angleRow valueRow
    global lineColor keyColor lineWidth isDraw Key isKey lineTag normOK
    global tmpDraw tmpWidth tmpColor tmpKey nowX nowY wait_var
    
    if {[winfo exist .top]} { return }

    toplevel .top -relief groove
    wm group .top $w ; wm title .top "Edit Data" ; grab set .top

    set wait_var ""

    foreach i {1 2 3 4} {
	set tmpDraw($i)  $isDraw($i)    ; set tmpWidth($i) $lineWidth($i)
	set tmpColor($i) $lineColor($i) ; set tmpKey($i)   $Key($i)
	set normOK($i)   0
    }

    # Widgets
    frame .top.0 -bd 3 
    label .top.0.draw  -text "Draw?"     -font $font(2) -width 7
    label .top.0.file  -text "File Name" -font $font(2) -width 15
    label .top.0.angle -text "Angle"     -font $font(2) -width 6
    label .top.0.value -text "Value"     -font $font(2) -width 6
    label .top.0.color -text "Color"     -font $font(2) -width 7
    label .top.0.width -text "Width"     -font $font(2) -width 7
    label .top.0.note  -text "Key"       -font $font(2) -width 12
    label .top.0.norm  -text "Normalize" -font $font(1) -width 12
    pack .top.0.draw .top.0.file .top.0.angle .top.0.value \
	    .top.0.color .top.0.width .top.0.note .top.0.norm -side left \
	    -expand yes -fill x

    foreach i {1 2 3 4} {
	frame .top.$i -bd 3
	checkbutton .top.$i.draw -variable tmpDraw($i) -text "Data$i" \
		-font $font(1) -bd 2
	label .top.$i.file -text "$file($i)"    -font $font(2) -width 15 \
		-relief groove -bd 5
	label .top.$i.angle -text $angleRow($i) -font $font(2) -width 5 \
		-relief sunken -bd 5
	label .top.$i.value -text $valueRow($i) -font $font(2) -width 5 \
		-relief sunken -bd 5

	button .top.$i.color  -text $tmpColor($i) -font $font(2) \
		-width 6 -relief raised -bd 4 -foreground $lineColor($i) \
		-activeforeground $lineColor($i) \
		-command "change_color .top.$i $i"
	menubutton .top.$i.width -menu .top.$i.width.m -text $lineWidth($i) \
		-font $font(1) -width 6 -height 1 -relief raised -bd 5 \
		-fg $tmpColor($i) -activeforeground $tmpColor($i)
	menu .top.$i.width.m -tearoff 0
	foreach width $widths {
	    .top.$i.width.m add radiobutton -label $width\
		    -variable tmpWidth($i) -value $width -font $font(2) \
		    -command "change_width .top.$i.width $width"
	}
	entry .top.$i.note -font $font(2) -textvariable tmpKey($i) \
		-width 10 -relief sunken -bd 5
	button .top.$i.norm -text "Data No.$i" -font $font(2) -bd 5\
		-activeforeground dodgerblue -command "normData . $i"

	pack .top.$i.draw .top.$i.file .top.$i.angle .top.$i.value \
		.top.$i.color .top.$i.width .top.$i.note .top.$i.norm \
		-side left -padx 1
    }
    pack .top.0 .top.1 .top.2 .top.3 .top.4 -side top -fill x -expand yes

    frame .top.bottom -bd 3 -relief groove
    button .top.bottom.ok -text "Okay" -font $font(4) -bd 3 -width 7\
	    -activeforeground blue -command {set wait_var 1}
    button .top.bottom.cancel -text "Cancel" -font $font(4) -bd 3 -width 7\
	    -activeforeground red -command {set wait_var 0 }
    pack .top.bottom.cancel .top.bottom.ok -side right

    pack .top.bottom -side top -anchor e

    # Bind
    foreach i {1 2 3} {
	bind .top.$i.note <Return> "focus .top.[expr $i+1].note"
    }
    bind .top.4.note <Return> {focus .top.bottom.ok}

    tkwait variable wait_var

    set anyNorm 0
    for {set i 1} {$i < 5} {incr i} {
	set anyNorm [expr $anyNorm + $normOK($i)]
    }
 
    if {$wait_var == 1 || $anyNorm != 0} {
	foreach i {1 2 3 4} {

	    # Check whether line colors and/or widths are changed or not.
	    if {$lineColor($i) != $tmpColor($i) || \
		    $lineWidth($i) != $tmpWidth($i)} {
		set lineWidth($i) $tmpWidth($i)
		set lineColor($i) $tmpColor($i)
		set keyColor($i)  $lineColor($i)
		.canvas itemconfigure lineTag($i) \
			-fill $lineColor($i) -width $lineWidth($i)
	    }

	    if {$isDraw($i) != $tmpDraw($i) || $normOK($i) == 1} {
		set isDraw($i) $tmpDraw($i)
		if {$dataOK($i) == "OK" && $isDraw($i) == 1} {
		    drawData $i	
		} else {
		    .canvas delete lineTag($i)
		    set isLine($i) ""; set isDraw($i) 0
		}
	    } 
	    if {$Key($i) != $tmpKey($i)} { set Key($i) $tmpKey($i) }
	}
	
	if {$isKey != ""} { set isKey "" ; drawNotes $nowX $nowY }
    }
    
    if {[winfo exist .top]} { destroy .top } ; grab release .top
}


# selectGraphForm -- Selecting Graph Form
#
# Argument     : Path of frame
# Return Value : none
#
proc selectGraphForm {w} {
    global font stepAxis1 stepAxis2 stepAngle startValue endValue isSubCircle
    global startAngle endAngle isAngleLine axisLabel graphForm
    global axisLabel nowX nowY isKey

    global tmpGraph tmpStart tmpEnd tmpMax tmpMin tmpStep1 tmpStep2
    global tmpAngleStep tmpAngle tmpSubCircle tmpAxisLabel

    if {[winfo exist .top]} { return }

    toplevel .top -relief groove -bd 5 -width 630 -height 300
    wm group .top $w; grab set .top ; wm title .top "Edit Graph"

    set tmpGraph $graphForm
    set tmpStart $startAngle          ; set tmpEnd $endAngle
    set tmpMax $startValue            ; set tmpMin $endValue
    set tmpStep1 $stepAxis1           ; set tmpStep2 $stepAxis2  
    set tmpAngleStep $stepAngle       ; set tmpAngle $isAngleLine
    set tmpSubCircle $isSubCircle
    set tmpAxisLabel(1) $axisLabel(1) ; set tmpAxisLabel(2) $axisLabel(2)
    global wait_var ; set wait_var ""

    button .top.ok -text "Okay" -font $font(4) -activeforeground blue\
	    -command {set wait_var 1} -width 5 -bd 3
    button .top.cancel -text "Cancel" -font $font(4) -bd 3\
	    -activeforeground red -command {set wait_var 0} -width 6
    radiobutton .top.full -text "Circle" -font $font(2) -value "full"\
	    -bd 3 -relief flat -width 12 -anchor w\
	    -variable tmpGraph -command {set tmpStart 0; set tmpEnd 360}
    radiobutton .top.semi -text "SemiCircle" -font $font(2) -value "semi" \
	    -bd 3 -relief flat -width 12 -anchor w\
	    -variable tmpGraph -command {set tmpStart -90; set tmpEnd 90}
    checkbutton .top.isAngle -text "Drawing Angle Line" -font $font(2) -bd 3 \
	    -variable tmpAngle -onvalue YES -relief sunken -command { \
	    if {$tmpAngle == "YES"} {
	.top.stepAngle configure -state normal -fg black
    } else { 
	.top.stepAngle configure -state disabled -fg gray50}
    }

    checkbutton .top.isValue -text "Sub Circles" -font $font(2) -bd 3 \
	    -variable tmpSubCircle -onvalue YES \
	    -relief sunken -width 12 -anchor w \
	    -command {if {$tmpSubCircle == "YES"} {
	.top.stepAxis2 configure -state normal -fg black
    } else {
	.top.stepAxis2 configure -state disabled -fg gray50}
    }
    
    label .top.graphText      -text "Graph Type"        -font $font(2)
    label .top.valueText      -text "Value Range"       -font $font(2)
    label .top.maxValueText   -text "Max."              -font $font(2)
    label .top.minValueText   -text "Min."              -font $font(2)
    label .top.angleText      -text "Angle Range"       -font $font(2)
    label .top.startAngleText -text "Start"             -font $font(2)
    label .top.endAngleText   -text "End"               -font $font(2)
    label .top.standardText   -text "Standard Circles" -font $font(2)
    label .top.unit0          -text "\[deg.\]"         -font $font(1)
    label .top.unit1          -text "step/circle"      -font $font(1)
    label .top.unit2          -text "step/circle"      -font $font(1)
    label .top.labelText      -text "Axis Label1   Label2" -font $font(1)

    entry .top.maxValue   -font $font(2) -textvariable tmpMax -width 5 -bd 3
    entry .top.minValue   -font $font(2) -textvariable tmpMin -width 5 -bd 3
    entry .top.startAngle -font $font(2) -textvariable tmpStart -width 5 -bd 3
    entry .top.endAngle   -font $font(2) -textvariable tmpEnd   -width 5 -bd 3\
	    -state disabled -fg gray50
    entry .top.stepAngle  -font $font(2) -textvariable tmpAngleStep -width 3 \
	    -bd 3

    for {set i 1} {$i < 3} {incr i} {
	entry .top.stepAxis$i -font $font(2) -textvariable tmpStep$i \
		-width 3 -bd 3
	entry .top.label$i -font $font(2) -textvariable tmpAxisLabel($i) \
		-width 6 -bd 3
    }
    canvas .top.sample -height 180 -width 180

    # Drawing Sample Graphic
    .top.sample create line 5 30 5 175 -fill black -width 2
    .top.sample create line 5 175 150 175 -fill black -width 2
    .top.sample create arc  -140 30 150 320 -outline black -extent 90 -width 2
    .top.sample create arc  -73 103 78 248 -outline blue -extent 90 \
	    -width 2 -style arc
    .top.sample create text 100 25 -text "Standard Circle" -font $font(1) \
	    -fill blue
    .top.sample create arc -104 66 114 284 -outline green3 -extent 90 \
	    -width 2 -style arc
    .top.sample create arc -31 139 41 211 -outline green3 -extent 90 \
	    -width 2 -style arc
    .top.sample create text 140 140 -text "Sub Circles" -fill green3 \
	    -font $font(1)
    .top.sample create line 140 145 140 150 115 160 -fill green3 
    .top.sample create line 140 150 38 170          -fill green3 
    .top.sample create text 15 38 -text "0"    -font $font(1)
    .top.sample create text 15 95 -text "-10"  -font $font(1)
    .top.sample create text 15 167 -text "-20" -font $font(1)
    .top.sample create line 100 30 70 140           -fill midnightblue 
    .top.sample create text 140 60 -text "Angle Lines" -fill red \
	    -font $font(1)
    .top.sample create line 5 175 130 102  -fill red -width 2
    .top.sample create line 5 175 78  50   -fill red -width 2
    .top.sample create line 140 65 120 105 -fill red
    .top.sample create line 138 70 60 80   -fill red

    place .top.graphText -relx 0.01 -rely 0
    place .top.full -relx 0.03 -rely 0.1
    place .top.semi -relx 0.03 -rely 0.2

    place .top.isAngle        -relx 0.35 -rely 0
    place .top.stepAngle      -relx 0.42 -rely 0.1
    place .top.unit0          -relx 0.5 -rely 0.12
    place .top.valueText      -relx 0.35 -rely 0.25
    place .top.maxValueText   -relx 0.37 -rely 0.33
    place .top.minValueText   -relx 0.48 -rely 0.33
    place .top.maxValue       -relx 0.38 -rely 0.43
    place .top.minValue       -relx 0.49 -rely 0.43
    place .top.angleText      -relx 0.35 -rely 0.6
    place .top.startAngleText -relx 0.37 -rely 0.68
    place .top.endAngleText   -relx 0.48 -rely 0.68
    place .top.startAngle     -relx 0.38 -rely 0.78
    place .top.endAngle       -relx 0.49 -rely 0.78

    place .top.standardText -relx 0.7  -rely 0
    place .top.stepAxis1    -relx 0.73 -rely 0.1
    place .top.unit1        -relx 0.8  -rely 0.12
    place .top.isValue      -relx 0.73 -rely 0.23
    place .top.stepAxis2    -relx 0.78 -rely 0.34
    place .top.unit2        -relx 0.85 -rely 0.36

    place .top.labelText -relx 0.7  -rely 0.5
    place .top.label1    -relx 0.73 -rely 0.6
    place .top.label2    -relx 0.85 -rely 0.6

    place .top.ok      -relx 0.66 -rely 0.80
    place .top.cancel -relx 0.81 -rely 0.80

    place .top.sample -relx 0.03 -rely 0.32

    if {$tmpAngle != "YES"} {
	.top.stepAngle configure -state disabled -fg gray50
    }
    if {$tmpSubCircle != "YES"} {
	.top.stepAxis2 configure -state disabled -fg gray50
    }

    bind .top.startAngle <Return> {
	if {[catch {expr double($tmpStart)}] == 0} {
	    set tmpStart [expr int($tmpStart)]
	    set tmpEnd [expr {($tmpGraph == "full") ?\
		[expr $tmpStart + 360] : [expr $tmpStart + 180]}]
	    focus .top.ok
	} else { set tmpStart $startAngle }
    }
    bind .top.startAngle <Leave> {
	if {[catch {expr double($tmpStart)}] == 0} {
	    set tmpStart [expr int($tmpStart)]
	    set tmpEnd [expr {($tmpGraph == "full") ?\
		[expr $tmpStart + 360] : [expr $tmpStart + 180]}]
	    focus .top.ok
	} else { set tmpStart $startAngle ; focus .top.ok}
    }
    bind .top.maxValue   <Return> {
	if {[catch {expr double($tmpMax)}] == 0} {
	    focus .top.minValue
	} else { set tmpMax $startValue	}
    }
    bind .top.maxValue   <Leave> {
	if {[catch {expr double($tmpMax)}] == 0} {
	    focus .top.minValue
	} else { set tmpMax $startValue ; focus .top.minValue }
    }
    bind .top.minValue   <Return> {
	if {[catch {expr double($tmpMin)}] == 0 && $tmpMin < $tmpMax} {
	    focus .top.ok
	} else { set tmpMin $endValue }
    }
    bind .top.minValue   <Leave> {
	if {[catch {expr double($tmpMin)}] == 0 && $tmpMin < $tmpMax} {
	    focus .top.ok
	} else { set tmpMin $endValue ; focus .top.ok }
    }
    bind .top.stepAngle  <Return> {
	if {[catch {expr double($tmpAngleStep)}] == 0 && $tmpAngleStep < 90} {
	    set tmpAngleStep [expr int($tmpAngleStep)] ; focus .top.ok
	} else { set tmpAngleStep $stepAngle }
    }
    bind .top.stepAngle  <Leave> {
	if {[catch {expr double($tmpAngleStep)}] == 0 && $tmpAngleStep < 90} {
	    set tmpAngleStep [expr int($tmpAngleStep)] ; focus .top.ok
	} else { set tmpAngleStep $stepAngle ; focus .top}
    }
    bind .top.stepAxis1  <Return> {
	if {[catch {expr double($tmpStep1)}] == 0} { focus .top.ok } \
		else { set tmpStep1 $stepAxis1 }
    }
    bind .top.stepAxis1  <Leave> {
	if {[catch {expr double($tmpStep1)}] == 0} { focus .top.ok } \
		else { set tmpStep1 $stepAxis1 ; focus .top.ok}
    }
    bind .top.stepAxis2  <Return> {
	if {[catch {expr double($tmpStep2)}] == 0 && $tmpStep2 < $tmpStep1} {
	    focus .top.ok
	} else { set tmpStep2 [expr double($tmpStep1)/2] }
    }
    bind .top.stepAxis2  <Leave> {
	if {[catch {expr double($tmpStep2)}] == 0 && $tmpStep2 < $tmpStep1} {
	    focus .top.ok
	} else { set tmpStep2 [expr double($tmpStep1)/2] ; focus .top.ok}
    }
    bind .top.label1 <Return> {focus .top.label2}
    bind .top.label2 <Return> {focus .top.ok}

    tkwait variable wait_var

    if {$wait_var == 1} {
	set isChange 0

	if {$tmpGraph != $graphForm} {
	    set isChange 1 ; set graphForm $tmpGraph
	}

	if {$tmpStart != $startAngle} { set isChange 1 }
	set startAngle [expr int($tmpStart)]
	if {$graphForm == "full"} {
	    set endAngle [expr $startAngle + 360]
	} else {
	    set endAngle [expr $startAngle + 180]	
	}

	if {$tmpMax != $startValue} {
	    set startValue $tmpMax ; set isChange 1
	}


	if {$tmpMin != $endValue} {
	    if {$tmpMin < $startValue} { set endValue   $tmpMin }\
		    else { set endValue   [expr $startValue - 40] }
	    set isChange 1
	}

	if {$tmpStep1 != $stepAxis1} {
	    set stepAxis1 $tmpStep1 ; set isChange 1
	}

	if {$tmpStep2 != $stepAxis2} {
	    if {$tmpStep2 < $stepAxis1} { set stepAxis2 $tmpStep2 }\
		    else { set stepAxis2 [expr double($stepAxis1)/2.0] }
	    set isChange 1
	}

	if {$tmpAngleStep != $stepAngle} {
	    if {$tmpAngleStep < 90} {
		set stepAngle [expr int($tmpAngleStep)]
	    } else { set stepAngle 30 } ; set isChange 1
	}

	if {$tmpAngle != $isAngleLine} {
	    set isAngleLine $tmpAngle ; set isChange 1
	}
	if {$tmpSubCircle != $isSubCircle} {
	    set isSubCircle $tmpSubCircle ; set isChange 1
	}
	if {$tmpAxisLabel(1) != $axisLabel(1)} {
	    set axisLabel(1) $tmpAxisLabel(1) ; set isChange 1
	}
	if {$tmpAxisLabel(2) != $axisLabel(2)} {
	    set axisLabel(2) $tmpAxisLabel(2) ; set isChange 1
	}

	if {$isChange == 1} {
	    drawAxis
	    for {set i 1} {$i < 5} {incr i} {
		global dataOK isDraw
		if {$dataOK($i) == "OK" && $isDraw($i) == 1} { drawData $i }
		if {$isKey != ""} { set isKey "" ; drawNotes $nowX $nowY }
	    }
	}

	if {$graphForm == "full"} {
	    global sizeCanvas
	    wm aspect . 508 543 508 543
	    wm geometry . =[expr $sizeCanvas+8]x[expr $sizeCanvas+43]
	} else {
	    global sizeCanvasX sizeCanvasY
	    wm aspect . 708 543 708 543
	    wm geometry . =[expr $sizeCanvasX+8]x[expr $sizeCanvasY+43]
	}
    }

    if {[winfo exist .top]} { destroy .top ; grab release .top }
}


# readFile -- Reading File (Core Procedure)
#
# Arguments    : FileName, number of reading data row1, row2, LineNumber,
#                 check value of wheter CSV File or not, and chech value
#                 of whether HP-IB OutputFile or not.
# Return Value : Result (Normal ..., 0 Abnormal...1,2,3,4$B!K(B
#
proc readFile {DataFile Angle Value Num isCSV isHPIB} { 
    global value angle dataOK isDraw isLine tmpRead file

    if {![file exists $DataFile]} {
	file_error "[file tail $readfile] doesn't exist" ; return 
    } elseif {[file size $DataFile] == 0} {
	file_error "[file tail $DataFile] is Empty" ; return 
    }

    if {[catch {expr int($Angle)}] != 0} { 
	return
    } elseif {[catch {expr int($Value)}] != 0} {
	return 
    }

    # Open Data File
    set in_fd [open $DataFile r]

    set i 0
    if {$isHPIB != "YES"} {
	# Off-set the row number
	set Angle [expr $Angle - 1] ; set Value [expr $Value - 1]
	if {$Angle < 0 || $Value < 0} {
	    set dataOK($Num) ""; set isDraw($i) 0
	    return 3 ;# Abnormal Finish
	}

	# Read Data (Comment Line has "#" at the head of the line)
	while {![eof $in_fd]} {
	    set line [gets $in_fd] ; regsub {
$} $line "" line
	    if {[llength $line] != 0 && [regexp {^\#} $line] != 1} {
		if {$isCSV == "YES"} { set line [split $line ,]	}
		
		# Read Angle and Value
		set tmp1 [scan [lrange $line $Angle $Angle] %f angle($Num,$i)]
		set tmp2 [scan [lrange $line $Value $Value] %f value($Num,$i)]
		
		if {$tmp1 != 1 || $tmp2 != 1} {
		    set dataOK($Num) ""; set isDraw($i) 0
		    return 1 ;# Abnormal Finish
		}
		incr i
	    }
	}
    } else {
	# Read Data of HP-IB formatted File
	set line [gets $in_fd] ; regsub {
$} $line "" line
	if {[lindex $line 0] != "CITIFILE"} { return 4 ;# Abnormal Finish }

	while {![eof $in_fd]} {
	    set line [gets $in_fd] ; regsub {
$} $line "" line
	    if {$line == "BEGIN"} {
		break
	    } elseif {$line == "SEG_LIST_BEGIN"} {
		set line [gets $in_fd] ; regsub {
$} $line "" line
		set tmp1 [scan [lrange $line 1 1] %f tmpStart]
		set tmp2 [scan [lrange $line 2 2] %f tmpEnd]
		set tmp3 [scan [lrange $line 3 3] %f tmpNumber]

		# Check whether the read data is a number or not
		if {$tmp1 != 1 || $tmp2 != 1 || $tmp3 != 1} {
		    return 1 ;# Abnormal Finish
		}
		
		set tmpStep [expr double($tmpEnd-$tmpStart) / ($tmpNumber-1)]
	    }
	}

	while {![eof $in_fd]} {
	    set line [gets $in_fd] ; regsub {
$} $line "" line
	    if {[llength $line] != 0 && $line != "END"} {
		# Reading real and imaginary part
		set tmp1 [scan [lrange [split $line ,] 0 0] %f real]
		set tmp2 [scan [lrange [split $line ,] 1 1] %f imag]

		if {$tmp1 != 1 || $tmp2 != 1} {
		    set dataOK($Num) ""; set isDraw($i) 0
		    return 1 ;# Abnormal Finish
		}
		set value($Num,$i) [expr 10.0*log10($real*$real+$imag*$imag)]
		set angle($Num,$i) [expr $tmpStart + $tmpStep*double($i)]

		incr i
	    }
	}
    }

    # Check whether the file has no valid data or not
    if {$i == 0} { return 2 } ;# Abnormal Finish

    # Normal Finish
    set angle($Num,$i) "END" ; set dataOK($Num) "OK" ; set isDraw($Num) 1
    set file($Num)  [file tail $DataFile] ; set isLine($Num) ""

    # Closing Data File
    close $in_fd ; set tmpRead "" ; return 0
}


# check_radios -- Check Status and Configure Radiobuttons
#                         for procedure of "readDataFile"
#
# Argument     : Widget Path on which radiobuttons are
# Return Value : None
# Create Date  : 1 Feb. 1997
#
proc check_radios { w } {
    global dataOK dataNum

    set flag "NO"

    for {set i 1} {$i < 5} {incr i} {
	if {$dataOK($i) == "OK"} {
	    $w.rb$i  conf -fg purple3 -activeforeground purple3
	} elseif {$flag == "NO"}  {
	    set flag "YES" ; set dataNum $i
	}
    }
    if {$dataNum == ""} {set dataNum 4}
}


# readDataFile -- Read Data File (Interface Procedure)
# 
# Argument     : Top Widget Path and Treating Type(READ/CONV)
# Return Value : None
# Create Date  : 31 Jan. 1997
#
proc readDataFile {w  how} {
    global font graphForm file curDir curDirC dataOK angleRow valueRow
    global dataNum isDraw angleNum valueNum angle value CSV HPIB
    global tmpAngle tmpValue tmpRead tmpConv isNorm toValue wait_var

    if {[winfo exist .top]} { return }

    toplevel .top -relief raised -bd 5 ; wm group .top $w; grab set .top 

    set tmpAngle  $angleNum  ; set tmpValue $valueNum  ; set tmpRead ""
    set HPIB     "NO"        ; set dataNum  ""         ; set wait_var 0
    set curDirC  $curDir     ; set toValue  ""

    #
    # Common Widgets
    #
    frame .top.1 -bd 10 ; frame .top.2 -bd 5 ; frame .top.3 -bd 5
    frame .top.4 -bd 5  ; frame .top.5 -bd 5 ; frame .top.6 -bd 10
    frame .top.bottom -bd 5 ; frame .top.read -bd 5 -relief groove
    frame .top.conv -bd 5 -relief groove

    label .top.dirT   -text "Directory Name : "   -font $font(3) -anchor w \
	    -bd 5
    label .top.dirName -bd 5                 -font $font(2) -anchor w
    label .top.fileT   -text "File Name : "  -font $font(3) -anchor w -bd 5
    label .top.typeT -text "Data Type : " -anchor w -font $font(3) -bd 5

    entry .top.value    -font $font(2) -textvariable tmpValue -bd 3 -width 3 
    entry .top.fileName -font $font(2) -textvariable tmpRead  -bd 5 -fg black

    checkbutton .top.bHPIB -text "HP-IB" -onvalue "YES" -font $font(2) -bd 3\
	    -variable HPIB -width 7 -anchor w
    checkbutton .top.bCSV  -text "CSV"   -onvalue "YES" -font $font(2) -bd 3\
	    -variable CSV  -width 7 -anchor w

    button .top.browse  -text "Browse" -font $font(2) -bd 3

    #
    # Widgets for READ/CONV
    #
    if {$how == "READ"} {
	wm title .top "Read Data Files"

	label .top.row_angleT -text "Row Number of Reading Data" \
		-font $font(3) -anchor w -bd 5
	label .top.valueT -text "Value : "       -font $font(3) -anchor w
	label .top.angleT -text "Angle : "       -font $font(3) -anchor w
	label .top.dataT  -text "Data Number"    -font $font(3) -anchor w -bd 5
	label .top.noticeT -text "(ReadData colored in Purple)" \
		-font $font(2) -fg purple3
	entry .top.angle -font $font(2) -textvariable tmpAngle -bd 3 -width 3 
	for {set i 1} {$i < 5} {incr i} {
	    radiobutton .top.rb$i -text "$i" -font $font(2) -value $i -bd 3\
		    -variable dataNum
	    pack .top.rb$i -side left -in .top.3 -expand yes
	}
	button .top.ok -width 7 -text "Read" -width 7 -font $font(4) -bd 3 \
		-activeforeground blue -command {  if {$tmpRead != ""} {\
		file_result [readFile $curDir/$tmpRead $tmpAngle $tmpValue \
		$dataNum $CSV $HPIB] YES} ; check_radios .top}
	
	.top.bHPIB conf -command {
	    set CSV "NO"
	    if {$HPIB == "YES"} {
		.top.angle conf -fg gray50 -state disabled
		.top.value conf -fg gray50 -state disabled
	    } else {
		.top.angle conf -fg black -state normal
		.top.value conf -fg black -state normal
	    }
	}
	.top.bCSV conf -command {
	    set HPIB "NO"
	    .top.angle conf -fg black -state normal
	    .top.value conf -fg black -state normal
	}
	.top.browse conf -command {
	    set tmpRead [ get_filename READ] ; zip_dirName .top.dirName $curDir
	}

	zip_dirName .top.dirName $curDir ; check_radios .top
    } else {
	wm title .top "Convert Data Files"

	label .top.convDirT   -text "OutputDirectory Name : " -font $font(3) \
		-anchor w  -bd 5
	label .top.convDirName -bd 5                 -font $font(2) -anchor w
	label .top.convFileT   -text "Output File Name : "  -font $font(3) \
		-anchor w -bd 5
	label .top.valueT -text "Row Number of Value : "    -font $font(3) \
		-anchor w
	entry .top.convFileName -font $font(2) -textvariable tmpConv -bd 5 \
		-fg black -state disabled
	button .top.convBrowse  -text "Browse" -font $font(2) -bd 3 -command {
	    if {$tmpRead != ""} {
		set tmpConv [ get_filename CONV]
		zip_dirName .top.convDirName $curDirC}
	    } -state disabled -fg gray50
	button .top.ok -width 7 -text "Convert" -width 7 -font $font(4) -bd 3 \
		-activeforeground blue -command {
	    if {$tmpRead != ""} { file_conv $normType $toValue}
	}
	checkbutton .top.isNorm -text "Normalize" -font $font(2) -bd 3\
		-width 9 -anchor w -variable isNorm -onvalue YES -command {
	    if {$isNorm == "YES"} {
		.top.normMax  conf -fg black -state normal
		.top.normArb  conf -fg black -state normal
		.top.normArbE conf -fg white ; set toValue 0.0
		set normType 0
	    } else {
		.top.normMax  conf -fg gray30 -state disabled
		.top.normArb  conf -fg gray30 -state disabled
		.top.normArbE conf -fg gray30 -state disabled
		set normType "" ; set toValue ""
	    }
	}
	radiobutton .top.normMax -text "Max. Value" -font $font(2) -bd 3\
		-fg gray30 -state disabled -width 14 -anchor w \
		-variable normType -value 0 -command {
		.top.normArbE conf -state disabled -fg white
	}
	radiobutton .top.normArb -text "Arbitrary Value" -font $font(2) -bd 3\
		-fg gray30 -state disabled -width 14 -anchor w \
		-variable normType -value ARB -command {
		.top.normArbE conf -state normal -fg black
	}
	entry .top.normArbE -font $font(2) -textvariable toValue \
		-bd 3 -width 5 -fg gray30 -state disabled

	.top.bHPIB conf -command {
	    set CSV "NO"
	    if {$HPIB == "YES"} {
		.top.value conf -fg gray50 -state disabled
	    } else {
		.top.value conf -fg black -state normal
	    }
	}
	.top.bCSV conf -command {
	    set HPIB "NO" ; .top.value conf -fg black -state normal
	}
	.top.browse conf -command {
	    set tmpRead [get_filename READ]
	    if {$tmpRead != ""} {
		set tmpConv [file rootname $tmpRead].$ext
		zip_dirName .top.dirName $curDir ; set curDirC $curDir
		zip_dirName .top.convDirName $curDirC
		focus .top.convFileName
		.top.convFileName conf -state normal
		.top.convBrowse   conf -state normal -fg black
	    } else {
		.top.convFileName conf -state disabled
		.top.convBrowse   conf -state disabled -fg gray50
		set tmpConv ""
	    }
	}

	zip_dirName .top.dirName $curDir ; zip_dirName .top.convDirName $curDir
    }

    button .top.close -text "Close" -width 7 -font $font(4) -bd 3 \
	    -activeforeground red -command {set wait_var 1}

    #
    # Packing Widgets
    
    # Packing Common Widgets
    pack .top.ok .top.close -side left -in .top.bottom -expand yes -fill x

    
    if {$how == "READ"} {
	pack .top.angleT .top.angle -side left  -in .top.1 -padx 10
	pack .top.value .top.valueT -side right -in .top.1 -padx 10
	pack .top.fileT  -side left  -in .top.2 -pady 1
	pack .top.browse -side right -in .top.2 -pady 1
	pack .top.bHPIB .top.bCSV -side left -in .top.4 -expand yes

	pack .top.row_angleT .top.1 .top.dirT .top.dirName .top.2 \
		.top.fileName .top.dataT .top.noticeT .top.3 .top.typeT \
		.top.4 .top.bottom -side top -fill x -expand yes -pady 1
    } else {
	pack .top.fileT  -side left  -in .top.2 -pady 1
	pack .top.browse -side right -in .top.2 -pady 1
	pack .top.valueT .top.value -side left -anchor w -in .top.3 -padx 10 \
		-expand yes
	pack .top.bHPIB .top.bCSV -side left -in .top.4 -expand yes
	pack .top.dirT .top.dirName .top.2 .top.fileName .top.3 .top.typeT \
		.top.4 -side top -in .top.read -fill x -expand yes
	pack .top.normMax -side top -anchor w -in .top.1
	pack .top.normArb .top.normArbE -side left -anchor w -in .top.1
	pack .top.isNorm .top.1 -side top -anchor w -in .top.6

	pack .top.convFileT  -side left  -in .top.5 -pady 1
	pack .top.convBrowse -side right -in .top.5 -pady 1
	pack .top.convDirT .top.convDirName .top.5 .top.convFileName \
		.top.6 -in .top.conv -side top -anchor w -expand yes -fill x

	pack .top.read .top.conv .top.bottom -side top -fill x -expand yes \
		-pady 1
    }


    # Bindings
    event add <<ReturnAndLeave>> <Return> <Leave>

    if {$how == "READ"} {
	bind .top.fileName <<ReturnAndLeave>> {
	    if {$tmpRead != "" && [file exists $tmpRead] == 1} {
		focus .top.ok
	    } else {
		set tmpRead ""
	    }
	}
	bind .top.angle <Any-Return> {
	    if {[catch {expr int($tmpAngle)}] == 0} {
		set tmpAngle [expr int($tmpAngle)]
	    } else {
		set tmpAngle $angleNum
	    }
	    focus .top.value
	}
	bind .top.angle <Leave> {
	    if {[catch {expr int($tmpAngle)}] == 0} {
		set tmpAngle [expr int($tmpAngle)]
	    } else {
		set tmpAngle $angleNum
	    }
	    focus .top.ok
	}
    } else {
	bind .top.fileName <<ReturnAndLeave>> {
	    if {[file exists $tmpRead] == 0} {
		set tmpRead ""
		.top.convFileName conf -state disabled
		.top.convBrowse   conf -state disabled -fg gray50
		set tmpConv ""
	    } elseif {$tmpRead != ""} {
		set tmpConv [file rootname $tmpRead].$ext
		.top.convFileName conf -state normal
		.top.convBrowse   conf -state normal -fg black
		focus .top.convFileName
	    }
	}
	bind .top.normArbE <<ReturnAndLeave>> {
	    if {$toValue == ""} {

	    } elseif {[catch {expr double($toValue)}] != 0} {
		set toValue 0.0 ; focus .top.ok
	    } else {
		focus .top.ok
	    }
	}
    }
    bind .top.value <<ReturnAndLeave>> {
	if {[catch {expr int($tmpValue)}] == 0} {
	    set tmpValue [expr int($tmpValue)]
	} else {
	    set tmpValue $valueNum
	} ; focus .top.ok
    }

    # Waiting untill change of "wait_var"
    tkwait variable wait_var

    global nowX nowY isKey isDraw isLine dataNum dataOK
    if {$how == "READ"} {
	for {set i 1} {$i < 5} {incr i} {
	    if {$dataOK($i) == "OK" && $isDraw($i) == 1 && $isLine($i)==""} {
		drawData $i
	    }
	}
	# Redraw Note if it was drawn.
	if {$isKey != ""} {
	    set isKey "" ; .canvas delete keys ; drawNotes $nowX $nowY 
	}
    }
    if {[winfo exist .top]} {destroy .top} ; grab release .top
}


# outputPS -- Output Graph on Canvas as PostScript File
#
# Argument     : PS filename
# Return Value : None
# Create Date  : 31 Jan. 1997
#
proc outputPS { PSfile times} {
    global graphForm sizeCanvas sizeCanvasX sizeCanvasY outPS

    if {[file exists $PSfile]} {
	set result [tk_messageBox -icon warning -type okcancel \
		-default cancel -title "The file exists" \
		-message "Overwrite $PSfile?"]
	if {$result == "cancel" } {
	    return
	} else {
	    if {![file writable $PSfile]} {
		tk_messageBox -icon error -type ok -default ok \
			-title "Output Error" \
			-message "You cannot write $PSfile. \
			Check Directory or File Mode"
		return
	    }
	}
    } else {
	if {![file writable [file dirname $PSfile]]} {
	    tk_messageBox -icon error -type ok -default ok \
		    -title "Output Error" \
		    -message "You cannot write $PSfile. Check Directory"
	    return
	}
    }


    if {$graphForm == "full"} {
	set pageHight [expr $sizeCanvas * $times]
	set pageWidth $pageHight
    } else {
	set pageWidth [expr $sizeCanvasX * $times]
	set pageHight [expr $sizeCanvasY * $times]
    }

    set outResult [.canvas postscript -file $PSfile \
	    -pageheight $pageHight -pagewidth $pageWidth -colormode color]
    
    if {$outResult == ""} {
	tk_messageBox -icon info -type ok -title "Success Information" \
		-message "Output of PS File is succeeded"
	set outPS [file tail $PSfile]
    } else {
	file_error "Cannot output PS file named \"$PSfile\" because $outResult"
    }
}


# outputFile -- Procedure for Output Files(Interface Procedure)
#
# Argument      : Paht of Top and Treating Type
# Return Value  : None
# Modified Date : 31 Jan. 1997 -> 2 Feb. 1997
#
proc outputFile {w how} {
    global font graphForm file outTgif outPS curDir dataOK angleRow valueRow
    global dataNum isDraw angleNum valueNum angle value CSV HPIB ext psSize
    global tmpAngle tmpValue tmpPS tmpTgif tmpSize wait_var 

    if {[winfo exist .top]} { return }

    toplevel .top -relief groove -bd 3 ; wm group .top $w; grab set .top 

    set tmpPS $outPS ; set tmpSize $psSize ; set tmpTgif $outTgif
    set wait_var 0

    # Frame 
    frame .top.1 -bd 5 ; frame .top.2 -bd 5 ;  frame .top.3 -bd 5
    frame .top.bottom -bd 5

    # Common Widgets
    label .top.dirT    -text "Directory Name : " -font $font(3) -anchor w -bd 5
    label .top.dirName -bd 5                     -font $font(2) -anchor w
    label .top.fileT   -text "File Name : " -bd 5 -font $font(3) -anchor w
    label .top.skel    -height 1
    entry .top.fileName -font $font(2) -bd 5 -fg black
    button .top.browse  -text "Browse" -font $font(2) -bd 3
    button .top.ok    -text "Output"  -width 7 -font $font(4) -bd 3 \
	    -activeforeground blue
    button .top.close -text "Close" -width 7 -font $font(4) -bd 3 \
	    -activeforeground red -command {set wait_var 1}

    # In Case of ...
    if {$how == "TGIF"} {
	wm title .top "Save as Tgif Object File"
	.top.fileName conf -textvariable tmpTgif
	.top.ok conf -command { if {$tmpTgif != ""} {
	    tgif_output $curDir/$tmpTgif }
	}
	.top.browse conf -command {set tmpTgif [ get_filename OutTGIF] ; \
	    zip_dirName .top.dirName $curDir}
    } elseif {$how == "PS"} {
	wm title .top "Save as PS File"
	.top.fileName conf -textvariable tmpPS
	.top.ok conf -command { if {$tmpPS != ""} {
	    outputPS $curDir/$tmpPS $tmpSize ; set psSize $tmpSize
	    }
	}
	.top.browse conf -command {set tmpPS [ get_filename OutPS] ; \
		zip_dirName .top.dirName $curDir}
	entry .top.sizeE  -textvariable tmpSize -font $font(2) -bd 5 -width 5
	label .top.sizeT -text "x Display Size" -font $font(2) -bd 3

	event add <<ReturnAndLeave>> <Return> <Leave>
	bind .top.sizeE <<ReturnAndLeave>> {
	    if {[catch {expr double($tmpSize)}]} {
		set tmpSize $psSize
	    } else {
		focus .top.ok
	    }
	}
	pack .top.sizeE .top.sizeT -side left -in .top.2
    }

    # Packing
    pack .top.fileT  -side left  -in .top.1
    pack .top.browse -side right -in .top.1
    pack .top.skel -side top -in .top.bottom
    pack .top.ok .top.close -side left -in .top.bottom -anchor s

    pack .top.dirT .top.dirName .top.1 .top.fileName -fill x
    pack .top.2 -side top -anchor e ; pack .top.bottom  -side top -fill x

    # Preparation 
    zip_dirName .top.dirName $curDir

    tkwait variable wait_var
    if {[winfo exist .top]} { grab release .top ; destroy .top }
}


# Font Selecter -- Change font of the Axis Labels and Keys
#
# Argument     : Path of Top Frame and Object
# Return Value : None
#
proc font_select {w obj} {
    if {[winfo exist .top2]} {return}

    global font fontFamily fontSize fontSlant fontWeight
    global tmpFontAxis tmpFontAngle tmpFontNote
    global family weight slant pixel width style slanttype wait_var2
    global tmpfamily tmpweight tmpslant tmppixel tmpwidth tmpstyle tmpslanttype

    toplevel .top2 ;  wm group .top2 $w ; grab set .top2
    wm title .top2 "Change Font of [string toupper $obj]"

    set wait_var2     ""
    set target(note)  "Notes"
    set target(axis)  "Axis Digit and Title"
    set target(angle) "Angle Digit and Title"
    set sampletext    "abcdefghijklmn\nABCDEFG 012345"
    set slanttype     "r i"

    if {$obj == "axis"} {
	set tmpFont $tmpFontAxis
    } elseif {$obj == "angle"} {
	set tmpFont $tmpFontAngle
    } else {
	set tmpFont $tmpFontNote
    }

    set family [lindex [split $tmpFont "-"] 2]
    set weight [lindex [split $tmpFont "-"] 3]
    set slant  [lindex [split $tmpFont "-"] 4]
    set pixel  [expr int(double([lindex [split $tmpFont "-"] 8])/10.0)]
    set width  "normal"
    set style  [expr {$slant == "r" ? "roman" : "italic"}]

    set tmpfamily $family ; set tmpfamily $family ; set tmpweight $weight 
    set tmpslant  $slant  ; set tmppixel  $pixel  ; set tmpwidth  $width  
    set tmpstyle  $style  

    # Frames
    frame .top2.left     -bd 3 -relief ridge
    frame .top2.center   -bd 3 -relief ridge
    frame .top2.right    -bd 3 -relief ridge
    frame .top2.bottom   -relief groove -bd 5
    frame .top2.middle   -relief groove -bd 5
    frame .top2.leftU    ; frame .top2.leftL   
    frame .top2.centerU  ; frame .top2.centerUS
    frame .top2.centerL  ; frame .top2.centerLS
    frame .top2.rightU   ; frame .top2.rightL  

    # Labels
    label .top2.family -text "Family" -font $font(2)
    label .top2.style  -text "Style"  -font $font(2)
    label .top2.weight -text "Weight" -font $font(2)
    label .top2.size   -text "Size"   -font $font(2)
    label .top2.selected -font $font(1) -anchor w -relief sunken -bd 2\
	    -text "Selected  : $family-$weight-$style-$pixel"
    label .top2.selecting -font $font(1) -anchor w -relief sunken -bd 2\
	    -text "Selecting : $family-$weight-$style-$pixel"

    # Listboxes
    listbox .top2.familylist -selectmode single -height 6 -width 12 -bd 3\
	    -font $font(3) -yscrollcommand ".top2.familybar set"
    listbox .top2.weightlist -height 2 -selectmode single -width 12 -bd 3 \
	    -font $font(3) -yscrollcommand ".top2.weightbar set"
    listbox .top2.stylelist -height 2 -selectmode single  -width 12 -bd 3 \
	    -font $font(3) -yscrollcommand ".top2.stylebar set"
    listbox .top2.sizelist -height 6 -selectmode single   -width 2  -bd 3 \
	    -font $font(3) -yscrollcommand ".top2.sizebar set"

    # Scrollbars
    scrollbar .top2.familybar -orient vertical -bd 2 \
	    -command ".top2.familylist yview"
    scrollbar .top2.weightbar -orient vertical -bd 2 \
	    -command ".top2.weightlist yview" 
    scrollbar .top2.stylebar  -orient vertical -bd 2 \
	    -command ".top2.stylelist yview"
    scrollbar .top2.sizebar   -orient vertical -bd 2 \
	    -command ".top2.sizelist yview"

    # Canvas for sample text and creating sample text
    canvas .top2.sample -width 260 -height 70 -bg gray -relief ridge -bd 5
    .top2.sample create text 20 40 -text $sampletext \
	    -font -*-$family-$weight-$slant-$width--*-[expr $pixel*10]-*-*-*-*-*-* \
	    -fill black -anchor w -tags sample

    # Buttons
    button .top2.ok -text "Okay" -font $font(4) -width 8 -height 1 -bd 3\
	    -activeforeground blue -command {set wait_var2 1}
    button .top2.cancel -text "Cancel" -font $font(4) -width 8 -height 1 \
	    -bd 3 -activeforeground red -command {set wait_var2 0}

    # Packing Widgets
    # Left
    pack .top2.family -side top -in .top2.leftU -fill x
    pack .top2.familylist .top2.familybar -side left -in .top2.leftL -fill y 
    pack .top2.leftU .top2.leftL -in .top2.left -side top -fill y -expand true

    # Center
    pack .top2.weight -side top -in .top2.centerU 
    pack .top2.weightlist .top2.weightbar -side left -in .top2.centerUS \
	    -fill y
    pack .top2.style  -side top -in .top2.centerL -fill y -anchor c
    pack .top2.stylelist .top2.stylebar -side left -in .top2.centerLS -fill y
    pack .top2.centerU .top2.centerUS .top2.centerL .top2.centerLS \
	    -side top -in .top2.center -fill y -expand true

    # Right
    pack .top2.size -side top -in .top2.rightU -fill x
    pack .top2.sizelist .top2.sizebar -side left -in .top2.rightL -fill y
    pack .top2.rightU .top2.rightL -in .top2.right -side top -fill y \
	    -expand true

    pack .top2.left .top2.center .top2.right -in .top2.middle -side left \
	    -fill both -expand true

    # Bottom
    pack .top2.sample -side left -in .top2.bottom 
    pack .top2.ok .top2.cancel -side top -in .top2.bottom -fill y -expand yes

    # All Packing
    pack .top2.middle .top2.selected .top2.selecting .top2.bottom \
	    -padx 2 -side top -expand true -fill both
    
    # Family, Size, Slant, and Weight Lists
    foreach i $fontFamily { .top2.familylist insert end $i }
    foreach i $fontSize   { .top2.sizelist   insert end $i }
    foreach i $fontSlant  { .top2.stylelist  insert end $i }
    foreach i $fontWeight { .top2.weightlist insert end $i }

    # Binding
    # Changing of Family, Size, Weight, Slant
    bind .top2.familylist <ButtonRelease-1> {
	set number [.top2.familylist curselection]
	set tmpfamily [.top2.familylist get $number] ; change_sample 
    }
    bind .top2.sizelist <ButtonRelease-1> {
	set number [.top2.sizelist curselection]
	set tmppixel  [.top2.sizelist get $number]   ; change_sample 
    }
    bind .top2.weightlist <ButtonRelease-1> {
	set number [.top2.weightlist curselection]
	set tmpweight  [.top2.weightlist get $number] ; change_sample
    }
    bind .top2.stylelist <ButtonRelease-1> {
	set number [.top2.stylelist curselection]
	set tmpslant  [lrange $slanttype $number $number] ; change_sample
    }
    
    # procedure for changing sample text font
    proc change_sample {} {
	global family weight slant width pixel style
	global tmpfamily tmpweight tmpslant tmpwidth tmppixel tmpstyle
	
	set tmpstyle [expr {$tmpslant == "r" ? "roman" : "italic"}]
	set result_sample [catch {.top2.sample itemconfigure sample \
		-fill black -tag sample -font -*-$tmpfamily-$tmpweight-$tmpslant-$tmpwidth--*-[expr $tmppixel*10]-*-*-*-*-*-* } tst_msg]

	if {$result_sample == 0} {
	    set family $tmpfamily ; set weight $tmpweight 
	    set slant  $tmpslant  ; set width  $tmpwidth
	    set pixel  $tmppixel  ; set style  $tmpstyle
	    .top2.selecting configure -text \
		    "Selecting : $family-$weight-$style-$pixel"
	} else {
	    tk_messageBox -icon error -type ok -title "Sorry..." -message \
		    "Your system \n doesn't have the font : \"$tmpfamily-$tmpweight-$tmpstyle-$tmppixel\"" -default ok
	    set tmpfamily $family ; set tmpweight $weight 
	    set tmpslant  $slant  ; set tmpwidth  $width
	    set tmppixel  $pixel  ; set tmpstyle  $style
	}
    }

    tkwait variable wait_var2

    if {[winfo exist .top2]} { destroy .top2 } ; grab release .top2
    if {$wait_var2 == 1} {
	return "-*-$family-$weight-$slant-$width--*-[expr $pixel*10]-*-*-*-*-*-*"
    } else { return $tmpFont}
}


# change_fonts -- Change Fonts
#
# Argument     : Path of Top Frame
# Return Value : None
#
proc change_fonts {w} {
    global font nowX nowY isKey fontAxis fontAngle fontNote
    global tmpFontAxis tmpFontAngle tmpFontNote wait_var

    if {[winfo exist .top]} {return}

    toplevel .top ; wm group .top $w
    wm title .top "Change Fonts" ; grab set .top

    set tmpFontAxis $fontAxis ; set tmpFontAngle $fontAngle
    set tmpFontNote $fontNote ; set wait_var ""

    frame .top.axis  ; frame .top.angle ; frame .top.note  
    frame .top.buttons -relief groove -bd 3
    frame .top.axisF   -relief groove -bd 3
    frame .top.angleF  -relief groove -bd 3
    frame .top.noteF   -relief groove -bd 3

    label .top.axisText  -text "Axis Label"  -font $font(2) -width 15 -anchor w
    label .top.angleText -text "Angle Label" -font $font(2) -width 15 -anchor w
    label .top.noteText  -text "Notes" -font $font(2) -width 15 -anchor w

    canvas .top.axisFont  -bg white -height 45 -width 200 -bd 5 -relief groove
    canvas .top.angleFont -bg white -height 45 -width 200 -bd 5 -relief groove
    canvas .top.noteFont  -bg white -height 45 -width 200 -bd 5 -relief groove

    .top.axisFont  create text 20 30 -text "abcABC1234567" -tag axisfonts \
	    -anchor w -font $fontAxis
    .top.angleFont create text 20 30 -text "abcABC1234567" -tag anglefonts \
	    -anchor w -font $fontAngle
    .top.noteFont  create text 20 30 -text "abcABC1234567" -tag notefonts \
	    -anchor w -font $fontNote

    button .top.changeAxis -text "Change" -font $font(1) -width 7\
	    -activeforeground royalblue \
	    -command {set tmpFontAxis [font_select .top "axis"] ; \
	    .top.axisFont itemconfigure axisfonts -font $tmpFontAxis }
    button .top.changeAngle -text "Change" -font $font(1) -width 7 \
	    -activeforeground royalblue \
	    -command {set tmpFontAngle [font_select .top "angle"] ; \
	    .top.angleFont itemconfigure anglefonts -font $tmpFontAngle }
    button .top.changeNote -text "Change" -font $font(1) -width 7\
	    -activeforeground royalblue \
	    -command {set tmpFontNote [font_select .top "note"] ; \
	    .top.noteFont itemconfigure notefonts -font $tmpFontNote }
    button .top.ok -text "Okay" -font $font(4) -activeforeground blue \
	    -width 7 -bd 3 -command {set wait_var 1}
    button .top.cancel -text "Cancel" -font $font(4) -activeforeground red \
	    -width 7 -bd 3 -command { set wait_var 0 }

    pack .top.axisText -side left -in .top.axisF
    pack .top.changeAxis -side right -in .top.axisF
    pack .top.angleText  -side left -in .top.angleF
    pack .top.changeAngle -side right -in .top.angleF
    pack .top.noteText -side left -in .top.noteF
    pack .top.changeNote -side right -in .top.noteF

    pack .top.axisF .top.axisFont -side top -in .top.axis -fill x
    pack .top.angleF .top.angleFont -side top -in .top.angle -fill x
    pack .top.noteF .top.noteFont -side top -in .top.note -fill x
    pack .top.ok .top.cancel -side left -in .top.buttons -expand true -fill x

    pack .top.axis .top.angle .top.note .top.buttons -side top -fill x

    tkwait variable wait_var

    if {$wait_var == 1} {
	if {$fontAxis != $tmpFontAxis} {
	    set fontAxis $tmpFontAxis
	    .canvas itemconfigure axisT -font $fontAxis
	    for {set i 0} {$i < 20} {incr i} {
		.canvas itemconfigure Axis($i) -font $fontAxis
	    }
	}
	if {$fontAngle != $tmpFontAngle} {
	    set fontAngle $tmpFontAngle
	    .canvas itemconfigure angleAxis  -font $fontAngle
	    .canvas itemconfigure angleAxisT -font $fontAngle
	}
	if {$fontNote != $tmpFontNote} {
	    set fontNote $tmpFontNote
	    if {$isKey != ""} {
		set isKey "" ; drawNotes $nowX $nowY
	    }
	}
    }

    if {[winfo exist .top]} { destroy .top } ; grab release .top
}


# about_drawp -- Display the Information of DrawP current version
# 
# Argument      : Top Path
# Return Value  : None
# Modified Date : 30 Jan. 1997
#
proc about_drawp {w} {
    if {[winfo exist .top]} { return }

    global font version
    toplevel .top ; wm group .top $w
    wm title .top "DrawP Information" ; grab set .top

    frame .top.frame
    set e_mail     "hueda@kamome.or.jp"
    set copyright  "Copyright (C) 1997 UEDA Hiroyuki."
    set copyright2 "All Rights Reserved."
    set fontI      *-Times-Bold-I-Normal--24-*-*-*-*-*-*-*
    set fontI2     *-Times-Medium-I-Normal--20-*-*-*-*-*-*-* \

    button .top.ok -text "Okay" -activeforeground blue -bd 3 -font $font(4) \
	    -width 5 -command {destroy .top; grab release .top}
    canvas .top.about -width 300 -height 180 -bd 10 -relief groove

    .top.about create text 151 32 -text "DrawP ver. $version" \
	    -fill white -font $fontI
    .top.about create text 150 30 -text "DrawP ver. $version" \
	    -fill midnightblue -font $fontI
    .top.about create text 200 60 -text "- for Unix/X11 -" \
	    -fill red -font $fontI2 -tags version
    .top.about create text 30 100 -fill black -font $font(2)\
	    -anchor w -text $copyright
    .top.about create text 77 130 -fill black -font $font(2) \
	    -anchor w -text $copyright2
    .top.about create text 77 175 -fill white -font $font(2) \
	    -anchor w -text $e_mail
    .top.about create text 75 173 -fill midnightblue -font $font(2) \
	    -anchor w -text $e_mail
    
    pack .top.about .top.ok -side top -in .top -anchor e
}


# get_filename -- Select File and Set Filename to the Variables
#
# Argument     : TYPE (READ / OutTGIF / outPS / outConv)
# Return Value : File Name
# Create Date  : 31 Jan. 1997
#
proc get_filename { TYPE } {
    global curDir curDirC readtypes tgiftypes pstypes outPS outTgif outConv ext
    global tmpRead

    if {$TYPE == "READ"} {
	set tmpname [tk_getOpenFile -title "Read File" -filetypes $readtypes]
	if {$tmpname == ""} { return ""}
    } else {
	if {$TYPE == "OutTGIF"} {
	    set tmpname [tk_getSaveFile -title "Save File" \
		    -initialfile $outTgif -filetypes $tgiftypes]
	} elseif {$TYPE == "OutPS"}  {
	    set tmpname [tk_getSaveFile -title "Save File" \
		    -initialfile $outPS -filetypes $pstypes]
	} else {
	    set tmpname [tk_getSaveFile -title "Save File" \
		    -initialfile "[file rootname $tmpRead].$ext"\
		    -filetypes $readtypes]
	}
	if {$tmpname == ""} {
	    if {$TYPE == "OutTGIF"} {
		return $outTgif
	    } elseif {$TYPE == "OutPS"} {
		return $outPS
	    } else {
		return [file rootname $tmpRead].$ext
	    }
	}
    }

    if {$TYPE == "READ"} {
	if {[file isfile $tmpname]} {
	    set curDir [file dirname $tmpname]
	    cd $curDir ; return [file tail $tmpname]
	} elseif {[file isdirectory $tmpname]} {
	    set curDir $tmpname ; cd $curDir ; return ""
	}
    } else {
	if {[file isdirectory $tmpname]} {
	    if {$TYPE == "OutTGIF"} { 
		set curDir $tmpname ; cd $curDir ; return $outTgif
	    } elseif {$TYPE == "OutPS"} {
		set curDir $tmpname ; cd $curDir ; return $outPS
	    } else {
		set curDirC $tmpname ; cd $curDirC
		return [file rootname $tmpRead].$ext
	    }
	} else {
	    if {$TYPE != "CONV"} {
		set curDir [file dirname $tmpname]
		cd $curDir ; return [file tail $tmpname]
	    } else {
		set curDirC [file dirname $tmpname]
		cd $curDirC ; return [file tail $tmpname]
	    }
	}
    }
}


# zip_dirName -- Zip Directory Name for diplay
#
# Argument     : Widget Path and Directory Name
# Return Value : None 
# Create Date  : 31 Jan. 1997
#
proc zip_dirName {w dirname} {
    if {[string length $dirname] < 21} {
	$w conf -text $dirname 
    } else {
	$w conf -text "   .../[file tail $dirname]"
    }
}


# file_result -- Check Result of Reading/Wrinting File 
#
# Argument     : Result Number and Whether execute case of "0"
# Return Value : None
# Create Date  : 31 Jan. 1997
#
proc file_result {result_num is0} {
    global file tmpRead

    if {$is0 == "YES"} {
	if {$result_num == 0} {
	    tk_messageBox -icon info -title "Success Information" -type ok\
		    -default ok -message "Finish reading the File" ; return
	}
    } else {
	if {$result_num == 0} {
	    return
	}
    }

    switch $result_num {
	1 { set message "Data Format is incorrect" }
	2 { set message "File has no Valid Data" }
	3 { set message "The Number of Angle or Value Row is incorrect" }
	4 { set message "Data Format is not HP-IB" }
	5 { set message "Cannot Read File"   }
	6 { set message "Cannot Write File"  }
	default {set message "Unknown Error. Please contact the Author of \
		this program!" }
    }
    file_error $message
}


# file_error -- Display Error Message of Reading File
#
# Argument      : Reason of Error
# Return Value  : None
# Modified Date : 31 Jan. 1997
#
proc file_error text { 
    set result [tk_messageBox -icon error -type ok -title "File Error" \
	    -message $text -default ok ]
}


# normalizer -- Normalizing the read Data
#
# Arguments    : Data Number, Normalizing Type(or Data Number)
#                    and Max Value
# Return Value : None
#
proc normalizer {dataNum type maxValue} {
    global angle value normOK

    set tmpMax -9.9e99 ; set j 0
    if {$type != "ARB"} {
	while {$angle($type,$j) != "END"} {
	    if {$tmpMax < $value($type,$j)} { set tmpMax $value($type,$j) }
	    incr j
	}
	set maxValue $tmpMax
    }

    set j 0
    while {$angle($dataNum,$j) != "END"} {
	set value($dataNum,$j) [expr $value($dataNum,$j) - $maxValue] ; incr j
    }
    if {$dataNum > 0} {set normOK($dataNum) 1}
}


# really_quit -- Quit Procedure with confirmation
#
# Arugument    : None
# Return Value : None(exit)
#
proc really_quit {} {
    set result [tk_messageBox -icon question -type okcancel -default ok \
	    -title "Really Quit ?" -message "Do you really quit ?" ]
    if {$result == "ok"} {exit} ; return 
}


# change_Notes -- Change Notes Frame and Order
#
# Arguments    : Top Path
# Return Value : None
proc change_Notes {w} {
    if {[winfo exist .top]} { return }

    global font frameType orderType isKey nowX nowY 
    global tmpFrame tmpOrder tmpKeyColors keyColors wait_var
    toplevel .top; wm group .top $w
    wm title .top "Change Notes" ; grab set .top

    set wait_var "" ; set tmpFrame $frameType ; set tmpOrder $orderType
    set tmpKeyColors $keyColors

    proc sample_draw {frame order} {
	global font tmpKeyColors
	.top.sample.c delete sample sampleT1 sampleT2 sampleT3 sampleT4

	# Set the text colors
	if {$tmpKeyColors == "Black"} {
	    for {set i 1} {$i < 5} {incr i} {
		set keyColor($i) black
	    }
	} else {
	    set keyColor(1) black ; set keyColor(2) red
	    set keyColor(3) blue  ; set keyColor(4) green
	}

	# Frame
	if {$frame != 3} {
	    if {$order == 1} {
		if {$frame == 1} {
		    .top.sample.c create rectangle 145 35 320 145 \
			    -fill black -tags sample
		}
		.top.sample.c create rectangle 140 30 315 140 \
			-fill white -tags sample
	    } elseif {$order == 2} {
		if {$frame == 1} {
		    .top.sample.c create rectangle 55 65 455 95 \
			    -fill black -tags sample
		}
		.top.sample.c create rectangle 50 60 450 90 \
			-fill white -tags sample
	    } else {
		if {$frame == 1} {
		    .top.sample.c create rectangle 135 45 405 110 \
			    -fill black -tags sample
		}
		.top.sample.c create rectangle 130 40 400 105 \
			-fill white -tags sample
	    }
	}

	# Order
	if {$order == 1} {
	    .top.sample.c create line 150 50 230 50 -width 2 \
		    -fill black -tags sample
	    .top.sample.c create line 150 75 230 75 -width 2 \
		    -fill red -tags sample
	    .top.sample.c create line 150 100 230 100 -width 2 \
		    -fill blue -tags sample
	    .top.sample.c create line 150 125 230 125 -width 2 \
		     -fill green -tags sample

	    for {set i 1} {$i < 5} {incr i} {
		.top.sample.c create text 240 [expr 50+($i-1)*25] \
			-text "Data $i" -font $font(2) -fill $keyColor($i) \
			-anchor w -tags sampleT$i
	    }
	} elseif {$order == 2} {
	    .top.sample.c create line 60 75 110 75 -width 2 \
		    -fill black -tags sample
	    .top.sample.c create line 190 75 240 75 -width 2 \
		    -fill red -tags sample
	    .top.sample.c create line 320 75 370 75 -width 2 \
		    -fill blue -tags sample

	    for {set i 1} {$i < 4} {incr i} {
		.top.sample.c create text [expr 120+($i-1)*130] 75 \
			-text "Data $i" -font $font(2) \
			-fill $keyColor($i) -anchor w -tags sampleT$i
	    }
	} else {
	    .top.sample.c create line 140 60 190 60 -width 2 \
		    -fill black -tags sample 
	    .top.sample.c create line 270 60 320 60 -width 2 \
		    -fill red -tags sample
	    .top.sample.c create line 140 85 190 85 -width 2 \
		    -fill blue -tags sample
	    .top.sample.c create line 270 85 320 85 -width 2 \
		    -fill green -tags sample

	    for {set i 1} {$i < 3} {incr i} {
		.top.sample.c create text 200 [expr 60+($i-1)*25] \
			-text "Data [expr ($i-1)*2+1]" \
			-font $font(2) -fill $keyColor([expr ($i-1)*2+1]) \
			-anchor w \
			-tags sampleT[expr ($i-1)*2+1]
		.top.sample.c create text 330 [expr 60+($i-1)*25] \
			-text "Data [expr $i*2]" \
			-font $font(2) -fill $keyColor([expr $i*2]) \
			-anchor w \
			-tags sampleT[expr $i*2]
	    }
	}
    }

    frame .top.top
    frame .top.frame  -bd 3 ; frame .top.order -bd 3
    frame .top.sample -bd 3 -relief groove
    frame .top.bottom -bd 3
    frame .top.bottom.text -bd 2 -relief groove
    
    # Frame Type
    label .top.frame.text -text "Frame Type" -font $font(2)

    for {set i 1} {$i < 4} {incr i} {
	radiobutton .top.frame.r$i -text "Type $i" -font $font(1) -bd 2\
		-activeforeground blue -variable tmpFrame -value $i \
		-command {sample_draw $tmpFrame $tmpOrder}
    }

    pack .top.frame.text -side top
    pack .top.frame.r1 .top.frame.r2 .top.frame.r3 -side left

    # Order Type
    label .top.order.text -text "Arrange Type" -font $font(2)

    set rom(1) "I" ; set rom(2) "II" ; set rom(3) "III"
    for {set i 1} {$i < 4} {incr i} {
	radiobutton .top.order.r$i -text "Type $rom($i)" -font $font(1) -bd 2\
		-activeforeground red -variable tmpOrder -value $i \
		-command {sample_draw $tmpFrame $tmpOrder}
    }

    pack .top.order.text -side top
    pack .top.order.r1 .top.order.r2 .top.order.r3 -side left

    # Sample 
    canvas .top.sample.c -height 150 -width 480 -bg white -bd 4 \
	    -relief sunken
    pack .top.sample.c

    # Bottom
    label  .top.bottom.text.textColor -text "Text Color" -font $font(2) \
	    -width 12
    if {$tmpKeyColors == "Black"} {
	set colorText Color
    } else {
	set colorText Black
    }

    button .top.bottom.text.color -text $colorText  -font $font(2) \
	    -relief raised -width 12 -command { 
	if {$tmpKeyColors == "Black"} {
	    .top.bottom.text.color configure -text "Black" 
	    set tmpKeyColors Color
	} else {
	    .top.bottom.text.color configure -text "Color" 
	    set tmpKeyColors Black
	}
	sample_draw $tmpFrame $tmpOrder
    }
    button .top.bottom.ok -text "Okay" -font $font(4) -activeforeground blue \
	    -command {set wait_var 1} -width 7 -bd 3
    button .top.bottom.cancel -text "Cancel" -font $font(4) \
	    -activeforeground red -command {set wait_var 0} -width 7 -bd 3

    pack .top.bottom.text.textColor .top.bottom.text.color -side top
    pack .top.bottom.text .top.bottom.ok .top.bottom.cancel -side left \
	    -fill x -expand yes -anchor s
    pack .top.frame .top.order -side left -in .top.top
    pack .top.top .top.sample .top.bottom -side top -fill x

    sample_draw $tmpFrame $tmpOrder

    tkwait variable wait_var

    if {$wait_var == 1} {
	set frameType $tmpFrame ; set orderType $tmpOrder
	set keyColors $tmpKeyColors

	if {$isKey != ""} { set isKey "" ; drawNotes $nowX $nowY } 
    }

    if {[winfo exist .top]} { destroy .top } ; grab release .top
}


# printCanvas -- Printing the Figures on the Canvas 
#
# Argument      : Path of Top
# Return Value  : None
# Modified Date : 31 Jan. 1997
#
proc printCanvas {w} {
    global font env sizeCanvas sizeCanvasX sizeCanvasY graphForm
    global printerName outputSize wait_var

    if {[winfo exist .top]} { return }

    toplevel .top -relief groove -bd 3
    wm group .top $w ; wm title .top "Print Graph" ; grab set .top

    set wait_var "" ; set outputSize  1.0

    frame .top.1 -bd 3 ; frame .top.2 -bd 3 ; frame .top.3 -bd 3

    # Printer Name
    label .top.1.name -text "Printer:" -font $font(2) -width 8 -anchor w 
    entry .top.1.printer -font $font(2) -width 10 -relief sunken \
	    -bd 5 -textvariable printerName
    pack .top.1.name .top.1.printer -side left

    # Output Size
    label .top.2.text -text "Size :" -font $font(2) -width 8 -anchor w
    entry .top.2.size -font $font(2) -width 5 -relief sunken -bd 5 \
	    -textvariable outputSize
    label .top.2.times -text "times" -font $font(2) -width 5 -anchor e
    pack .top.2.text .top.2.size .top.2.times -side left

    # Buttons
    button .top.3.ok -text "Print" -font $font(4) -activeforeground blue \
	    -bd 3 -width 7 -command {set wait_var 1}
    button .top.3.close -text "Close" -font $font(4) \
	    -activeforeground red  -bd 3 -width 7  -command {set wait_var 0}

    pack .top.3.ok .top.3.close -side left -fill x -expand yes
    pack .top.1 .top.2 .top.3 -side top -fill x -expand yes

    # Binding
    bind .top.1.printer <Return> {focus .top.2.size}
    bind .top.2.size <Return> {
	if {[catch {expr double($outputSize)}] == 0} {
	    focus .top.3.ok; .top.3.ok configure -state active
	} else { set outputSize 1.0 }
    }
    bind .top.2.size <Leave> {
	if {[catch {expr double($outputSize)}] == 0} {
	    focus .top.3.ok; .top.3.ok configure -state active
	} else { set outputSize 1.0 ; focus .top.3.ok }
    }

    # Check Default Printer Name
    if {[catch {set printerName $env(PRINTER)}] != 0} {
	set printerName "Unknown" ; .top.1.printer conf -fg red
    }

    # Waiting for the change of value wait_var
    tkwait variable wait_var

    if {$wait_var == 1} {
	# Printout
	if {$graphForm == "full"} {
	    set printSizeX [expr $sizeCanvas * $outputSize]
	    set printSizeY $printSizeX
	} else {
	    set printSizeX [expr $sizeCanvasX * $outputSize]
	    set printSizeY [expr $sizeCanvasY * $outputSize]
	}

	# Printing
	set f_prn [open "|lpr -P$printerName" w]
	puts $f_prn [.canvas postscrip -pagewidth $printSizeX \
		-pageheight $printSizeY -colormode color] ; close $f_prn

    tk_messageBox -title "Success Information" -type ok -default ok \
	    -message "The Graph is sent to the Printer" -icon info
    }


    # Final Process
    if {[winfo exist .top]} { destroy .top } ; grab release .top; return 
}


# tgif_output -- Output Tgif Object File
#
# Arguments    : Top Path Help title
# Return Value : None
#
proc tgif_output {TGIFfile} {
    global stepAxis1 stepAxis2 stepScale stepAngle isAngleLine isSubCircle
    global startValue endValue startAngle endAngle graphForm axisLabel 
    global dataOK isDraw Key isKey outTgif
    global angle value isDraw lineColor lineWidth deg2rad

    if {[file exists $TGIFfile]} {
	set result [tk_messageBox -icon warning -type okcancel \
                -default cancel -title "The file exists" \
                -message "Overwrite $TGIFfile?"]
        if {$result == "cancel" } {
	    return
	} else {
	    if {![file writable $TGIFfile]} {
		tk_messageBox -icon error -type ok -default ok \
			-title "Output Error" \
			-message "You cannot write $TGIFfile. \
			Check Directory or File Mode"
		return
	    }
	}
    }    


    # Postions
    set centerX 544; set centerY 640
    set X0 394 ; set Y0 490 ; set XM 694 ; set YM 790

    set out_fd [open $TGIFfile w]
    set stepMain [expr int(double($startValue-$endValue)/$stepAxis1)]
    set stepSub  [expr int(double($stepAxis1)/$stepAxis2)]

    if {$graphForm == "full"} {
	set centerX 544; set centerY 640 ; set offangle 90
	set X0 394 ; set Y0 490 ; set XM 694 ; set YM 790
    } else {
	set centerX 544; set centerY 640 ; set offangle 180
	set X0 344 ; set Y0 440 ; set XM 744 ; set YM 840
    }
    set radius [expr $XM-$centerX]

    # Header Part
    puts $out_fd "%TGIF 3.0-p5"
    puts $out_fd "state(0,33,100,384,480,1,16,0,9,1,1,0,0,1,0,1,0,'Helvetica',0,34,0,0,0,10,0,1,1,1,0,16,0,0,1,1,1,0,1088,1408,0,0,2880)."
    puts $out_fd "%\n% @(#)\$Header\$\n% %W%\n%\n%"
    puts $out_fd "%\tGenerated by DrawP ver 2.0, (C) 1996 UEDA Hiroyuki.\n%"
    puts $out_fd "unit(\"1 pixel/pixel\")."
    puts $out_fd "page(1,\"\",1)."

    # Drawing Full Circle or Semi Circle Graph 
    if {$graphForm == "full"} {
	# Most outside Circle
	puts $out_fd "oval('black',$X0,$Y0,$XM,$YM,0,2,1,22,0,0,0,0,0,'1',\["
	puts $out_fd "\])."

	# Base Lines
	puts $out_fd "poly('black',2,\["
	puts $out_fd "\t\t$centerX,$Y0,$centerX,$YM,\],0,1,1,25,0,0,0,0,8,3,0,0,0,'1','8','3',)"
	puts $out_fd "\"0\",\[" ; puts $out_fd "\])."
	puts $out_fd "poly('black',2,\["
	puts $out_fd "\t\t$X0,$centerY,$XM,$centerY,\],0,1,1,25,0,0,0,0,8,3,0,0,0,'1','8','3',)"
	puts $out_fd "\"0\",\[" ;  puts $out_fd "\])."

	# Angle Base Lines
	if {$isAngleLine == "YES"} {
	    set tmp [expr int(180.0/$stepAngle)]
	    set angleStep [expr $stepAngle*$deg2rad]
	    for {set i 1} {$i < $tmp} {incr i} {
		if {[expr int($stepAngle*$i)%90] == 0} { continue } 
		set sublineX  [expr $centerX + $radius*cos($angleStep*$i)]
		set sublineY  [expr $centerY + $radius*sin($angleStep*$i)]
		set sublineX2 [expr $centerX - $radius*cos($angleStep*$i)]
		set sublineY2 [expr $centerY - $radius*sin($angleStep*$i)]
		puts $out_fd "poly('gray',2,\["
		puts $out_fd "\t\t$sublineX,$sublineY,$sublineX2,$sublineY2,\],0,1,1,25,0,0,0,0,8,3,0,0,0,'1','8','3',)"
		puts $out_fd "\"0\",\[" ; puts $out_fd "\])."
	    }
	}

	# Main Circles
	for {set i 0} {$i < $stepMain} {incr i} {
	    set tmpStep [expr double($i)/$stepMain]
	    set Xs [expr int(double($radius)*$tmpStep+$X0)]
	    set Ys [expr int(double($radius)*$tmpStep+$Y0)]
	    set Xe [expr int($XM-double($radius)*$tmpStep)]
	    set Ye [expr int($YM-double($radius)*$tmpStep)]
	    puts $out_fd "oval('black',$Xs,$Ys,$Xe,$Ye,0,1,1,22,0,0,0,0,0,'1',\["
	    puts $out_fd "\])."
	}

	# Sub Circles
	if {$isSubCircle == "YES"} {
	    set disMain [expr int(double($radius)/$stepMain)]
	    set disSub [expr int(double($disMain)/$stepSub)]
	    for {set i 0} {$i < $stepMain} {incr i} {
		set tmpStep [expr double($i)/$stepMain]
		set Xsm [expr int(double($radius)*$tmpStep+$X0)]
		set Ysm [expr int(double($radius)*$tmpStep+$Y0)]
		set Xem [expr int($XM-double($radius)*$tmpStep)]
		set Yem [expr int($YM-double($radius)*$tmpStep)]
		for {set j 1} {$j < $stepSub} {incr j} {
		    set Xs [expr int($disSub*$j+$Xsm)]
		    set Ys [expr int($disSub*$j+$Ysm)]
		    set Xe [expr $Xem - int($disSub*$j)]
		    set Ye [expr $Yem - int($disSub*$j)]
		    puts $out_fd "oval('black',$Xs,$Ys,$Xe,$Ye,0,1,1,22,1,0,0,0,0,'1',\["
		    puts $out_fd "\])."
		}
	    }
	}

    } else {
	#
	# Semi Circle
	#
	# Postions
	set diameter [expr int($centerX-$X0)*2]

	# Most Outside Arc
	puts $out_fd "arc('black',0,2,1,0,$X0,$Y0,$centerX,$centerY,$X0,$centerY,$XM,$centerY,0,$diameter,$diameter,0,11520,0,22,0,1,8,0,0,0,0,'1','8',\["
	puts $out_fd "\])."

	# Main Arc
	for {set i 1} {$i < $stepMain} {incr i} {
	    set tmpStep [expr double($i)/$stepMain]
	    set Xs [expr int(double($radius)*$tmpStep+$X0)]
	    set Ys [expr int(double($radius)*$tmpStep+$Y0)]
	    set Xe [expr int($XM-double($radius)*$tmpStep)]
	    set Ye [expr int($YM-double($radius)*$tmpStep)]
	    set tmpdia [expr abs($Xs-$centerX)*2]
	    puts $out_fd "arc('black',0,1,1,0,$Xs,$Ys,$centerX,$centerY,$Xs,$centerY,$Xe,$centerY,0,$tmpdia,$tmpdia,0,11520,0,22,0,1,8,0,0,0,0,'1','8',\["
	    puts $out_fd "\])."
	}

	# Base Lines
	puts $out_fd "poly('black',2,\["
	puts $out_fd "\t\t$centerX,$Y0,$centerX,$centerY,\],0,1,1,25,0,0,0,0,8,3,0,0,0,'1','8','3',)"
	puts $out_fd "\"0\",\[" ; puts $out_fd "\])."
	puts $out_fd "poly('black',2,\["
	puts $out_fd "\t\t$X0,$centerY,$XM,$centerY,\],0,1,1,25,0,0,0,0,8,3,0,0,0,'1','8','3',)"
	puts $out_fd "\"0\",\[" ;  puts $out_fd "\])."

	# Sub Arc
	if {$isSubCircle == "YES"} {
	    set disMain [expr int(double($radius)/$stepMain)]
	    set disSub [expr int(double($disMain)/$stepSub)]
	    for {set i 0} {$i < $stepMain} {incr i} {
		set Xsm [expr int(double($radius)/$stepMain*$i+$X0)]
		set Ysm [expr int(double($radius)/$stepMain*$i+$Y0)]
		set Xem [expr int($XM-double($radius)/$stepMain*$i)]
		set Yem [expr int($YM-double($radius)/$stepMain*$i)]
		for {set j 1} {$j < $stepSub} {incr j} {
		    set Xs [expr int($disSub*$j+$Xsm)]
		    set Ys [expr int($disSub*$j+$Ysm)]
		    set Xe [expr $Xem - int($disSub*$j)]
		    set Ye [expr $Yem - int($disSub*$j)]
		    set tmpdia [expr abs($Xs-$centerX)*2]
		    puts $out_fd "arc('black',0,1,1,1,$Xs,$Ys,$centerX,$centerY,$Xs,$centerY,$Xe,$centerY,0,$tmpdia,$tmpdia,0,11520,0,22,0,1,8,0,0,0,0,'1','8',\["
		    puts $out_fd "\])."
		}
	    }
	}

	# Angle Base Lines
	if {$isAngleLine == "YES"} {
	    set tmp [expr int(180.0/$stepAngle)]
	    set angleStep [expr $stepAngle*$deg2rad]
	    for {set i 1} {$i < $tmp} {incr i} {
		if {[expr int($stepAngle*$i)%90] == 0} { continue } 
		set sublineX  [expr $centerX - $radius*cos($angleStep*$i)]
		set sublineY  [expr $centerY - $radius*sin($angleStep*$i)]
		puts $out_fd "poly('gray',2,\["
		puts $out_fd "\t\t$sublineX,$sublineY,$centerX,$centerY,\],0,1,1,25,0,0,0,0,8,3,0,0,0,'1','8','3',)"
		puts $out_fd "\"0\",\[" ; puts $out_fd "\])."
	    }
	}
    }

    # Common Object Output
    # Notes
    if {$isKey != ""} {
	set j 0
	for {set i 1} {$i < 5} {incr i} {
	    if {$isDraw($i) == 1 && $dataOK($i) == "OK"} {
		puts $out_fd "text('$lineColor($i)',[expr $XM+50],[expr $Y0+$j*30-15],'Helvetica',0,20,1,0,0,1,31,22,43,0,18,4,2,0,0,0,0,2,0,0,0,0,\"\",0,0,0,\["
		puts $out_fd "\"$Key($i)\"\])."
		puts $out_fd "poly('$lineColor($i)',2,\["
		puts $out_fd "\t\t$XM,[expr $Y0+$j*30],[expr $XM+40],[expr $Y0+$j*30],\],0,2,1,25,0,0,0,0,8,3,0,0,0,'1','8','3',)"
		puts $out_fd "\"0\",\[" ; puts $out_fd "\])."
		incr j
	    }
	}
    }

    # Datas
    set magnif [expr double($XM-$centerX)/$stepMain/$stepAxis1]
    for {set i 1} {$i < 5} {incr i} {
	if {$dataOK($i) != "OK" ||  $isDraw($i) != 1} {continue}
	set j 0 ; set datas ""
	while {$angle($i,$j) < $startAngle} {incr j} ; set numP 0
	while {$angle($i,$j) != "END"} {
	    if {$angle($i,$j) > $endAngle} { break } ; set tmpValue ""
	    if {$value($i,$j) < $endValue} {
		set tmpValue $endValue
	    } elseif {$value($i,$j) > $startValue} {
		set tmpValue $startValue
	    } else {set tmpValue $value($i,$j)}
	    
	    set realAngle [expr ($startAngle-$angle($i,$j)+$offangle)*$deg2rad]
	    set realValue [expr ($tmpValue-$endValue)*$magnif]
	    
	    set realX [expr int($realValue*cos($realAngle)+$centerX)]
	    set realY [expr int($centerY - $realValue*sin($realAngle))]

	    lappend datas "$realX,$realY," ; incr numP ; incr j
	}
	puts $out_fd "poly('$lineColor($i)',$numP,\["
	set tmpNumP $numP
	if {[llength $datas] > 8} {
	    set k 0
	    while {[set tmpdatas [lrange $datas $k [expr $k+7]]] != ""} {
		set tmpNumP [incr tmpNumP -8]
		if {[llength [split $tmpdatas "," ]] > 16 && $tmpNumP != 0} {
		    puts $out_fd "\t$tmpdatas"
		} else {
		    puts $out_fd "\t$tmpdatas\],0,$lineWidth($i),1,25,0,0,0,0,8,3,0,0,0,'1','8','3',"
		}
		incr k 8
	    }
	} else {
	    puts $out_fd "\t\t$datas\],0,1,1,25,0,0,0,0,8,3,0,0,0,'1','8','3',"
	}
	    
	set num0  [expr int(double($numP)/4)] ; set text0 ""
	for {set m 1} {$m <= $num0} {incr m} {
	    append text0 "0" ; if {$m % 64 == 0} { append text0 "\n" }
	}
	puts $out_fd "\"$text0\",\[" ; puts $out_fd "\]).\n"
    }

    # Value Texts
    if {$graphForm == "full"} {
	puts $out_fd "text('black',[expr int($centerX+5)],[expr int($Y0-10)],'Helvetica',0,20,1,0,0,1,31,22,43,0,18,4,2,0,0,0,0,2,0,0,0,0,\"\",0,0,0,\["
    } else {
	puts $out_fd "text('black',[expr int($centerX+5)],[expr int($centerY+10)],'Helvetica',0,20,1,0,0,1,31,22,43,0,18,4,2,0,0,0,0,2,0,0,0,0,\"\",0,0,0,\["
    }
    puts $out_fd "\"$axisLabel(1)\"\])."
    for {set i 0} {$i <= $stepMain} {incr i} {
	set X [expr int($centerX-5)]
	set Y [expr int(double($YM-$centerY)/$stepMain*$i+$Y0)-10]
	set tmpvalue [expr $startValue-$stepAxis1*$i]
	puts $out_fd "text('black',$X,$Y,'Helvetica',0,20,1,2,0,1,31,22,43,0,18,4,2,0,0,0,0,2,0,0,0,0,\"\",0,0,0,\["
	puts $out_fd "\"$tmpvalue\"\])."
    }

    # Angle Texts
    if {$graphForm == "full"} {
	set Xv(0) [expr $centerX+10] ; set Yv(0) [expr $Y0-30]
	set Xv(1) [expr $XM+15]      ; set Yv(1) [expr $centerY-10]
	set Xv(2) [expr $centerX+15] ; set Yv(2) [expr $YM+5]
	set Xv(3) [expr $X0-5]       ; set Yv(3) [expr $centerY-10]
	set tmpdiv 4                 ; set tmpnum 2
    } else {
	set Xv(0) [expr $X0-10]  ; set Yv(0) [expr $centerY-10]
	set Xv(1) $centerX       ; set Yv(1) [expr $Y0-30]
	set Xv(2) [expr $XM+30]  ; set Yv(2) [expr $centerY-10]
	set tmpdiv 2             ; set tmpnum 1
    }
    puts $out_fd "text('black',[expr $Xv($tmpnum)+10],$Yv($tmpnum),'Helvetica',0,20,1,0,0,1,31,22,43,0,18,4,2,0,0,0,0,2,0,0,0,0,\"\",0,0,0,\["
    puts $out_fd "\"$axisLabel(2)\"\])."
    for {set i 0} {$i < 4} {incr i} {
	if {$i == 3 && $graphForm != "full"} { break }
	set tmpvalue [expr int($startAngle+\
		double($endAngle-$startAngle)/$tmpdiv*$i)]
	puts $out_fd "text('black',$Xv($i),$Yv($i),'Helvetica',0,20,1,2,0,1,31,22,43,0,18,4,2,0,0,0,0,2,0,0,0,0,\"\",0,0,0,\["
	puts $out_fd "\"$tmpvalue\"\])."
    }

    # Close output file
    close $out_fd
    
    tk_messageBox -icon info -type ok -title "Success Information" \
	    -message "Output of Tgif File is succeeded"
    set outTgif [file tail $TGIFfile]
}


# file_conv -- File Converstion 
#
# Arguments    : How to Normalize, Value for Normalization
# Return Value : None
# Create Date  : 9th Mar. 1997
#
proc file_conv {normType toValue} {
    global curDir curDirC tmpRead tmpValue CSV HPIB isNorm tmpConv
    global angle value 

    set readFile $tmpRead ; set valueRow $tmpValue

    set result [readFile $curDir/$tmpRead 1 $tmpValue 0 $CSV $HPIB]
    if {$result != 0} {file_result $result NO ; return}

    # Data is normalized if needed.
    if {$isNorm == "YES"} {
	normalizer 0 $normType $toValue
    }

    # Execution depending on Data File Type
    if {$HPIB == "YES"} {
	set out_fd [open $curDirC/$tmpConv w] ; set j 0
	while {$angle(0,$j) != "END"} {
	    puts $out_fd "$angle(0,$j) $value(0,$j)" ; incr j
	}
    } else {
	set tmpRead  $readFile ; set tmpValue [incr tmpValue -1] ; set j 0
	set in_fd  [open $curDir/$tmpRead  r]
	set out_fd [open $curDirC/$tmpConv w]

	while {$angle(0,$j) != "END"} {
	    set line [gets $in_fd]
	    regsub {
$} $line "" line
	    if {[regexp {^\#} $line] == 1 || [llength $line] == 0} {
		puts $out_fd $line ; continue
	    }
	    if {$CSV == "YES"} {
		set line [split $line ,]
	    }
	    set line [lreplace $line $tmpValue $tmpValue $value(0,$j)]
	    if {$CSV == "YES"} {
		regsub -all { } $line {,} line
	    }
	    puts $out_fd $line ; incr j
	}
	close $in_fd
    }
    close $out_fd ; set tmpValue $valueRow ; set tmpConv ""
    tk_messageBox -icon info -title "Success Information" -type ok \
	    -default ok -message "Finish converting the File"
}


# setup -- Setup Default Values of DrawP 
#
# Argument      : Path of Top Frame
# Return Value  : none
# Modified Date : 2 Feb. 1997
#
proc setup {w} {
    global font angleNum valueNum frameType orderType graphForm 
    global stepAxis1 stepAxis2 stepAngle startValue endValue 
    global startAngle endAngle ext CSV frameTMP orderTMP graphTMP 
    global axis1TMP axis2TMP angleTMP sValueTMP eValueTMP sAngleTMP eAngleTMP
    global extTMP csvTMP angleNumTMP valueNumTMP wait_var

    if {[winfo exist .top]} { return }
    toplevel .top -bd 5 -relief sunken ; grab set .top
    wm group .top $w ; wm title .top "Customize Default Values"

    set wait_var ""

    if {[file exist ~/.drawp] == 1 && [file size ~/.drawp] != 0} {
	set in_fd [open ~/.drawp r] ; set line [gets $in_fd] ; close $in_fd

	for {set i 0} {$i < 14} {incr i} {
	    set defaults($i) [lindex [split $line ,] $i]
	}
	set frameTMP    $defaults(0)  ; set orderTMP    $defaults(1)
	set graphTMP    $defaults(2)  ; set axis1TMP    $defaults(3)
	set axis2TMP    $defaults(4)  ; set angleTMP    $defaults(5)
	set sValueTMP   $defaults(6)  ; set eValueTMP   $defaults(7)
	set sAngleTMP   $defaults(8)  ; set eAngleTMP   $defaults(9)
	set extTMP      $defaults(10) ; set csvTMP      $defaults(11)
	set angleNumTMP $defaults(12) ; set valueNumTMP $defaults(13)
    } else {
	set frameTMP $frameType   ; set orderTMP $orderType
	set graphTMP $graphForm   ; set axis1TMP $stepAxis1
	set axis2TMP $stepAxis2   ; set angleTMP $stepAngle
	set sValueTMP $startValue ; set eValueTMP $endValue
	set sAngleTMP $startAngle ; set eAngleTMP $endAngle
	set extTMP $ext           ; set csvTMP $CSV
	set angleNumTMP $angleNum ; set valueNumTMP $valueNum
    }

    frame .top.frame  -bd 2 ; frame .top.order   -bd 2 
    frame .top.graph  -bd 2 ; frame .top.csv     -bd 2
    frame .top.axes   -bd 2 ; frame .top.angle   -bd 2
    frame .top.values -bd 2 ; frame .top.angles  -bd 2
    frame .top.ext    -bd 2 ; frame .top.numbers -bd 2

    label .top.frameT -text "Frame Type of Notes : No." \
	    -font $font(2) -width 25 -anchor w
    label .top.orderT -text "Order Type of Notes : No." \
	    -font $font(2) -width 25 -anchor w
    label .top.graphT -text "Graph Form : " \
	    -font $font(2) -width 25 -anchor w
    label .top.csvT -text "Data Format is CSV : " \
	    -font $font(2) -width 25 -anchor w
    label .top.angleT -text "Angle Line Step : " \
	    -font $font(2) -width 25 -anchor w
    label .top.angleT2 -text "(degs./line)" -font $font(1) -anchor w
    label .top.axesT -text "Axis Main/Sub Step : " \
	    -font $font(2) -width 19 -anchor w
    label .top.axesT2 -text "(units/line)" \
	    -font $font(1) -width 10 -anchor w
    label .top.valuesT -text "Max./Min. Value : " \
	    -font $font(2) -width 19 -anchor w
    label .top.anglesT -text "Start/End Angle : " \
	    -font $font(2) -width 19 -anchor w
    label .top.anglesT2 -text "(degs.)" -font $font(1) -width 10 -anchor w
    label .top.numbersT -text "Angle/Value Rows : No. " \
	    -font $font(2) -width 25 -anchor w
    label .top.extT -text "Converted File Extension : " \
	    -font $font(2) -width 25 -anchor w

    set rom(1) "I" ; set rom(2) "II" ; set rom(3) "III"
    for {set i 1} {$i < 4} {incr i} {
	radiobutton .top.frame$i -text "$i"       -font $font(2) -bd 3\
		-variable frameTMP -value $i
	radiobutton .top.order$i -text "$rom($i)" -font $font(2) -bd 3\
		-variable orderTMP -value $i
    }

    radiobutton .top.graph_f -text "Full" -font $font(2) -variable graphTMP \
	    -value "full" -bd 3 -command {set sAngleTMP 0 ;\
	    set eAngleTMP [expr $sAngleTMP+360]}
    radiobutton .top.graph_s -text "Semi" -font $font(2) -variable graphTMP \
	    -value "semi" -bd 3 -command {set sAngleTMP -90 ;\
	    set eAngleTMP [expr $sAngleTMP+180]}
    checkbutton .top.isCSV -text "YES" -font $font(2) -variable csvTMP \
	    -onvalue YES -offvalue NO -bd 3

    button  .top.ok -text "Save" -font $font(4) -bd 3 -activeforeground blue \
	    -command {set wait_var 1}
    button  .top.cancel -text "Cancel" -font $font(4) -bd 3 \
	    -activeforeground red -command {set wait_var 0}

    entry .top.numberE1 -textvariable angleNumTMP -font $font(2) -width 4 -bd 3
    entry .top.numberE2 -textvariable valueNumTMP -font $font(2) -width 4 -bd 3
    entry .top.angleE   -textvariable angleTMP    -font $font(2) -width 4 -bd 3
    entry .top.extE     -textvariable extTMP      -font $font(2) -width 4 -bd 3
    entry .top.axis1E   -textvariable axis1TMP    -font $font(2) -width 4 -bd 3
    entry .top.axis2E   -textvariable axis2TMP    -font $font(2) -width 4 -bd 3
    entry .top.sValueE  -textvariable sValueTMP   -font $font(2) -width 4 -bd 3
    entry .top.eValueE  -textvariable eValueTMP   -font $font(2) -width 4 -bd 3
    entry .top.sAngleE  -textvariable sAngleTMP   -font $font(2) -width 4 -bd 3
    entry .top.eAngleE  -textvariable eAngleTMP   -font $font(2) \
	    -width 4 -bd 3 -fg gray50 -state disabled

    bind .top.angleE   <Return> {
	if {[catch {expr double($angleTMP)}] == 0} { focus .top.axis1E } \
		else { set angleTMP $stepAngle }
    }
    bind .top.angleE   <Leave> {
	if {[catch {expr double($angleTMP)}] == 0} { focus .top.ok } \
		else { set angleTMP $stepAngle ; focus .top.ok}
    }
    bind .top.axis1E   <Return> {
	if {[catch {expr double($axis1TMP)}] == 0} { focus .top.axis2E }\
		else { set axis1TMP $stepAxis1 }
    }
    bind .top.axis1E   <Leave> {
	if {[catch {expr double($axis1TMP)}] == 0} { focus .top.ok }\
		else { set axis1TMP $stepAxis1 ; focus .top.ok}
    }
    bind .top.axis2E   <Return> {
	if {[catch {expr double($axis2TMP)}] == 0 && $axis2TMP < $axis1TMP} {
	    focus .top.sValueE
	} else { set axis2TMP $stepAxis2 }
    }
    bind .top.axis2E   <Leave> {
	if {[catch {expr double($axis2TMP)}] == 0 && $axis2TMP < $axis1TMP} {
	    focus .top.ok
	} else { set axis2TMP $stepAxis2 ; focus .top.ok}
    }
    bind .top.sValueE  <Return> {
	if {[catch {expr double($sValueTMP)}] == 0} { focus .top.eValueE }\
		else { set sValueTMP $startValue }
    }
    bind .top.sValueE  <Leave> {
	if {[catch {expr double($sValueTMP)}] == 0} { focus .top.ok }\
		else { set sValueTMP $startValue ; focus .top.ok}
    }
    bind .top.eValueE  <Return> {
	if {[catch {expr double($eValueTMP)}]==0 && $eValueTMP<$sValueTMP} {
	    	focus .top.sAngleE
	} else { set eValueTMP $endValue }
    }
    bind .top.eValueE  <Leave> {
	if {[catch {expr double($eValueTMP)}]==0 && $eValueTMP<$sValueTMP} {
	    	focus .top.ok
	} else { set eValueTMP $endValue ; focus .top.ok}
    }
    bind .top.sAngleE  <Return> {
	if {[catch {expr double($sAngleTMP)}] == 0} {
	    set eAngleTMP [expr {($graphTMP == "full") ?\
		    [expr $sAngleTMP + 360] : [expr $sAngleTMP + 180]} ]
	    focus .top.extE
	} else { set sAngleTMP $startAngle}
    }
    bind .top.sAngleE  <Leave> {
	if {[catch {expr double($sAngleTMP)}] == 0} {
	    set eAngleTMP [expr {($graphTMP == "full") ?\
		    [expr $sAngleTMP + 360] : [expr $sAngleTMP + 180]} ]
	    focus .top.ok
	} else { set sAngleTMP $startAngle ; focus .top.ok}
    }
    bind .top.extE     <Return> {focus .top.numberE1}
    bind .top.numberE1 <Return> {
	if {[catch {expr int($angleNumTMP)}] == 0} {
	    set angleNumTMP [expr int($angleNumTMP)] ; focus .top.numberE2
	} else { set angleNumTMP $angleNum }
    }
    bind .top.numberE1 <Leave> {
	if {[catch {expr int($angleNumTMP)}] == 0} {
	    set angleNumTMP [expr int($angleNumTMP)] ; focus .top.ok
	} else { set angleNumTMP $angleNum ; focus .top.ok}
    }
    bind .top.numberE2 <Return> {
	if {[catch {expr int($valueNumTMP)}] == 0 && \
		$valueNumTMP != $angleNumTMP} {
	    set valueNumTMP [expr int($valueNumTMP)] ; focus .top.ok
	} else { set valueNumTMP $valueNum }
    }
    bind .top.numberE2 <Leave> {
	if {[catch {expr int($valueNumTMP)}] == 0 && \
		$valueNumTMP != $angleNumTMP} {
	    set valueNumTMP [expr int($valueNumTMP)] ; focus .top.ok
	} else { set valueNumTMP $valueNum ; focus .top.ok}
    }

    pack .top.graphT               -in .top.graph -side left
    pack .top.graph_s .top.graph_f -in .top.graph -side right
    pack .top.frameT .top.frame1 .top.frame2 .top.frame3 \
	    -in .top.frame -side left
    pack .top.orderT .top.order1 .top.order2 .top.order3 \
	    -in .top.order -side left
    pack .top.csvT .top.isCSV -in .top.csv -side left
    pack .top.extT .top.extE  -in .top.ext -side left
    pack .top.angleT .top.angleE .top.angleT2 -in .top.angle -side left
    pack .top.axesT .top.axis1E .top.axis2E .top.axesT2 -in .top.axes \
	    -side left -padx 2 -anchor w
    pack .top.valuesT .top.sValueE .top.eValueE -in .top.values -side left \
	    -padx 2 -anchor w
    pack .top.anglesT .top.sAngleE .top.eAngleE .top.anglesT2 -in .top.angles \
	    -side left -padx 2  -anchor w
    pack .top.numbersT .top.numberE1 .top.numberE2 -side left -in .top.numbers 
    pack .top.frame .top.order .top.graph .top.csv .top.angle .top.axes \
	    .top.values .top.angles .top.ext .top.numbers -side top \
	    -padx 2 -anchor w
    pack .top.ok .top.cancel -side left -fill x -expand yes

    tkwait variable wait_var

    if {$wait_var == 1} {
	if {$extTMP == ""} {set extTMP $ext}

	set out_fd [open ~/.drawp w]
	puts $out_fd $frameTMP,$orderTMP,$graphTMP,$axis1TMP,$axis2TMP,$angleTMP,$sValueTMP,$eValueTMP,$sAngleTMP,$eAngleTMP,$extTMP,$csvTMP,$angleNumTMP,$valueNumTMP
	close $out_fd
    }

    if {[winfo exist .top]} { destroy .top } ;  grab release .top
}


drawAxis 
