
# This code is shared by all the ICEM CFD GUI's.
#
# Copyright (c) 1993 - 1995 Pacific Marketing and Consulting, Inc,
#       and ICEM Systems, GmbH.  All rights reserved.
# Author:  Wayne A. Christopher, wayne@icemcfd.com

proc test_histogram {} {
    set xvals "0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16"
    set yvals "10 20 30 20 10 17 35 0  12 18 35 16 14 24 19 43"
    set ylimit 40
    set labels [list "First label" "Second label"]
    
    set nylines 4
    set nlabel 3
    set dimlines 0
    set defbuts 0
    set raiseback 0
    set raisegraph 1
    set pstitle 0
    set usequery 0
    
    make_histogram .fooey "Random histogram" $xvals $yvals $ylimit $labels \
	"" "" "" "" 0 $nylines $nlabel $dimlines $defbuts $raiseback \
	$raisegraph $pstitle $usequery
}

proc histo_format {x {use_more 0}} {
    global histo_xformat histo_colorband histo_maxv_limit histo_nbars
    if [info exists histo_xformat] {
        set xl [format $histo_xformat $x]
    } elseif {$x > -999999 && $x < 9999999 && [expr int ($x)] == $x} {
        set xl [expr int ($x)]
    } else {
        if $use_more {
            set xl [format %.3g $x]
        } else {
            set xl [format %.2g $x]
        }
    }
    if {[info exists histo_colorband] && [aie_get_max_possible_colorband] == "1.0e38" && \
        ($histo_nbars < $histo_maxv_limit)} {
        set xl [expr int ($x)]
    }
    return $xl
}

