
proc APSPlotCanvasHelp {} {
    return "Usage: APSPlotCanvas widget \n\[-parent <string>\]\n\[-packOption <list>\]\n\[-background <color>\]\n\[-width <integer>\]\n\[-height <integer>\]\n\[-dataFile <sddsplot output file>\]\n\[-sddsplotOptions <sddsplot commandline>\]\n\[-sddscontourOptions <sddscontour commandline>\]\n\nCreates\t\$parent\$widget.canvas\n\t\$parent\$widget.label"
}

proc APSPlotCanvas {widget args} {
    set parent ""
    set packOptions "-side top -expand true -fill both"
    set background black
    set width 688
    set height 466
    set dataFile ""
    set sddsplotOptions ""
    set sddscontourOptions ""
    APSStrictParseArguments {parent packOptions background width height dataFile sddsplotOptions sddscontourOptions}
    
    global apsMenuBackground tk_version
    if {[string range $tk_version 0 2] <= 8.3} {
        frame ${parent}${widget} -bg $apsMenuBackground -relief raised -bd 2
    } else {
        frame ${parent}${widget} -bg $apsMenuBackground -padx 2 -pady 2 -relief raised -bd 2
    }
    eval pack ${parent}$widget $packOptions
    label ${parent}$widget.label -text "Plot 1 of ?" -bg $apsMenuBackground -fg white
    pack ${parent}$widget.label -fill x
    canvas ${parent}$widget.canvas -bg $background -width $width -height $height -relief flat -bd 0
    pack ${parent}$widget.canvas -fill both -expand true
    set plot ${parent}$widget.canvas
    set plotLabel ${parent}$widget.label
    update

    set program sddsplot
    if {[string length $sddscontourOptions] > 0} {
	set sddsplotOptions $sddscontourOptions
	set program sddscontour
    }
    if {[string length $sddsplotOptions] > 0} {
	if {![llength $dataFile]} {
	    set dataFile /tmp/[APSTmpString]
	    APSAddToTempFileList $dataFile
	}
	if {[catch {eval exec $program $sddsplotOptions -output=$dataFile} results]} {
	    puts "$results"
	}
    }
	

    set i 0
    while 1 {
        global apsPlot$i
        if {![info exists apsPlot$i]} {
            break
        }
        incr i
    }
    set apsPlot${i}(program) $program
    set apsPlot${i}(sddsplotOptions) $sddsplotOptions
    set apsPlot${i}(dataFile) $dataFile
    set apsPlot${i}(dataFileOrig) $dataFile
    set apsPlot${i}(tags) ""
    set apsPlot${i}(page) "1"
    set apsPlot${i}(deltax) "1.0"
    set apsPlot${i}(deltay) "1.0"
    set apsPlot${i}(x0) "0.0"
    set apsPlot${i}(y0) "0.0"
    set apsPlot${i}(width) "$width"
    set apsPlot${i}(height) "$height"
    set apsPlot${i}(userax) 0.0
    set apsPlot${i}(userbx) 0.0
    set apsPlot${i}(useray) 0.0
    set apsPlot${i}(userby) 0.0
    set apsPlot${i}(userindex) 1000
    set apsPlot${i}(mx) 0.0
    set apsPlot${i}(my) 0.0
    set apsPlot${i}(xtime) 0
    if {[string length $sddsplotOptions] > 0} {
        foreach op $sddsplotOptions {
            if {([string first -ticks=xtime $op] != -1)} {
                set apsPlot${i}(xtime) 1
                break
            }
        }
    }
    if {$background == "white"} {
        set zoomOutline "black"
    } else {
        set zoomOutline "white"
    }

    bind $plot <Configure> "APSUpdatePlotCanvas %w %h -updateLabel 0 -plot $plot -plotLabel $plotLabel -background $background -plotVar apsPlot$i"
    bind $plot <KeyPress-less> "APSPlotFirst -plot $plot -plotVar apsPlot$i -plotLabel $plotLabel"
    bind $plot <KeyPress-greater> "APSPlotLast -plot $plot -plotVar apsPlot$i -plotLabel $plotLabel"
    bind $plot <KeyPress-n> "APSPlotNext -plot $plot -plotVar apsPlot$i -plotLabel $plotLabel"
    bind $plot <KeyPress-p> "APSPlotPrevious -plot $plot -plotVar apsPlot$i -plotLabel $plotLabel"
    bind $plot <KeyPress-m> "APSPlotMovie -plot $plot -plotVar apsPlot$i -plotLabel $plotLabel"
    bind $plot <ButtonPress-1> "APSPlotZoomBoxStart %x %y -plot $plot -plotVar apsPlot$i -outline $zoomOutline"
    bind $plot <B1-Motion> "APSPlotZoomBoxMove %x %y -plot $plot -plotVar apsPlot$i"
    bind $plot <ButtonRelease-1> "APSPlotZoomBoxRelease %x %y -plot $plot -plotVar apsPlot$i"
    bind $plot <ButtonPress-2> "APSPlotZoom -plot $plot -plotVar apsPlot$i"
    bind $plot <ButtonPress-3> "APSPlotUnZoom -plot $plot -plotVar apsPlot$i"
    bind $plot <Enter> "focus $plot"
    bind $plot <KeyPress-period> "APSToggleMouseTracker -plot $plot -plotVar apsPlot$i -background $background"
    bind $plot <KeyPress-t> "APSToggleMouseTrackerTime -plotVar apsPlot$i"
    focus $plot
    APSUpdatePlotCanvas 0 0 -updateLabel 1 -plot $plot -plotLabel $plotLabel -background $background -plotVar apsPlot$i
}