proc make_histogram {w title xvals yvals {ylimit 0} {labels ""} \
			 {replot_com ""} {highlight_com ""} {replot_args ""} \
			 {extra_buts ""} {always_highlight 0} \
			 {nylines 12} {nlabel 9} {dimlines 1} {defbuts 1} \
			 {raiseback 1} {raisegraph 0} {pstitle 1} \
			 {donebutton 1}} {
    global labelcolor histo_status histo_ids histo_title
    global histo_minx histo_maxx histo_clickedon histo_idmap histo_numy whoami
    global histo_width histo_height histo_solid histo_show
    global histo_color_by_quality black_and_white histo_xformat
    global histo_param histo_minv histo_maxv histo_ylim histo_nbars
    global histo_minv_limit histo_maxv_limit histo_after_click
    global histo_small_layout histo_bad_elements
    global ai_environment colorBand histo_colorband hexa_histogram_exist

    if {([info exists ai_environment] && $ai_environment)} {
        variable ::AIEnv::GUIManagement::GUIDisplayData
        set bigfont $::AIEnv::GUIManagement::GUIDisplayData("HistoBigFont")
        set normalfont $::AIEnv::GUIManagement::GUIDisplayData("HistoSmallFont")
        set nylines 4
    }

    if ![info exists histo_width] {
        set histo_width 600
        set histo_height 400
        set histo_solid 0
        set histo_color_by_quality 1
    }
    
    if [info exists hexa_histogram_exist] { unset hexa_histogram_exist }
    if [info exists histo_colorband] { unset histo_colorband }
    if {($highlight_com == "hex_select_histo" || $highlight_com == "aie_str_plot_histo" || $highlight_com == "grid_highlight_cmd")}  {
        if {$highlight_com == "hex_select_histo"} { set hexa_histogram_exist 1 } 
    } else {
        set histo_colorband 1
    }

    if ![info exists normalfont] {
        set normalfont -*-helvetica-bold-r-normal--10*
    }
    if ![info exists bigfont] {
        set bigfont -*-helvetica-bold-r-normal--12*
    }
    if ![info exists whoami] { set whoami histogram }
    
    set the_height $histo_height
    
    foreach i {minx maxx numy status ids idmap} { catch {unset histo_$i} }
    
    set histo_title $title
    
    if [winfo exists $w] {
        set ch [winfo children $w]
        if {$ch != ""} {
            pack propagate $w 0
            $w configure -width [winfo width $w] -height [winfo height $w] 
            foreach ww $ch {
                destroy $ww
            }
        }
        set must_move 0
    } else {
        top_window $w 1 Histogram
        top_geometry $w -0-0
    }
    set histo_ylim $ylimit
    set histo_nbars [llength $yvals]
    
    set has_replot [expr {$replot_com != ""}]
    set has_highlight [expr {$highlight_com != ""}]

    if $has_replot {
        set cmd [list histo_replot $w $replot_com $replot_args $ylimit]
    } else {
        set cmd list
    }
    if $has_highlight {
        set cmd2 [list histo_highlight $w 1 $highlight_com $replot_args]
    } else {
        set cmd2 list
    }
    
    if {[winfo parent $w] == "."} {
	    if {$highlight_com == ""} {
	        set donecmd "top_destroy $w"
	    } else {
	        set donecmd "$highlight_com $w {} \"$replot_args\" 0; top_destroy $w"
	    }
	    frame $w.botvals3
	    button $w.botvals3.done -text Done -command $donecmd -background gray80 -activebackground gray70
	    button $w.botvals3.ps -text "Hardcopy" -command "histo_postscript $w" -background gray80 -activebackground gray70
	    pack $w.botvals3.done $w.botvals3.ps -side left -fill none -padx 2 -pady 2
	    pack $w.botvals3 -side bottom -fill none -anchor c
	    incr the_height [expr -([winfo reqheight $w.botvals3.done] + 6)]
    }
    set place_widget ""
    catch {unset histo_popup_menu}
    if {$has_replot || $has_highlight} {
	if [info exists histo_small_layout] {
	    if { ([info exists ai_environment] && $ai_environment) } {
		set m $w.menu
		menu $m -tearoff 0
		$m add command -label Replot -command [list histo_replot_cmd $cmd]
		$m add command -label Reset -command [list histo_reset_cmd $cmd $cmd2]
		if {$has_highlight && ($highlight_com != "hex_select_histo" && \
		    $highlight_com != "aie_str_plot_histo")}  {
		    $m add command -label Refresh -command [list histo_refresh_cmd $cmd2 $replot_args]
		}
		if {$always_highlight == 2} {
		    $m add checkbutton -variable histo_show -label Show -command \
			[list histo_highlight $w 1 $highlight_com $replot_args]
		}
		if $always_highlight {
		    $m add checkbutton -variable histo_solid -label Solid \
			-command [list histo_highlight $w 1 $highlight_com \
				      $replot_args]
		    if {($highlight_com != "hex_select_histo" && $highlight_com != "aie_str_plot_histo")}  {
		        $m add checkbutton -variable histo_color_by_quality \
			    -label "Color by Quality" -command \
			    [list histo_highlight $w 1 $highlight_com $replot_args]
		    }
		} else {
		    $m add checkbutton -variable histo_solid -text Solid
		    if {($highlight_com != "hex_select_histo" && $highlight_com != "aie_str_plot_histo")} {
		        $m add checkbutton -variable histo_color_by_quality \
			    -text "Color by Quality"
		    }	
		}
		if {[info exists histo_bad_elements] && $always_highlight == 2 && \
		    $highlight_com != "hex_select_histo"} {
		    $m add cascade -label "Highlight..." -menu $w.menu.highlightbad
		    menu $w.menu.highlightbad -tearoff 0
		    $w.menu.highlightbad add radiobutton -label "selected elements" \
		        -variable histo_bad_elements -value bad \
		        -command "aie_histo_show_bad_elements"
		    $w.menu.highlightbad add radiobutton -label "selected elements + 1 layer" \
		        -variable histo_bad_elements -value bad_1_layer \
		        -command "aie_histo_show_bad_elements"
		    $w.menu.highlightbad add radiobutton -label "selected elements + 2 layer" \
		        -variable histo_bad_elements -value bad_2_layer \
		        -command "aie_histo_show_bad_elements"
		    if ![info exists histo_bad_elements] {
		        set histo_bad_elements bad
		    }
		}
		foreach b $extra_buts {
		    $m add command -label [lindex $b 1] -command [lindex $b 2]
		}
		set histo_popup_menu $m
	    } else {
		frame $w.optsframe
		button $w.optsframe.replot -text Replot -command [list histo_replot_cmd $cmd] -borderwidth 1
		button $w.optsframe.reset -text Reset -command [list histo_reset_cmd $cmd $cmd2] -borderwidth 1
		pack $w.optsframe.replot  $w.optsframe.reset -side top -fill x
		if {$always_highlight == 2} {
		    #button $w.optsframe.show -text Show -command
		    set histo_show 1
		    checkbutton $w.optsframe.show -variable histo_show -text  Show -command \
			[list histo_highlight $w 1 $highlight_com $replot_args] -borderwidth 1
		    pack $w.optsframe.show -side top -fill x
		}
		set histo_solid 0
		set histo_color_by_quality 1
		if $always_highlight {
		    checkbutton  $w.optsframe.solid -variable histo_solid \
			-text Solid -command [list histo_highlight $w 1 \
			$highlight_com \ $replot_args]  -borderwidth 1
		} else {
		    checkbutton $w.optsframe.solid  -variable histo_solid -text Solid  -borderwidth 1
		}
		pack $w.optsframe.solid -side top -fill x
		
		if $always_highlight {
		    checkbutton  $w.optsframe.color_by_quality -variable \
			histo_color_by_quality -text "Color by Quality" \
			 -command [list histo_highlight $w 1 \
			$highlight_com \ $replot_args]  -borderwidth 1
		} else {
		    checkbutton $w.optsframe.color_by_quality -variable \
			histo_color_by_quality -text "Color by Quality" \
			-borderwidth 1
		}
		pack $w.optsframe.color_by_quality -side top -fill x

		foreach b $extra_buts {
		    button $w.optsframe.$b -text [lindex $b 1] -command [lindex $b 2]  -borderwidth 1
		    pack $w.optsframe.$b -side top -fill x
		}
		set place_widget $w.optsframe
	    }
	} else {
	    frame $w.botvals
	    frame $w.botvals2
	    label $w.botvals.minl -text Min
	    label $w.botvals.maxl -text Max
	    label $w.botvals.yliml -text Height
	    label $w.botvals.barsl -text Bars
	    entry $w.botvals.min -textvariable histo_minv -width 6
	    entry $w.botvals.max -textvariable histo_maxv -width 6
	    entry $w.botvals.ylim -textvariable histo_ylim -width 4
	    entry $w.botvals.bars -textvariable histo_nbars -width 4
	    pack $w.botvals.minl $w.botvals.min $w.botvals.maxl $w.botvals.max \
		$w.botvals.yliml $w.botvals.ylim \
		$w.botvals.barsl $w.botvals.bars -side left -fill both
	    
	    button $w.botvals2.reset -text Reset -command "\
	    set histo_minv \$histo_minv_limit \;\
	    set histo_maxv \$histo_maxv_limit \;\
	    set histo_nbars 20 \; \
	    set histo_ylim 0 \;\
	    $cmd \; $cmd2"
	    button $w.botvals2.replot -text Replot -command $cmd
	    label $w.botvals2.space1 -text "  "
	    pack $w.botvals2.reset $w.botvals2.replot $w.botvals2.space1 -side left -fill both
	    if {$always_highlight == 2} {
            button $w.botvals2.show -text Show -command "histo_highlight $w 1 \"$highlight_com\" \"$replot_args\""
            pack $w.botvals2.show -side left -fill both
	    }
	    checkbutton $w.botvals2.solid -variable histo_solid -text Solid
	    pack $w.botvals2.solid -side left -fill both
	    if $always_highlight {
		    $w.botvals2.solid configure -command "histo_highlight $w 1 \"$highlight_com\" \"$replot_args\""
	    }
	    checkbutton $w.botvals2.color_by_quality -variable histo_color_by_quality -text "Color by Quality"
	    if $always_highlight {
		    $w.botvals2.color_by_quality configure -command "histo_highlight $w 1 \"$highlight_com\" \"$replot_args\""
	    }
	    pack $w.botvals2.color_by_quality -side left -fill both
	    if {$extra_buts != ""} {
		    foreach b $extra_buts {
		        button $w.botvals2.[lindex $b 0] -text [lindex $b 1] -command [lindex $b 2]
		        pack $w.botvals2.[lindex $b 0] -side left -padx 2 -pady 2
		    }
	    }
	    pack $w.botvals2 $w.botvals -side bottom -fill x
	    incr the_height [expr -2 * ([winfo reqheight $w.botvals.min] + 4)]
	    bind $w.botvals.min <Return> $cmd
	    bind $w.botvals.max <Return> $cmd
	    bind $w.botvals.ylim <Return> $cmd
	    bind $w.botvals.bars <Return> $cmd
	}
    }
    
    if $raiseback {
        set rb "-relief raised"
    } else {
        set rb ""
    }

    eval canvas $w.background -width $histo_width -height $the_height $rb -borderwidth 2
    
    # We put the graph on the background.  The background holds the
    # axes, but everything else put on the graph.  The graph is
    # indented into the axes which means we must include the
    # width of the graph's border in our calculations
    
    pack $w.background -side top -fill both -expand 1
    
    if [info exists histo_param(ticklen)] {
        set ticklen $histo_param(ticklen)
    } else {
        set ticklen 8
    }
    
    if {([info exists ai_environment] && $ai_environment)} {
    	set xlo 60
        set xhi [expr {$histo_width - 10}]
        set ylo 10
        set yhi [expr {$the_height - 3}]
    } else {
        set xlo 80
        set xhi [expr {$histo_width - 10}]
        set ylo 30
        set yhi [expr {$the_height - 30}]
    }
    
    if [info exists histo_param(tickcolor)] {
        set tickcolor $histo_param(tickcolor)
    } else {
        set tickcolor black
    }
    
    $w.background create line $xlo $yhi $xhi $yhi -fill $tickcolor
    $w.background create line $xlo $yhi $xlo $ylo -fill $tickcolor
    
    set gbw 0
    set gr_w [expr $xhi - $xlo - 1 - $gbw]
    set gr_h [expr $yhi - $ylo - 1 - $gbw]
    set gr_yh [expr $gr_h + $gbw]
    
    if $raisegraph {
        set rg "-relief raised"
    } else {
        set rg ""
    }

    if [info exists colorBand] {
        set bgcolor white
        set txtcolor red
        set fillcolor black
        set outline_width 1.5
    } else {
        set bgcolor black
        set txtcolor white
        set fillcolor green
        set outline_width 1.0
    }
    
    eval canvas $w.graph -width $gr_w -height $gr_h $rg -borderwidth $gbw -background $bgcolor

    if [info exists histo_popup_menu] {
        bind $w.graph <ButtonPress-3> "tk_popup $histo_popup_menu %X %Y"
    }

    set gr_xbase [expr $xlo+1+$gbw]
    set gr_ybase [expr $ylo-1-$gbw]
    place $w.graph -in $w -x $gr_xbase -y $gr_ybase

    if {([info exists ai_environment] && $ai_environment)} {
        if {$place_widget != ""} {
            place $place_widget -in $w -x [expr $xhi+8] -y 0
            raise $place_widget
        }
    } else {
        if {$place_widget != ""} {
            place $place_widget -in $w -x 0 -y 0
            raise $place_widget
        }
    }
    
    set username [cmd_whoami]
    
    # This will show up in the ps but not otherwise.
    
    if $pstitle {
        set upx [expr {$histo_width + 1}]
        set upy [expr {$the_height + 1}]
        $w.background create line -1 -1 -1 $upy -fill white
        $w.background create line -1 $upy $upx $upy -fill white
        $w.background create line $upx $upy $upx -1 -fill white
        $w.background create line $upx -1 -1 -1 -fill white
        $w.background create text $histo_width [expr {$the_height + 4}] \
            -anchor ne -fill white -font $normalfont -text \
            "Plotted by $username@[cmd_uname_n] on [cmd_date], using the $whoami."
    }
    
    # Calculate the largest value in the yvals.  The smallest will be assumed
    # to be 0.  We know that all the y values are integers.
    set ymax 0

    foreach y $yvals {if {$ymax < $y} {set ymax $y}}
    if {$ylimit && ($ymax > $ylimit)} {set ymax $ylimit}
    
    # include the effect of the border width on the X axis of graph
    
    set prevx [expr - ($gbw + 1)]
    set gr_xlo $prevx
    set gr_xhi $gr_w
    
    # Create nylines labels on the Y axis.
    
    set inter [expr {int($ymax / $nylines)}]
    if {!$inter} {
        set inter 2
    } elseif {($inter % 2) != 0} {
        incr inter
    }
    
    # Minor Tick Frequency - twice as often
	
    set minter [expr $inter / 2]
    if {!$minter} {set minter 1}
    
    if {int($ymax) % $inter} {
        set ymax [expr {int($ymax / $inter)}]
        set ymax [expr {($ymax + 1) * $inter}]
    }

    # scale factor for both the indented graph and the
    # outer graph scale is the same.  Compute the effect of
    # the border width on where the origin for the graph (as
    # opposed to the graph axes)
    
    if {$ymax == 0} { set ymax 1 }
    
    set gr_yscale [expr double($yhi - $ylo)/double($ymax)]
    set gr_ylo [expr ($gbw + 1.0)/$gr_yscale]
    
    for {set i 0} {$i <= $ymax} {incr i $inter} {
        set gr_ypos [expr {$gr_yh - int(($i - $gr_ylo)*$gr_yscale)}]
        set ypos [expr $ylo + $gr_ypos - $gbw]
	
        # don't go below y origin of the GRAPH (as opposed to y axis)
        # to create the gray line
	
        if {$dimlines && $gr_ypos <= $gr_yh} {
            $w.graph create line 0 $gr_ypos $gr_xhi $gr_ypos -fill DimGray -width 0
        }
	    
        $w.background create line [expr $xlo-$ticklen] $ypos $xlo $ypos -fill $tickcolor
	
        if [info exists histo_param(yformat)] {
            set yl [format $histo_param(yformat) $i]
        } else {
            set yl $i
        }
        $w.background create text [expr $xlo-$ticklen-2] $ypos -text $i -anchor e -fill $tickcolor -font $normalfont
    }
    
    # add minor tick marks
    
    for {set i 0} {$i <= $ymax} {incr i $minter} {
        set gr_ypos [expr {$gr_yh - int(($i - $gr_ylo)*$gr_yscale)}]
        set ypos [expr $ylo + $gr_ypos - $gbw]	
        $w.background create line [expr $xlo-$ticklen/2] $ypos $xlo $ypos -fill $tickcolor
        
        # don't go below y origin of the GRAPH (as opposed to y axis)
        # to create the gray line
        
        if {$dimlines && $gr_ypos <= $gr_yh} {
            $w.graph create line 0 $gr_ypos $gr_xhi $gr_ypos -fill DimGray -width 0
        }
    }
    
    set num [llength $xvals]
    
    set width [expr {($gr_xhi - $gr_xlo) / $num}]

    # How often do we put labels?  We want <nlabel> labels, let's say.
    
    if {$nlabel > 0} {
        set lfreq [expr {$num / $nlabel}]
        if {$lfreq < 1} {set lfreq 1}
    } else {
        set lfreq 1
    }

    if {([info exists ai_environment] && $ai_environment)} {
        set histo_after_click [list histo_highlight $w 1 $highlight_com $replot_args]
    } else {
        set histo_after_click ""
    }
    if {$title == "Max warp" || $title == "Max warpgls" || $title == "TGrid Skew"} {
        if {![info exists histo_minv] || $histo_minv == ""} {      
            set backup_minx 0.0
        } else {
            set backup_minx $histo_minv
        }
        if {![info exists histo_maxv] || $histo_maxv == ""} {
            if {$title == "Max warp" || $title == "Max warpgls"} {
                set backup_maxx 90.0
            } else {
                set backup_maxx 1.0
            }  
        } else {
            set backup_maxx $histo_maxv
        }
    }
    set histo_minv ""; set histo_maxv ""
    
    set use_more 0
    if {([info exists ai_environment] && $ai_environment)} {
        if {[lindex $xvals end] == 1} {
            if {[expr [lindex $xvals end] - [lindex $xvals 0]] <= 0.05} {
                set use_more 1
            }
        }
    }
 
    for {set i 0} {$i < $num - 1} {incr i} {
        set x [lindex $xvals $i]
        set nx [lindex $xvals [expr int($i + 1)]] ;# bug in tcl?
        set y [lindex $yvals $i]
        # special case -- don't make histogram below GRAPH x origin
        if {$prevx < 0} {
	        set xpos 0
	    } else {
	        set xpos $prevx
	    }
	    set nextx [expr {$prevx + $width}]
	    if [info exists colorBand($i)] {
	        set outcolor $colorBand($i)
	    } else {
	        set outcolor red
	    }
	    if {$y == 0} {
	        set use_outline_width 0
	    } else {
	        set use_outline_width $outline_width
	    }
	    if {!$ylimit || ($y < $ylimit)} {
	        # compute the height of the histogram
	        set height [expr { int(($y-$gr_ylo)*$gr_yscale)} ]
	        if {$height < 0} {set height 0}
	        set id [$w.graph create rectangle $xpos $gr_yh $nextx [expr {$gr_yh - $height}] -fill $fillcolor -outline $outcolor -width $use_outline_width]
	    } else {
	        set height [expr { int(($ylimit-$gr_ylo)*$gr_yscale) }]
	        set id [$w.graph create rectangle $xpos $gr_yh $nextx [expr {$gr_yh - $height}] -fill $fillcolor -outline $outcolor -width $use_outline_width]
	        set xm [expr {($prevx + $nextx + 1) / 2}]
	        $w.graph create line $xm [expr {$gr_ylo + 23}] $xm [expr {$gr_ylo + 3}] -width 5 -arrow last -fill blue
	    }
	    if {$highlight_com != ""} {
	        if {$always_highlight == 1}  {
		        set upd "; $histo_after_click"
	        } else {
		        set upd ""
	        }
	        $w.graph bind $id <ButtonPress-1> "histo_click $w %x %y 1 $upd"
	        $w.graph bind $id <B1-Motion> "histo_click $w %x %y 0 $upd"
	        $w.graph bind $id <ButtonRelease-1> "catch { unset histo_clickedon }"
	    }
	    set histo_ids($i) $id
	    set histo_status($i) 0
	    set histo_minx($i) $x
	    set histo_maxx($i) $nx	
	    set histo_idmap($id) $i
	    set histo_numy($i) $y
	
	    if {($histo_minv == "") || ($x < $histo_minv)} { set histo_minv $x }
	    if {($histo_maxv == "") || ($nx > $histo_maxv)} { set histo_maxv $nx }
	
	    if {!($i % $lfreq)} {
	        set xl [ histo_format $x $use_more]
	        set bx [expr $prevx + $gr_xbase]
	        $w.background create line $bx $yhi $bx [expr {$yhi + $ticklen}] -fill $tickcolor	    
	        $w.background create text $bx [expr {$yhi + $ticklen + 2}] -text $xl -anchor n -fill $tickcolor -font $normalfont
	    }
        set prevx $nextx
    }
    if ![info exists histo_minv_limit] {
        set histo_minv_limit $histo_minv
    }
    if ![info exists histo_maxv_limit] {
        set histo_maxv_limit $histo_maxv
    }
    if {$title == "Max warp" || $title == "Max warpgls" || $title == "TGrid Skew"} {
        set histo_minv $backup_minx
        set histo_maxv $backup_maxx
    }

    # Now put the last tick mark at the high end.
    set xl [ histo_format $nx]
    
    set bx [expr $prevx + $gr_xbase]
    $w.background create line $bx $yhi $bx [expr {$yhi + $ticklen}] -fill $tickcolor
    $w.background create text $bx [expr {$yhi + $ticklen + 2}] -text $xl -anchor n -fill $tickcolor -font $normalfont
    
    # Now add the labels.
    if ![info exists colorBand] {
        set id [$w.graph create text [expr {$gr_xhi / 2}] 5 \
		-text $title -fill $txtcolor -font $bigfont -anchor n]
        $w.graph bind $id <ButtonPress-1> "histo_edit_title $w $id"
    
        set top [expr {[lindex [$w.graph bbox $id] 3] + 3}]
        set leftlim [expr {$gr_xhi + 100}]
        set left $leftlim
        set lids {}
        foreach lab $labels {
            set id [$w.graph create text $leftlim $top -text $lab -anchor nw -fill $txtcolor -font $normalfont]
            lappend lids $id
            set box [$w.graph bbox $id]
            set iw [expr {[lindex $box 2] - [lindex $box 0]}]
            set top [expr {[lindex $box 3] + 3}]
            if {$left + $iw > $gr_w - 10} {
                set left [expr {$gr_w - 10 - $iw}]
            }
	    }
        foreach id $lids {$w.graph move $id [expr {$left - $leftlim}] 0}
    } else {
        set histo_mess "$title "
        append histo_mess "([lindex $labels 0] [lindex $labels 1])"
        status_message "Quality metrics criterion: $histo_mess"
    }
    if ![info exists histo_minv] {
        set histo_minv ""
        set histo_maxv ""
    }
    update
    if {[winfo parent $w] == "."} {
        top_resizable $w 0 0
    }
}