proc APSToggleMouseTrackerTime {args} {
    set plotVar ""
    APSStrictParseArguments {plotVar}
    global $plotVar
    if {[set ${plotVar}(xtime)]} {
        set ${plotVar}(xtime) 0
    } else {
        set ${plotVar}(xtime) 1
    }
}

proc APSToggleMouseTracker {args} {
    set plot ""
    set plotVar ""
    set background black
    APSStrictParseArguments {plot plotVar background}
    global $plotVar

    if {$background == "white"} {
        set fg black
    } else {
        set fg white
    }
    if {[winfo exists .${plotVar}mt]} {
        if {[set ${plotVar}(userindex)] == 0} {
            destroy .${plotVar}mt
            bind $plot <Motion> ""
        } else {
            incr ${plotVar}(userindex) -1
            APSPlotSetUserCoords -plotVar $plotVar
        }
    } else {
        set page [set ${plotVar}(page)]
        set ${plotVar}(userindex) [expr {[llength [set ${plotVar}(userax$page)]] - 1}]
        APSPlotSetUserCoords -plotVar $plotVar
        bind $plot <Motion> "APSMouseTracker %x %y -plot $plot -plotVar $plotVar"
        frame .${plotVar}mt
        APSLabeledOutput .x -parent .${plotVar}mt -label "\#1 x:" -textVariable ${plotVar}(mx) -packOption "-side left"
        APSLabeledOutput .y -parent .${plotVar}mt -label "y:" -textVariable ${plotVar}(my) -packOption "-side left"
        .${plotVar}mt.x configure -bg $background
        .${plotVar}mt.x.label configure -bg $background -fg $fg -font {Times 8}
        .${plotVar}mt.x.entry configure -readonlybackground $background -bg $background -fg $fg -font {Times 8}
        .${plotVar}mt.y configure -bg $background
        .${plotVar}mt.y.label configure -bg $background -fg $fg -font {Times 8}
        .${plotVar}mt.y.entry configure -readonlybackground $background -bg $background -fg $fg -font {Times 8}
        place .${plotVar}mt -in $plot -x 1 -y 1
    }
}