proc histo_replot_cmd {cmd} {
    global histo_replot_changed histo_colorband histo_status
    global hexa_histogram_exist histo_replot hexa_histogram_title
    global histo_minv histo_maxv histo_ylim histo_nbars
    
    catch { unset histo_replot_changed }
    set d [form_init .histo_replot Replot "" {accept reset cancel}]
    if {$d != ""} {
        form_label $d.minl "Min X value" {0 0}
        form_label $d.maxl "Max X value" {1 0}
        form_label $d.heightl "Max Y height" {2 0}
        form_label $d.nbarsl "Num bars" {3 0}
        form_entry $d.min histo_minv float {0 1}
        form_entry $d.max histo_maxv float {1 1}
        form_entry $d.height histo_ylim float {2 1}
        form_entry $d.nbars histo_nbars float {3 1}
        form_finish +500+500
    }
    if {([info exists hexa_histogram_exist] && $hexa_histogram_exist) && [info exists hexa_histogram_title]} {
        if {[info exists histo_replot($hexa_histogram_title,minv)] && $histo_replot($hexa_histogram_title,minv) != ""} {
            set histo_minv $histo_replot($hexa_histogram_title,minv)
        }
        if {[info exists histo_replot($hexa_histogram_title,maxv)] && $histo_replot($hexa_histogram_title,maxv) != ""} {
            set histo_maxv $histo_replot($hexa_histogram_title,maxv)
        }
        if {[info exists histo_replot($hexa_histogram_title,ylim)] && $histo_replot($hexa_histogram_title,ylim) != ""} {
            set histo_ylim $histo_replot($hexa_histogram_title,ylim)
        }
        if {[info exists histo_replot($hexa_histogram_title,nbars)] && $histo_replot($hexa_histogram_title,nbars) != ""} {
            set histo_nbars $histo_replot($hexa_histogram_title,nbars)
        }
    }
    if ![form_wait .histo_replot] return
    set histo_replot_changed 1
    foreach n [lsort -dictionary [array names histo_status]] {
        set histo_status($n) 0
    }
    if {([info exists hexa_histogram_exist] && $hexa_histogram_exist) && [info exists hexa_histogram_title]} {
        set histo_replot($hexa_histogram_title,minv) $histo_minv
        set histo_replot($hexa_histogram_title,maxv) $histo_maxv
        set histo_replot($hexa_histogram_title,ylim) $histo_ylim
        set histo_replot($hexa_histogram_title,nbars) $histo_nbars
        if {[aie_active_dez] == "hexQualityDEZ"} {
            foreach p {minv maxv ylim nbars} {
                hexQualityDEZ set $p [set histo_$p]
            }
        }
    }
    eval $cmd
}