proc APSMouseTracker {x y args} {
    set plot ""
    set plotVar ""
    APSStrictParseArguments {plot plotVar}
    global $plotVar
    
    if {![info exists ${plotVar}(scaley)]} {return}
    if {![info exists ${plotVar}(userby)]} {return}

    set tmp [expr {(($x + [set ${plotVar}(offsetx0)]) / [set ${plotVar}(scalex)]) * [set ${plotVar}(userax)] + [set ${plotVar}(userbx)]}]
    if {[set ${plotVar}(xtime)]} {
        set ${plotVar}(mx) [clock format [expr int($tmp)] -format "%D %T"]
    } else {
        set ${plotVar}(mx) $tmp
    }
    set ${plotVar}(my) [expr {([set ${plotVar}(YMAX)] - ($y + [set ${plotVar}(offsety0)]) / [set ${plotVar}(scaley)]) * [set ${plotVar}(useray)] + [set ${plotVar}(userby)]}]    

}

proc APSPlotFirst {args} {
    set plot ""
    set plotVar ""
    set plotLabel ""
    APSStrictParseArguments {plot plotVar plotLabel}
    global $plotVar

    $plot itemconfigure t[set ${plotVar}(page)] -state hidden
    set ${plotVar}(page) 1
    $plotLabel configure -text "Plot [set ${plotVar}(page)] of [set ${plotVar}(pages)]"
    $plot itemconfigure t[set ${plotVar}(page)] -state normal
    APSPlotSetUserCoords -plotVar $plotVar
}

proc APSPlotLast {args} {
    set plot ""
    set plotVar ""
    set plotLabel ""
    APSStrictParseArguments {plot plotVar plotLabel}
    global $plotVar

    $plot itemconfigure t[set ${plotVar}(page)] -state hidden
    set ${plotVar}(page) [set ${plotVar}(pages)]
    $plotLabel configure -text "Plot [set ${plotVar}(page)] of [set ${plotVar}(pages)]"
    $plot itemconfigure t[set ${plotVar}(page)] -state normal
    APSPlotSetUserCoords -plotVar $plotVar
}

proc APSPlotNext {args} {
    set plot ""
    set plotVar ""
    set plotLabel ""
    APSStrictParseArguments {plot plotVar plotLabel}
    global $plotVar

    if {[set ${plotVar}(page)] == [set ${plotVar}(pages)]} {
        return
    }
    $plot itemconfigure t[set ${plotVar}(page)] -state hidden
    incr ${plotVar}(page)
    $plotLabel configure -text "Plot [set ${plotVar}(page)] of [set ${plotVar}(pages)]"
    $plot itemconfigure t[set ${plotVar}(page)] -state normal
    APSPlotSetUserCoords -plotVar $plotVar
}

proc APSPlotSetUserCoords {args} {
    set plotVar ""
    APSStrictParseArguments {plotVar}

    global $plotVar
    set page [set ${plotVar}(page)]
    if {[set ${plotVar}(userindex)] >= [llength [set ${plotVar}(userax$page)]]} {
        set ${plotVar}(userindex) [expr {[llength [set ${plotVar}(userax$page)]] - 1}]
    }
    set ${plotVar}(userax) [lindex [set ${plotVar}(userax$page)] [set ${plotVar}(userindex)]]
    set ${plotVar}(userbx) [lindex [set ${plotVar}(userbx$page)] [set ${plotVar}(userindex)]]
    set ${plotVar}(useray) [lindex [set ${plotVar}(useray$page)] [set ${plotVar}(userindex)]]
    set ${plotVar}(userby) [lindex [set ${plotVar}(userby$page)] [set ${plotVar}(userindex)]]
    if {[winfo exists .${plotVar}mt.x.label]} {
        set lineN [expr {[llength [set ${plotVar}(userax$page)]] - [set ${plotVar}(userindex)]}]
        .${plotVar}mt.x.label configure -text "\#$lineN x:"
    }
}

proc APSPlotPrevious {args} {
    set plot ""
    set plotVar ""
    set plotLabel ""
    APSStrictParseArguments {plot plotVar plotLabel}
    global $plotVar

    if {[set ${plotVar}(page)] == "1"} {
        return
    }
    $plot itemconfigure t[set ${plotVar}(page)] -state hidden
    incr ${plotVar}(page) -1
    $plotLabel configure -text "Plot [set ${plotVar}(page)] of [set ${plotVar}(pages)]"
    $plot itemconfigure t[set ${plotVar}(page)] -state normal
    APSPlotSetUserCoords -plotVar $plotVar
}