proc histo_reset_cmd {cmd cmd2} {
    global histo_minv histo_minv_limit histo_maxv histo_maxv_limit
    global histo_nbars histo_ylim histo_status histo_bad_elements
    global histo_showit
    
    set histo_minv $histo_minv_limit
    set histo_maxv $histo_maxv_limit
    set histo_nbars 20
    set histo_ylim 0
    if {$histo_maxv != 1.0} {
        set histo_maxv [expr $histo_maxv + 0.000001]
    }
    if [info exists histo_bad_elements] {
        set histo_bad_elements bad
    }
    if [info exists histo_showit] {
        unset histo_showit
    }
    foreach n [lsort -dictionary [array names histo_status]] {
        set histo_status($n) 0
    }
    eval $cmd
    eval $cmd2
}

proc histo_refresh_cmd {cmd arguments} {
    global ai_environment histogram_args histo_title 
    global histo_minv histo_maxv histo_ylim histo_nbars histo_status

    if {[info exists ai_environment] && $ai_environment} {
        foreach n [lsort -dictionary [array names histo_status]] {
            set histo_status($n) 0
        }
        eval aie_smooth_update_histogram \"$histo_title\" $histo_nbars $histo_minv $histo_maxv $histo_ylim \"$arguments\"
        aie_redraw_histogram
        eval $cmd
    }
}

proc histo_click {w x y toggle} {
    global histo_idmap histo_after_click
 
    set id [$w.graph find closest $x $y]
    if {![info exists histo_idmap($id)]} return
    set num $histo_idmap($id)
    if {[histo_click_on_bucket $w $num] == "1"} return
    eval $histo_after_click
}

proc histo_click_on_range {w minv maxv} {
    global histo_maxx histo_minx histo_after_click

    foreach num [lsort -integer [array names histo_minx]] {
	    if {($histo_minx($num) >= $minv) && ($histo_maxx($num) <= $maxv)} {
	        histo_click_on_bucket $w $num
	    }
    }
}

proc histo_click_on_bucket {w num} {
    global histo_ids histo_status histo_clickedon histo_minx histo_maxx
    global histo_numy histo_param histo_status_prev ai_environment
    global histo_color_by_quality colorBand

    if [info exists histo_clickedon($num)] { return 1 }
    set histo_clickedon($num) 1
    if $histo_numy($num) {
	    mess "\t$histo_minx($num) -> $histo_maxx($num), $histo_numy($num) values\n"
    }
    set id $histo_ids($num)  
    if $histo_status($num) {
	    if [info exists colorBand($num)] {
	        $w.graph itemconfigure $id -fill black -outline $colorBand($num)
	    } else {
	        $w.graph itemconfigure $id -fill green	    
	    }
	    set histo_status($num) 0
    } else {
	    if [info exists colorBand($num)] {
	        $w.graph itemconfigure $id -fill $colorBand($num) -outline red
	    } else {
	        $w.graph itemconfigure $id -fill pink
	    }
	    set histo_status($num) 1
    }
    if {[info exists ai_environment] && $ai_environment} {
        if [info exists colorBand(actual_min)] {
	        if [info exist histo_color_by_quality] {
                set colorBand(color_by_quality) $histo_color_by_quality
	        }
            aie_create_colorband $colorBand(actual_min) $colorBand(actual_max) $colorBand(xvals) $colorBand(color_by_quality)
        }
    }
    set histo_status_prev($num) $histo_status($num)
    return 0
}