proc APSPlotUnZoom {args} {
    set plot ""
    set plotVar ""
    APSStrictParseArguments {plot plotVar}
    global $plotVar
    
    eval $plot delete zoom
    set ${plotVar}(deltax) 1.0
    set ${plotVar}(deltay) 1.0
    set ${plotVar}(x0) 0.0
    set ${plotVar}(y0) 0.0
    if {[string length [set ${plotVar}(sddsplotOptions)]] > 0} {
	if {[info exists ${plotVar}(plotdatabinaryOrig)]} {
	    set ${plotVar}(plotdatabinary) [set ${plotVar}(plotdatabinaryOrig)]
	    set ${plotVar}(dataFile) [set ${plotVar}(dataFileOrig)]
	}
    } else {
	event generate $plot <Configure>
    }
    event generate $plot <Configure>
}

proc APSPlotZoom {args} {
    set plot ""
    set plotVar ""
    APSStrictParseArguments {plot plotVar}
    global $plotVar
    
    eval $plot delete zoom
    if {![info exists ${plotVar}(zoomx)]} {return}
    set x1 [set ${plotVar}(zoomx)]
    set x2 [set ${plotVar}(zoomx2)]
    set y1 [set ${plotVar}(zoomy)]
    set y2 [set ${plotVar}(zoomy2)]
    unset ${plotVar}(zoomx)

    if {([string length [set ${plotVar}(sddsplotOptions)]] > 0) && ([set ${plotVar}(program)] == "sddsplot")} {
	if {$x1 < $x2} {
	    set xmin $x1
	    set xmax $x2
	} else {
	    set xmin $x2
	    set xmax $x1
	}
	if {$y1 < $y2} {
	    set ymin $y2
	    set ymax $y1
	} else {
	    set ymin $y1
	    set ymax $y2
	}
	set xminLimit [expr {(($xmin + [set ${plotVar}(offsetx0)]) / [set ${plotVar}(scalex)]) * [set ${plotVar}(userax)] + [set ${plotVar}(userbx)]}]
	set xmaxLimit [expr {(($xmax + [set ${plotVar}(offsetx0)]) / [set ${plotVar}(scalex)]) * [set ${plotVar}(userax)] + [set ${plotVar}(userbx)]}]
	set yminLimit [expr {([set ${plotVar}(YMAX)] - ($ymin + [set ${plotVar}(offsety0)]) / [set ${plotVar}(scaley)]) * [set ${plotVar}(useray)] + [set ${plotVar}(userby)]}]    
	set ymaxLimit [expr {([set ${plotVar}(YMAX)] - ($ymax + [set ${plotVar}(offsety0)]) / [set ${plotVar}(scaley)]) * [set ${plotVar}(useray)] + [set ${plotVar}(userby)]}]    

	set dataFile /tmp/[APSTmpString]
	APSAddToTempFileList $dataFile
        set options ""
        foreach op [set ${plotVar}(sddsplotOptions)] {
            if {([string first -factor=ym [string tolower $op]] != -1)} {
                set ymult [os editstring "z=dz=d" [string range $op 1 end]]
                append options "\"$op\" -limit=xMinimum=${xminLimit},xMaximum=${xmaxLimit},yMinimum=[expr {${yminLimit} / (1.0 * $ymult)}],yMaximum=[expr {${ymaxLimit} / (1.0 * $ymult)}],autoscaling "
            } elseif {([string first -limit [string tolower $op]] != -1) ||
                      ([string first -scale [string tolower $op]] != -1)} {
            } else {
                append options "\"$op\" "
            }
        }
        if {[catch {eval exec [set ${plotVar}(program)] -limit=xMinimum=${xminLimit},xMaximum=${xmaxLimit},yMinimum=${yminLimit},yMaximum=${ymaxLimit},autoscaling $options -output=$dataFile} results]} {
            puts "$results"
        }
	if {![info exists ${plotVar}(plotdatabinaryOrig)]} {
	    set ${plotVar}(plotdatabinaryOrig) [set ${plotVar}(plotdatabinary)]
	}
	unset ${plotVar}(plotdatabinary)
	set ${plotVar}(dataFile) $dataFile
	set ${plotVar}(deltax) "1.0"
	set ${plotVar}(deltay) "1.0"
	set ${plotVar}(x0) "0.0"
	set ${plotVar}(y0) "0.0"
    } else {
	set width [set ${plotVar}(width)]
	set height [set ${plotVar}(height)]
	
	set dx [set ${plotVar}(deltax)]
	set dy [set ${plotVar}(deltay)]
	set ${plotVar}(deltax) [expr {abs($x1 - $x2) * [set ${plotVar}(deltax)] / (1.0 * $width)}]
	set ${plotVar}(deltay) [expr {abs($y1 - $y2) * [set ${plotVar}(deltay)] / (1.0 * $height)}]
	
	if {$x1 < $x2} {
	    set x $x1
	} else {
	    set x $x2
	}
	if {$y1 < $y2} {
	    set y $y1
	} else {
	    set y $y2
	}
	set ${plotVar}(x0) [expr {$dx * $x + [set ${plotVar}(x0)]}]
	set ${plotVar}(y0) [expr {$dy * $y + [set ${plotVar}(y0)]}]
    }
    event generate $plot <Configure>
}

proc APSPlotZoomBoxStart {x y args} {
    set plot ""
    set plotVar ""
    set outline "white"
    APSStrictParseArguments {plot plotVar outline}
    global $plotVar
    
    eval $plot delete zoom
    set ${plotVar}(zoomx) $x
    set ${plotVar}(zoomy) $y
    $plot create rectangle $x $y $x $y -fill "" -outline $outline -state hidden -tags zoom
    $plot configure -cursor crosshair
}

proc APSPlotZoomBoxMove {x y args} {
    set plot ""
    set plotVar ""
    APSStrictParseArguments {plot plotVar}
    global $plotVar
    
    $plot coords zoom [set ${plotVar}(zoomx)] [set ${plotVar}(zoomy)] $x $y
    $plot itemconfigure zoom -state normal
}

proc APSPlotZoomBoxRelease {x y args} {
    set plot ""
    set plotVar ""
    APSStrictParseArguments {plot plotVar}
    global $plotVar
    
    set ${plotVar}(zoomx2) $x
    set ${plotVar}(zoomy2) $y
    $plot coords zoom [set ${plotVar}(zoomx)] [set ${plotVar}(zoomy)] $x $y    
    $plot configure -cursor ""
}

proc APSPlotMovie {args} {
    set plot ""
    set plotVar ""
    set plotLabel ""
    APSStrictParseArguments {plot plotVar plotLabel}
    global $plotVar

    $plot itemconfigure t[set ${plotVar}(page)] -state hidden
    set ${plotVar}(page) 0

    for {set i 1} {$i <= [set ${plotVar}(pages)]} {incr i} {
        APSPlotNext -plot $plot -plotVar $plotVar -plotLabel $plotLabel
        APSWaitWithUpdate -waitSeconds .2 -updateInterval .2
    }
}

proc APSRGB {r g b} {
    set r [format %X $r]
    set g [format %X $g]
    set b [format %X $b]
    if {[string length $r] == 1} { set r 0$r }
    if {[string length $g] == 1} { set g 0$g }
    if {[string length $b] == 1} { set b 0$b }                
    return "\#$r$g$b"
}

proc APSPlotDrawLine {plot line color width tag state} {
    if {[llength $line] >= 4} {
	$plot create line $line -fill $color -width $width -tags $tag -state $state
    }
}