proc histo_highlight {w force com arguments} {
    global histo_status histo_minx histo_maxx histo_solid histo_numy histo_show
    global histo_color_by_quality ai_environment histo_crit histo_minv histo_maxv histo_colorband
    global hexa_histogram_exist histo_ids histo_showit

    if {[info exists ai_environment] && $ai_environment} {
	    if [info exist histo_color_by_quality] {
	        if {!$histo_color_by_quality} {
		        aie_delete_colorband
	        }
	    }
    }

    set intervals {}
    set num [array size histo_status]
    if {!$force || ($histo_show && [info exists hexa_histogram_exist] && ![info exists histo_colorband])} {
	    set tot 0
	    for {set i 0} {$i < $num} {incr i} {
	        if $histo_status($i) {
		        incr tot $histo_numy($i)
	            if {$tot > 100000 && ![info exists histo_showit]} {
	                set show_them [tk_dialog .showitornot "Total number of elements"  "Total number of elements to show: $tot. Show or skip ?" "" 1 "Show" "Skip"]
	                switch -- $show_them {
                        0 { 
                            set histo_showit 1
                            break
                        }
	                    1 { 
                            set id $histo_ids($i)
                            $w.graph itemconfigure $id -fill green
                            set histo_status($i) 0
                            return
                        }
                    }
                }
	        }
	    }
        if $tot {
            mess "\nTotal number of elements: $tot\n" blue
        }
    }
    for {set i 0} {$i < $num} {incr i} {
        if $histo_status($i) {
	        set min $histo_minx($i)
	        set max $histo_maxx($i)
	        lappend intervals "$min $max"
	    }
    }
    if {([info exists ai_environment] && $ai_environment)} {
        if [info exist histo_color_by_quality] {
            if {[info exists histo_colorband] && $histo_colorband} {
                $com $w $intervals $arguments $histo_solid $histo_show $histo_color_by_quality $histo_crit $histo_minv $histo_maxv
            } else {
                if {$com == "aie_str_plot_histo"} {
                    $com $w $intervals $arguments $histo_solid $histo_show
                } else {
                    $com $w $intervals $arguments $histo_solid $histo_show $histo_color_by_quality
                }
            }
        } else {
	        $com $w $intervals $arguments $histo_solid $histo_show
	    }
    } else {
	    $com $w $intervals $arguments $histo_solid $histo_color_by_quality
    }
}