proc APSUpdatePlotCanvas {width height args} {
    set plot ""
    set background black
    set plotVar ""
    set plotLabel ""
    set updateLabel ""
    set clicks 0
    APSStrictParseArguments {plot background plotVar plotLabel updateLabel clicks}

    global apsMenuBackground tcl_platform $plotVar

    eval $plot delete [set ${plotVar}(tags)]
    set ${plotVar}(tags) ""
    if {$width == 0} {
        set width [set ${plotVar}(width)]
    } else {
        set ${plotVar}(width) [expr {$width - 2}]
    }
    if {$height == 0} {
        set height [set ${plotVar}(height)]
    } else {
        set ${plotVar}(height) [expr {$height - 2}]
    }

    set NCOLORS 18
    set NSPECT 101
    set linecolormax 0
    set linewidthscale 1
    set X11_XMAX 4096.0
    set X11_YMAX 3165.0
    set XMAX ${X11_XMAX}
    set YMAX ${X11_YMAX}
    set scalex [expr {($width - 1.0) / ($XMAX * [set ${plotVar}(deltax)])}]
    set scaley [expr {($height - 1.0) / ($YMAX * [set ${plotVar}(deltay)])}]
    set offsetx0 [expr {$scalex * [set ${plotVar}(x0)] * $XMAX / $width}]
    set offsety0 [expr {$scaley * [set ${plotVar}(y0)] * $YMAX / $height}]
    set offsetx [expr {$offsetx0 - .5}]
    set offsety [expr {$offsety0 - .5}]

    set ${plotVar}(offsetx0) $offsetx0
    set ${plotVar}(offsety0) $offsety0
    set ${plotVar}(scalex) $scalex
    set ${plotVar}(scaley) $scaley
    set ${plotVar}(XMAX) $XMAX
    set ${plotVar}(YMAX) $YMAX

    global apsPlotSpectrum
    if {![info exists apsPlotSpectrum(0)]} {
        set k 0
	for {set n 0} {$n < $NSPECT} {incr n} {
            if {$k < 256} {
                set apsPlotSpectrum($n) [APSRGB 0 $k 255]
            } elseif {($k >= 256) && ($k < 512)} {
                set apsPlotSpectrum($n) [APSRGB 0 255 [expr {511 - $k}]]
            } elseif {($k >= 512) && ($k < 768)} {
                set apsPlotSpectrum($n) [APSRGB [expr {$k - 512}] 255 0]
            } elseif {($k >= 768) && ($k < 1024)} {
                set apsPlotSpectrum($n) [APSRGB 255 [expr {1023 - $k}] 0]
            } else {
                set apsPlotSpectrum($n) [APSRGB 255 0 [expr {$k - 1024}]]
            }
            incr k 12;
        }   
    }

    set i 0
    foreach color "black white white red blue green yellow magenta cyan limegreen gold orange hotpink deepskyblue mediumspringgreen tomato tan grey75" {
        set colors($i) $color
        incr i
    }

    if {![info exists ${plotVar}(plotdatabinary)]} {
        if {[catch {open [set ${plotVar}(dataFile)] "r"} fid]} {
            puts "Error: $fid"
            return
        }
        fconfigure $fid -translation binary
        set plotdatabinary [read -nonewline $fid]
        catch {close $fid}
        set ${plotVar}(plotdatabinary) $plotdatabinary
    } else {
        set plotdatabinary [set ${plotVar}(plotdatabinary)]
    }
    binary scan $plotdatabinary "c*" plotData
    
    if {$tcl_platform(byteOrder) == "bigEndian"} {
        set s S
    } else {
        set s s
    }

    set currentcolor "white"
    set currentlinewidth 1
    set len [llength $plotData]

    for {set iteration 1} {$iteration <= 2} {incr iteration} {
        set page 0
        set ${plotVar}(pages) 0
	set line ""
        for {set n 0} {$n < $len} {} {
            binary scan $plotdatabinary @${n}c command
            set command [format %c $command]
            switch -exact -- $command {
                "V" {
                    #draw line
                    if {(($iteration == 1) && ($page == [set ${plotVar}(page)])) ||
                        (($iteration == 2) && ($page != [set ${plotVar}(page)]))} {
                        incr n
                        binary scan $plotdatabinary @${n}$s$s x y
                        append line "[expr {round($x * $scalex - $offsetx)}] [expr {round(($YMAX - $y) * $scaley - $offsety)}] "
                        incr n 4
                    } else {
                        incr n 5
                    }
                }
                "M" {
                    #move to
                    if {(($iteration == 1) && ($page == [set ${plotVar}(page)])) ||
                        (($iteration == 2) && ($page != [set ${plotVar}(page)]))} {
                        incr n
			APSPlotDrawLine $plot $line $currentcolor $currentlinewidth t$page hidden
                        binary scan $plotdatabinary @${n}$s$s cx cy
                        set line "[expr {round($cx * $scalex - $offsetx)}] [expr {round(($YMAX - $cy) * $scaley - $offsety)}] "
                        incr n 4
                    } else {
                        incr n 5
                    }
                }
                "P" {
                    #draw point
                    if {(($iteration == 1) && ($page == [set ${plotVar}(page)])) ||
                        (($iteration == 2) && ($page != [set ${plotVar}(page)]))} {
                        incr n
			APSPlotDrawLine $plot $line $currentcolor $currentlinewidth t$page hidden
                        binary scan $plotdatabinary @${n}$s$s cx cy
                        set cx [expr {round($cx * $scalex - $offsetx)}]
                        set cy [expr {round(($YMAX - $cy) * $scaley - $offsety)}]
			set line "$cx $cy "
                        $plot create line $cx $cy [expr {$cx + 1}] $cy \
                            -fill $currentcolor \
                            -tags t$page \
                            -state hidden
                        incr n 4
                    } else {
                        incr n 5
                    }
                }
                "L" {
                    #set linetype
                    if {(($iteration == 1) && ($page == [set ${plotVar}(page)])) ||
                        (($iteration == 2) && ($page != [set ${plotVar}(page)]))} {
                        incr n
			APSPlotDrawLine $plot $line $currentcolor $currentlinewidth t$page hidden
			set line ""
                        binary scan $plotdatabinary @${n}$s lt
                        set lt [expr {$lt%16 + 2}]
                        if {$lt >= $NCOLORS} {set lt [expr {$NCOLORS - 1}]}
                        if {$lt > $linecolormax} {set linecolormax $lt}
                        set type PS_SOLID
                        set currentlinewidth $linewidthscale
                        set currentcolor $colors($lt)
                        incr n 2
                    } else {
                        incr n 3
                    }
                }
                "W" {
                    #set linewidth
                    if {(($iteration == 1) && ($page == [set ${plotVar}(page)])) ||
                        (($iteration == 2) && ($page != [set ${plotVar}(page)]))} {
                        incr n
			APSPlotDrawLine $plot $line $currentcolor $currentlinewidth t$page hidden
			set line ""
                        binary scan $plotdatabinary @${n}$s lt
                        set currentlinewidth [expr {$lt * $linewidthscale}]
                        incr n 2
                    } else {
                        incr n 3
                    }
                }
                "B" {
                    #draw rectangle
                    if {(($iteration == 1) && ($page == [set ${plotVar}(page)])) ||
                        (($iteration == 2) && ($page != [set ${plotVar}(page)]))} {
                        incr n
			APSPlotDrawLine $plot $line $currentcolor $currentlinewidth t$page hidden
			set line ""
                        binary scan $plotdatabinary @${n}$s$s$s$s$s shade xl xh yl yh
                        set shade [expr {$shade%$NSPECT}]
                        
                        $plot create rectangle \
                            [expr {round($xl * $scalex - $offsetx)}] \
                            [expr {round(($YMAX - $yl) * $scaley - $offsety)}] \
                            [expr {round($xh * $scalex - $offsetx)}] \
                            [expr {round(($YMAX - $yh) * $scaley - $offsety)}] \
                            -fill $apsPlotSpectrum($shade) \
                            -outline $apsPlotSpectrum($shade)\
                            -tags t$page \
                            -state hidden
                        incr n 10
                    } else {
                        incr n 11
                    }
                }
                "U" {
                    #user coordinate scaling
                    if {(($iteration == 1) && ($page == [set ${plotVar}(page)])) ||
                        (($iteration == 2) && ($page != [set ${plotVar}(page)]))} {
                        incr n
                        binary scan $plotdatabinary @${n}dddd userax userbx useray userby
                        set found 0
                        foreach ele1 [set ${plotVar}(userax$page)] \
                            ele2 [set ${plotVar}(userbx$page)] \
                            ele3 [set ${plotVar}(useray$page)] \
                            ele4 [set ${plotVar}(userby$page)] {
                                if {($userax == $ele1) && ($userbx == $ele2) && ($useray == $ele3) && ($userby == $ele4)} {
                                    set found 1
                                    break
                                }
                            }
                        if {$found} {
                            incr n 32
                            continue                            
                        }
                        append ${plotVar}(userax$page) "$userax "
                        append ${plotVar}(userbx$page) "$userbx "
                        append ${plotVar}(useray$page) "$useray "
                        append ${plotVar}(userby$page) "$userby "
                        incr n 32
                    } else {
                        incr n 33
                    }
                }
                "G" {
                    if {($iteration == 1)} {
                        if {($page == [set ${plotVar}(page)])} {
			    APSPlotDrawLine $plot $line $currentcolor $currentlinewidth t$page hidden
			    set line ""
                            $plot itemconfigure t[set ${plotVar}(page)] -state normal
                            if {$updateLabel} {
                                $plotLabel configure -text "Plot [set ${plotVar}(page)] of [set ${plotVar}(pages)]"
                            }
                            update idletasks
                            break
                        }
                    }
                    APSPlotDrawLine $plot $line $currentcolor $currentlinewidth t$page hidden
                    set line ""
                    incr ${plotVar}(pages)
                    if {(($iteration == 2) && ($updateLabel))} {
                        $plotLabel configure -text "Plot [set ${plotVar}(page)] of [set ${plotVar}(pages)]"
                        update idletasks
                    }
                    set page [set ${plotVar}(pages)]
                    append ${plotVar}(tags) "t$page "
                    if {(($iteration == 1) && ($page == [set ${plotVar}(page)])) ||
                        (($iteration == 2) && ($page != [set ${plotVar}(page)]))} {
                        set ${plotVar}(userax$page) ""
                        set ${plotVar}(userbx$page) ""
                        set ${plotVar}(useray$page) ""
                        set ${plotVar}(userby$page) ""
                    }
                    incr n
                } 
                "R" {
		    #reset graphics
                    incr n
                } 
                "E" {
		    #text
                    incr n
                } 
                "C" {
                    if {(($iteration == 1) && ($page == [set ${plotVar}(page)])) ||
                        (($iteration == 2) && ($page != [set ${plotVar}(page)]))} {
                        incr n
                        binary scan $plotdatabinary @${n}$s$s$s r g b
                        set r [format %X [expr {(( $r + 0x10000 ) % 0x10000) / 256}]]
                        set g [format %X [expr {(( $g + 0x10000 ) % 0x10000) / 256}]]
                        set b [format %X [expr {(( $b + 0x10000 ) % 0x10000) / 256}]]
                        if {[string length $r] == 1} { set r 0$r }
                        if {[string length $g] == 1} { set g 0$g }
                        if {[string length $b] == 1} { set b 0$b }                
                        set currentcolor "\#$r$g$b"
                        incr n 6
                    } else {
                        incr n 7
                    }
                }
                default {
                    incr n
                }
            }
        }
        if {($iteration == 1)} {
            if {($page == [set ${plotVar}(page)])} {
		APSPlotDrawLine $plot $line $currentcolor $currentlinewidth t$page hidden
		set line ""
                $plot itemconfigure t[set ${plotVar}(page)] -state normal
                if {$updateLabel} {
                    $plotLabel configure -text "Plot [set ${plotVar}(page)] of [set ${plotVar}(pages)]"
                }
                APSPlotSetUserCoords -plotVar $plotVar
                update idletasks
            }
        }
        APSPlotDrawLine $plot $line $currentcolor $currentlinewidth t$page hidden
        set line ""
    }

    if {[set ${plotVar}(page)] > [set ${plotVar}(pages)]} {
        set ${plotVar}(page) [set ${plotVar}(pages)]
    }
    if {[set ${plotVar}(page)] <= 0} {
        set ${plotVar}(page) 1
    }
}