proc histo_postscript {w} {
    global bigfont normalfont histo_fontmap histo_colormap printer_name
    global histo_param
    
    set histo_fontmap($bigfont) {Times-Roman 24}
    set histo_fontmap($normalfont) {Helvetica 12}
    set histo_colormap(black) "1.0 1.0 1.0 setrgbcolor "
    #set histo_colormap(green) "0.9 0.9 0.9 setrgbcolor "
    set histo_colormap(white) "0 0 0 setrgbcolor "
    #set histo_colormap(blue) "0 0 0 setrgbcolor "
    set histo_colormap(red) "0 0 0 setrgbcolor "
    #set histo_colormap(pink) "0.5 0.5 0.5 setrgbcolor "
    set histo_colormap(DimGray) "0.1 0.1 0.1 setrgbcolor "
    set file [question "Output file?" "PostScript"]
    if {$file == ""} return
    switch [tk_dialog .hardcopy_type Message "Type of picture?" "" -1 Color Grayscale] {
		0 { set col color }
		1 { set col gray }
	}
    $w.graph addtag all all
    set bb [$w.graph bbox all]
    $w.graph postscript -file $file -fontmap histo_fontmap -colormap histo_colormap -rotate 1 -colormode $col \
	    -pagex 5.5i -pagey 4.25i -pageanchor c -x [lindex $bb 0] -y [lindex $bb 1] \
	    -width [expr {[lindex $bb 2] - [lindex $bb 0]}] -height [expr {[lindex $bb 3] - [lindex $bb 1]}]
}

proc histo_replot {w com arguments ylimit} {
    global histo_status histo_minx histo_maxx histo_title histo_param
    global histo_minv histo_maxv histo_minv_limit histo_maxv_limit histo_ylim
    global histo_nbars

    set num $histo_nbars
    if [info exists histo_minv] {
        if {$histo_minv == ""} { set histo_minv $histo_minv_limit }
        if {$histo_maxv == ""} { set histo_maxv $histo_maxv_limit }
	    eval $com \"$histo_title\" $num $histo_minv $histo_maxv $histo_ylim \"$arguments\"
    }
}

proc histo_edit_title {w id} {
    global histo_title histo_param
    
    set title [llast [$w.graph itemconfigure $id -text]]
    set nt [query_enter $w.query "Edit the text for the title" $title]
    if {$nt != "*cancel*"} {
        $w.graph itemconfigure $id -text $nt
        set histo_title $nt
    }
}
