Tk Source Code

Check-in [a7c3cf8b]
Login
Bounty program for improvements to Tcl and certain Tcl packages.
Tcl 2019 Conference, Houston/TX, US, Nov 4-8
Send your abstracts to [email protected]
or submit via the online form by Sep 9.

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:New files from René Zaumseil (branch does not compile at this point).
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | tip-510
Files: files | file ages | folders
SHA3-256: a7c3cf8b677b9f2cfe444356237f41efee6695d9a9be349a0b7366d967cf4309
User & Date: fvogel 2019-04-10 19:22:13
Context
2019-04-11
06:03
Further files from René Zaumseil check-in: 88b11f8b user: fvogel tags: tip-510
2019-04-10
19:22
New files from René Zaumseil (branch does not compile at this point). check-in: a7c3cf8b user: fvogel tags: tip-510
2018-12-15
11:33
New files from René Zaumseil check-in: cc4a0d4c user: fvogel tags: tip-510
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to doc/graph.n.md.

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
..
34
35
36
37
38
39
40

41

42
43
44
45
46
47
48
...
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264

265
266
267
268
269
270
271
...
376
377
378
379
380
381
382



















383
384
385
386
387
388
389
  [-barmode, barMode, BarMode](#-barmode)  
  [-barwidth, barWidth, BarWidth](#-barwidth)  
  [-baseline, baseline, Baseline](#-baseline)  
  [-bottommargin, bottomMargin, Margin](#-bottommargin) *pixels*  
  [-bottomvariable, bottomVariable, BottomVariable](#-bottomvariable)  
  [-bufferelements, bufferElements, BufferElements](#-bufferelements) *boolean*  
  [-buffergraph, bufferGraph, BufferGraph](#-buffergraph)  
  [-style, style, Style](#-style) *line|bar|strip*  
  [-data, data, Data](#-data)  
  [-datacommand, dataCommand, DataCommand](#-datacommand)  
  [-font, font, Font](#-font) *fontName*  
  [-halo, halo, Halo](#-halo) *pixels*  
  [-highlightbackground, highlightBackground, HighlightBackground](#-highlightbackground)  
  [-highlightcolor, highlightColor, HighlightColor](#-highlightcolor)  
  [-highlightthickness, highlightThickness, HighlightThickness](#-highlightthickness)  
  [-invertxy, invertXY, InvertXY](#-invertxy) *boolean*  
  [-justify, justify, Justify](#-justify) *justify*  
................................................................................
  [-plotpadx, plotPadX, PlotPad](#-plotpadx) *pad*  
  [-plotpady, plotPadY, PlotPad](#-plotpadx) *pad*  
  [-plotrelief, plotRelief, Relief](#-plotrelief) *relief*  
  [-relief, relief, Relief](#-relief) *relief*  
  [-rightmargin or -rm, rightMargin, Margin](#-rightmargin) *pixels*  
  [-rightvariable, rightVariable, RightVariable](#-rightvariable)  
  [-shadow, shadow, Shadow](#-shadow)  

  [-takefocus, takeFocus, TakeFocus](#-takefocus)  

  [-title, title, Title](#-title) *text|image*  
  [-topmargin or -tm, topMargin, Margin](#-topmargin) *pixels*  
  [-topvariable, topVariable, TopVariable](#-topvariable)  
*   [DESCRIPTION](#DESCRIPTION)  
*   [WIDGET COMMAND](#WIDGET-COMMAND)  
  [*pathName* **axis**](#pathName-axis) *operation ?arg?...*  
  [*pathName* **binding**](#pathName-binding) *?crosshairs? ?findelement? ?legend? ?zoom?*  
................................................................................
> > Indicates whether an internal pixmap to buffer the display of data elements should be used. If boolean is true, data elements are drawn to an internal pixmap. This option is especially useful when the graph is redrawn frequently while the remains data unchanged (for example, moving a marker across the plot). See the section. The default is 1.

<a name="-buffergraph"></a>
Command-Line Name: **-buffergraph**  
Database Name: **bufferGraph**  
Database Class: **BufferGraph**

<a name="-style"></a>
Command-Line Name: **-style**  
Database Name: **style**  
Database Class: **Style**

The option can only be set on creation time of the new window. The option control the appearance of the widget. Default value is **line**.

> **line**

> > Display X-Y plotchart

> **bar**

> > Display barchart.

> **strip**

> > Display stripchart.

<a name="-data"></a>
Command-Line Name: **-data**  
Database Name: **data**  
Database Class: **Data**

<a name="-datacommand"></a>
Command-Line Name: **-datacommand**  
Database Name: **dataCommand**  
Database Class: **DataCommand**


<a name="-font"></a>
Command-Line Name: **-font**  
Database Name: **font**  
Database Class: **Font**

> > Specifies the font of the graph title. The default is `*-Helvetica-Bold-R-Normal-*-18-180-*`.
................................................................................
Database Class: **RightVariable**

<a name="-shadow"></a>
Command-Line Name: **-shadow**  
Database Name: **shadow**  
Database Class: **Shadow**




















> **-takefocus** *focus*
<a name="-takefocus"></a>
Command-Line Name: **-takefocus**  
Database Name: **takeFocus**  
Database Class: **TakeFocus**

> > Provides information used when moving the focus from window to window via keyboard traversal (e.g., Tab and Shift-Tab). If focus is 0, this means that this window should be skipped entirely during keyboard traversal. 1 means that the this window should always receive the input focus. An empty value means that the traversal scripts make the decision whether to focus on the window. The default is "".






|
<
<







 







>

>







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
|
|

<
<
<
<
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







13
14
15
16
17
18
19
20


21
22
23
24
25
26
27
..
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
...
230
231
232
233
234
235
236



















237
238
239
240
241




242
243
244
245
246
247
248
249
...
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
  [-barmode, barMode, BarMode](#-barmode)  
  [-barwidth, barWidth, BarWidth](#-barwidth)  
  [-baseline, baseline, Baseline](#-baseline)  
  [-bottommargin, bottomMargin, Margin](#-bottommargin) *pixels*  
  [-bottomvariable, bottomVariable, BottomVariable](#-bottomvariable)  
  [-bufferelements, bufferElements, BufferElements](#-bufferelements) *boolean*  
  [-buffergraph, bufferGraph, BufferGraph](#-buffergraph)  
  [-class, class, Class](options.htm#M-class)  


  [-font, font, Font](#-font) *fontName*  
  [-halo, halo, Halo](#-halo) *pixels*  
  [-highlightbackground, highlightBackground, HighlightBackground](#-highlightbackground)  
  [-highlightcolor, highlightColor, HighlightColor](#-highlightcolor)  
  [-highlightthickness, highlightThickness, HighlightThickness](#-highlightthickness)  
  [-invertxy, invertXY, InvertXY](#-invertxy) *boolean*  
  [-justify, justify, Justify](#-justify) *justify*  
................................................................................
  [-plotpadx, plotPadX, PlotPad](#-plotpadx) *pad*  
  [-plotpady, plotPadY, PlotPad](#-plotpadx) *pad*  
  [-plotrelief, plotRelief, Relief](#-plotrelief) *relief*  
  [-relief, relief, Relief](#-relief) *relief*  
  [-rightmargin or -rm, rightMargin, Margin](#-rightmargin) *pixels*  
  [-rightvariable, rightVariable, RightVariable](#-rightvariable)  
  [-shadow, shadow, Shadow](#-shadow)  
  [-style, style, Style](#-style) *line|bar|strip*  
  [-takefocus, takeFocus, TakeFocus](#-takefocus)  
  [-tile, tile, Tile](#-tile)  
  [-title, title, Title](#-title) *text|image*  
  [-topmargin or -tm, topMargin, Margin](#-topmargin) *pixels*  
  [-topvariable, topVariable, TopVariable](#-topvariable)  
*   [DESCRIPTION](#DESCRIPTION)  
*   [WIDGET COMMAND](#WIDGET-COMMAND)  
  [*pathName* **axis**](#pathName-axis) *operation ?arg?...*  
  [*pathName* **binding**](#pathName-binding) *?crosshairs? ?findelement? ?legend? ?zoom?*  
................................................................................
> > Indicates whether an internal pixmap to buffer the display of data elements should be used. If boolean is true, data elements are drawn to an internal pixmap. This option is especially useful when the graph is redrawn frequently while the remains data unchanged (for example, moving a marker across the plot). See the section. The default is 1.

<a name="-buffergraph"></a>
Command-Line Name: **-buffergraph**  
Database Name: **bufferGraph**  
Database Class: **BufferGraph**




















<a name="-class"></a>
Command-Line Name: **-class**  
Database Name: **class**  
Database Class: **Class**





> > Define class for use in getting values from option database.

<a name="-font"></a>
Command-Line Name: **-font**  
Database Name: **font**  
Database Class: **Font**

> > Specifies the font of the graph title. The default is `*-Helvetica-Bold-R-Normal-*-18-180-*`.
................................................................................
Database Class: **RightVariable**

<a name="-shadow"></a>
Command-Line Name: **-shadow**  
Database Name: **shadow**  
Database Class: **Shadow**

<a name="-style"></a>
Command-Line Name: **-style**  
Database Name: **style**  
Database Class: **Style**

The option can only be set on creation time of the new window. The option control the appearance of the widget. Default value is **line**.

> **line**

> > Display X-Y plotchart

> **bar**

> > Display barchart.

> **strip**

> > Display stripchart.

> **-takefocus** *focus*
<a name="-takefocus"></a>
Command-Line Name: **-takefocus**  
Database Name: **takeFocus**  
Database Class: **TakeFocus**

> > Provides information used when moving the focus from window to window via keyboard traversal (e.g., Tab and Shift-Tab). If focus is 0, this means that this window should be skipped entirely during keyboard traversal. 1 means that the this window should always receive the input focus. An empty value means that the traversal scripts make the decision whether to focus on the window. The default is "".

Changes to doc/path.n.md.

17
18
19
20
21
22
23

24
25
26

27
28
29
30
31
32
33
...
187
188
189
190
191
192
193







194
195
196
197
198
199
200
...
208
209
210
211
212
213
214







215
216
217
218
219
220
221
  [-selectbackground, selectBackground, Foreground](options.htm#M-selectbackground)  
  [-selectborderwidth, selectBorderWidth, BorderWidth](options.htm#M-selectborderwidth)  
  [-selectforeground, selectForeground, Background](options.htm#M-selectforeground)  
  [-takefocus, takeFocus, TakeFocus](options.htm#M-takefocus)  
  [-xscrollcommand, xScrollCommand, ScrollCommand](options.htm#M-xscrollcommand)  
  [-yscrollcommand, yScrollCommand, ScrollCommand](options.htm#M-yscrollcommand)  
* [WIDGET-SPECIFIC OPTIONS](#WIDGET-SPECIFIC-OPTIONS)  

  [-closeenough, closeEnough, CloseEnough](#-closeenough)  
  [-confine, confine, Confine](#-confine)  
  [-height, height, Height](#-height)  

  [-scrollregion, scrollRegion, ScrollRegion](#-scrollregion)  
  [-state, state, State](#-state)  
  [-tagstyle, tagstyle, Tagstyle](#-tagstyle)  
  [-width, width, Width](#-width)  
  [-xscrollincrement, xScrollIncrement, ScrollIncrement](#-xscrollincrement)  
  [-yscrollincrement, yScrollIncrement, ScrollIncrement](#-yscrollincrement)  
*   [DESCRIPTION](#DESCRIPTION)  
................................................................................
[-yscrollcommand, yScrollCommand, ScrollCommand](options.htm#M-yscrollcommand)  

See the [options][] manual entry for details on the standard options.

<a name="WIDGET-SPECIFIC-OPTIONS"></a>
## WIDGET-SPECIFIC OPTIONS








<a name="-closeenough"></a>
Command-Line Name: **-closeenough**  
Database Name: **closeEnough**  
Database Class: **CloseEnough**

> Specifies a floating-point value indicating how close the mouse cursor must be to an item before it is considered to be "inside" the item. Defaults to 1.0. 

................................................................................
<a name="-height"></a>
Command-Line Name: **-height**  
Database Name: **height**  
Database Class: **Height**

> Specifies a desired window height that the canvas widget should request from its geometry manager. The value may be specified in any of the forms described in the [COORDINATES][] section below. 








<a name="-scrollregion"></a>
Command-Line Name: **-scrollregion**  
Database Name: **scrollRegion**  
Database Class: **ScrollRegion**

> Specifies a list with four coordinates describing the left, top, right, and bottom coordinates of a rectangular region. This region is used for scrolling purposes and is considered to be the boundary of the information in the canvas. Each of the coordinates may be specified in any of the forms given in the [COORDINATES][] section below. 







>



>







 







>
>
>
>
>
>
>







 







>
>
>
>
>
>
>







17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
...
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
...
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
  [-selectbackground, selectBackground, Foreground](options.htm#M-selectbackground)  
  [-selectborderwidth, selectBorderWidth, BorderWidth](options.htm#M-selectborderwidth)  
  [-selectforeground, selectForeground, Background](options.htm#M-selectforeground)  
  [-takefocus, takeFocus, TakeFocus](options.htm#M-takefocus)  
  [-xscrollcommand, xScrollCommand, ScrollCommand](options.htm#M-xscrollcommand)  
  [-yscrollcommand, yScrollCommand, ScrollCommand](options.htm#M-yscrollcommand)  
* [WIDGET-SPECIFIC OPTIONS](#WIDGET-SPECIFIC-OPTIONS)  
  [-class, class, Class](#-class)  
  [-closeenough, closeEnough, CloseEnough](#-closeenough)  
  [-confine, confine, Confine](#-confine)  
  [-height, height, Height](#-height)  
  [-offset, offset, Offset](#-offset)  
  [-scrollregion, scrollRegion, ScrollRegion](#-scrollregion)  
  [-state, state, State](#-state)  
  [-tagstyle, tagstyle, Tagstyle](#-tagstyle)  
  [-width, width, Width](#-width)  
  [-xscrollincrement, xScrollIncrement, ScrollIncrement](#-xscrollincrement)  
  [-yscrollincrement, yScrollIncrement, ScrollIncrement](#-yscrollincrement)  
*   [DESCRIPTION](#DESCRIPTION)  
................................................................................
[-yscrollcommand, yScrollCommand, ScrollCommand](options.htm#M-yscrollcommand)  

See the [options][] manual entry for details on the standard options.

<a name="WIDGET-SPECIFIC-OPTIONS"></a>
## WIDGET-SPECIFIC OPTIONS

<a name="-class"></a>
Command-Line Name: **-class**  
Database Name: **class**  
Database Class: **Class**

> > Define class for use in getting values from option database.

<a name="-closeenough"></a>
Command-Line Name: **-closeenough**  
Database Name: **closeEnough**  
Database Class: **CloseEnough**

> Specifies a floating-point value indicating how close the mouse cursor must be to an item before it is considered to be "inside" the item. Defaults to 1.0. 

................................................................................
<a name="-height"></a>
Command-Line Name: **-height**  
Database Name: **height**  
Database Class: **Height**

> Specifies a desired window height that the canvas widget should request from its geometry manager. The value may be specified in any of the forms described in the [COORDINATES][] section below. 

<a name="-offset"></a>
Command-Line Name: **-offset**  
Database Name: **offset**  
Database Class: **Offset**

> Stipple offset for outline. 

<a name="-scrollregion"></a>
Command-Line Name: **-scrollregion**  
Database Name: **scrollRegion**  
Database Class: **ScrollRegion**

> Specifies a list with four coordinates describing the left, top, right, and bottom coordinates of a rectangular region. This region is used for scrolling purposes and is considered to be the boundary of the information in the canvas. Each of the coordinates may be specified in any of the forms given in the [COORDINATES][] section below. 

Added doc/tkoWidget.3.md.
















































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# tkoWidget(3) -- oo class like widgets

*   [NAME](#NAME)
*   [SYNOPSIS](#SYNOPSIS)
*   [ARGUMENTS](#ARGUMENTS)  
*   [DESCRIPTION](#DESCRIPTION)  
*   [SEE ALSO](#SEE-ALSO)  
*   [KEYWORDS](#KEYWORDS)  
*   [COPYRIGHT](#COPYRIGHT)  

<a name="NAME"></a>
## NAME

TkoWidgetClassDefine,
TkoWidgetOptionVar,
TkoWidgetOptionGet,
TkoWidgetOptionSet,
TkoWidgetWindow -- tko widget class commands

<a name="SYNOPSIS"></a>
## SYNOPSIS

**#include "tkoWidget.h"**

int **TkoWidgetClassDefine**(*interp,clazz,classname,methods,options*)  
Tk\_Window \***TkoWidgetWindow**(*object*)  
Tcl\_Obj \***TkoWidgetOptionVar**(*object*)  
Tcl\_Obj \***TkoWidgetOptionGet**(*interp,object,option*)  
int **TkoWidgetOptionSet**(*interp,context,option,type,meta,offset*)  

<a name="ARGUMENTS"></a>
## ARGUMENTS

Tcl\_Interp **\*interp** Used interpreter.  
Tcl\_Class **clazz** Oo class of widget.  
Tcl\_Obj **\*classname** Oo class name of widget.  
const Tcl\_MethodType **\*methods** This array defines class methods to create. For creation methods see [Tcl_NewMethod] manpage. If the method name of the first array entry is not NULL it will be used as **constructor**, if the second method name is not NULL it used as **destructor**. Then follow public methods until an entry with an method name equal NULL comes. Then follow private methods until an entry with an method name equal NULL comes.  
const tkoWidgetOptionDefine **\*options** This array contain option definitions.  
Tcl\_Object **object** This is the current object reference.  
Tcl\_Obj **\*option** The name of the used option.  
Tcl\_ObjectContext **context** The context of the current object. Used to get associated object data.  
tkoWidgetOptionType **type** A type used in the common option setting routine.  
Tcl\_ObjectMetadataType **\*meta** The type of metadata attaches to the current object.  
size\_t **offset** Offset of variable to set in the attaches meta data record.  

<a name="DESCRIPTION"></a>
## DESCRIPTION

The **TkoWidgetClassDefine** function can be used to define options and methods of an **tko::widget** subclass.

The **TkoWidgetWindow** function return the address of the internally created Tk\_Window. Subclasses should check the address on NULL after creation. If the Tk\_Window\* at these address is NULL the widget is destroyed and it should not be used.

The **TkoWidgetOptionVar** function return the globally accessible name of the array variable holding the option values. Additionall there is an element "**.**" inside containing the tk widget path name of the widget.

The **TkoWidgetOptionGet** function returns the current value of the given option.

The **TkoWidgetOptionSet** function can be used to check given *option* values and set C record structure fields at the given *offset*. The record will be retrieved using the given *meta* metadata. The *type* must be one of the **tkoWidgetOptionType** described below.

### tkoWidgetOptionDefine

typedef struct tkoWidgetOptionDefine {
    const char *option;    /* Name of option. Starts with "-" minus sign */
    const char *dbname;    /* Option DB name or synonym option if dbclass is NULL */
    const char *dbclass;   /* Option DB class name or NULL for synonym options. */
    const char *defvalue;  /* Default value. */
    const char *proc;      /* If not NULL it is the body of the newly created -option method */
    Tcl_MethodCallProc *method;     /* If not NULL it is the function name of the -option method */
    int flags;             /* if TKO_WIDGETOPTIONREADONLY then option is only setable at creation time */
    tkoWidgetOptionType type;       /* if greater 0 then option type used in common option set method */
    Tcl_ObjectMetadataType *meta;   /* meta data address used in common option set method */
    int offset;            /* offset in meta data struct */
} **tkoWidgetOptionDefine**;

### tkoWidgetOptionType

Suported enum type in the TkowidgetOptinSet() function. In comments is the type of the address pointer.

        TKO_SET_CLASS = 1,     /* (Tcl_Obj **)address */
        TKO_SET_VISUAL, /* (Tcl_Obj **)address */
        TKO_SET_COLORMAP,       /* (Tcl_Obj **)address */
        TKO_SET_USENULL,        /* (Tcl_Obj **)address */
        TKO_SET_CONTAINER,      /* (int *)address */
        TKO_SET_TCLOBJ, /* (Tcl_Obj **)address */
        TKO_SET_XCOLOR, /* (Xcolor **)address */
        TKO_SET_3DBORDER,       /* (Tk_3DBorder *)address */
        TKO_SET_PIXEL,  /* (int *)address */
        TKO_SET_PIXELNONEGATIV, /* (int *)address */
        TKO_SET_PIXELPOSITIV,   /* (int *)address */
        TKO_SET_DOUBLE, /* (double *)address */
        TKO_SET_BOOLEAN,        /* (int *)address */
        TKO_SET_CURSOR, /* (Tk_Cursor *)address */
        TKO_SET_INT,    /* (int *)address */
        TKO_SET_RELIEF, /* (int *)address */
        TKO_SET_ANCHOR, /* (int *)address */
        TKO_SET_WINDOW, /* (Tk_Window *)address */
        TKO_SET_FONT,   /* (Tk_Font *)address */
        TKO_SET_STRING, /* (char **)address */
        TKO_SET_STRINGNULL,     /* (char **)address */
        TKO_SET_SCROLLREGION,   /* (int *[4])address */
        TKO_SET_JUSTIFY /* (Tk_Justify *)address */

<a name="SEE-ALSO"></a>
## SEE ALSO

<a name="KEYWORDS"></a>
## KEYWORDS

canvas, svg, widget

<a name="COPYRIGHT"></a>
## COPYRIGHT

&copy; 2019- René Zaumseil <[email protected]>

BSD style license.

<a name="SEE-ALSO"></a>
## SEE ALSO

[frame][], [labelframe][], [toplevel][], [oo::class][]

<a name="KEYWORDS"></a>
## KEYWORDS

widget, oo

[options]: options.htm
[frame]: frame.htm
[labelframe]: labelframe.htm
[toplevel]: toplevel.htm
[graph]: graph.htm
[path]: path.htm
[Tkpath]: <https://sourceforge.net/projects/tclbitprint/>
[Rbc]: <https://sourceforge.net/projects/rbctoolkit/>


Added doc/tkoWidget.n.md.
























































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# tko::widget(n) -- oo class like widgets

*   [SYNOPSIS](#SYNOPSIS)
*   [TKO STANDARD OPTIONS](#TKO-STANDARD-OPTIONS)  
  [-class, class, Class](#-class)  
  [-screen, screen, Screen](#-screen)  
*   [DESCRIPTION](#DESCRIPTION)  
*   [WIDGET OPTIONS](#WIDGET-OPTIONS)  
*   [WIDGET METHODS](#WIDGET-METHODS)  
*   [TKO WIDGETS](#TKO-WIDGETS)  

*   [KEYWORDS](#KEYWORDS)  
*   [COPYRIGHT](#COPYRIGHT)  

<a name="SYNOPSIS"></a>
## SYNOPSIS

**oo::class create** *widgetClass* {
  {\*}$::tko::unknown ;# define unknown method to support common tk widget style
  superclass *tkoClass* ;# one of the provided tko widget class's
  variable tko ;# array with options *$tko(-option)* and widget path *$tko(.)*
}

The command creates a new Tcl class whose name is *widgetClass*. This command may be used to create new widgets. Each new widget class has as a *tkoClass* as superclass. The common functionality is in the **tko::widget** class. Currently the following *tkoClass* superclasses are provided:

**::tko::toplevel** *pathName ?option value? ..*

**::tko::frame** *pathName ?option value? ..*

**::tko::labelframe** *pathName ?option value? ..*

**::graph** *pathName ?option value? ..*

**::path** *pathName ?option value? ..*

<a name="TKO-STANDARD-OPTIONS"></a>
## TKO STANDARD OPTIONS

<a name="-class"></a>
Command-Line Name: **-class**  
Database Name: **class**  
Database Class: **Class**

> > Define class for use in getting values from option database. Can only be set on widget creation time.

<a name="-screen"></a>
Command-Line Name: **-screen**  
Database Name: **screen**  
Database Class: **Screen**

> > Affect creation of underlying widget structure. If given the created widget will be a toplevel widget.

<a name="DESCRIPTION"></a>
## DESCRIPTION

The **tko::widget** class contain the common widget functionality. To get these functionality you have to create a subclass of the **tko::widget** class. This can only be done in C. To use the functionality on tcl script level the following classes are provided.

<a name="tko-toplevel"></a>
## tko::toplevel

These class contain the functionality of the [toplevel][] widget command.

<a name="tko-frame"></a>
## tko::frame

These class contain the functionality of the [frame][] widget command.

<a name="tko-labelframe"></a>
## tko::labelframe

These class contain the functionality of the [labelframe][] widget command.

<a name="tko-graph"></a>
## graph

These class contain the functionality of the [Rbc][] graph widget command. It is described in detail in the [graph][] manpage.

<a name="tko-path"></a>
## path

These class contain the functionality of the [Tkpath][] widget command. It is described in detail in the [path][] manpage.

<a name="WIDGET-OPTIONS"></a>
### WIDGET OPTIONS

Widget options can be dynamically added and removed at class or object level.

<a name="WIDGET-METHODS"></a>
### WIDGET METHODS

Widget methods can be dynamically added and removed at class or object level.

**NOTE** Do not change *tkoClass*'s behaviour. Instead create your own class and modify it to your need! Or change created widget objects behaviour.

The **tko::widget** class provides the following methods.

<a name="method-constructor"></a>
**constructor {optionlist arglist}**

> The *optionlist* contain a sorted list off option descriptions as described in **configure optonadd**. It will be processed in the **tko::widget** constructor in the given order. It should always start with the "-class" option definition. The necessary *-option* method's should already be exist.

> The *arglist* is the normal *-option value ..* list of all tk widgets.

> Each widget class constructor should call **next** *$optionlist $arglist*!


<a name="method-destructor"></a>
**destructor {}**

> Here you can free your own ressources. Don't forget to call **next**! After **next** the **tko::widget** data are gone (widget path, tko array variable).

<a name="method-cget"></a>
**cget** *option*

> Return the current vlaue of the given *option*.

<a name="method-configure"></a>
**configure** *args*

> **configure**

> > If *args* is empty the method will return a sorted list of all configuration options.

> **configure** *-option*

> > If we have one element in *args* starting with a minus sign ("-") then the method return the configuration list including the current value of the given *-option*.

> **configure** *-option value ..*

> > If we have an even number list in *args* and the first element starts with a minus sign ("-") then the method does configure all the given option-value pairs. If an error occurs the the corresponding element is not set and the method gives an error. Alrready successfull set options remain.

> **configure init**

> > This is an internal function used in constructing new widgets. It is used in the *unknown* method to initialize all options.

> **configure optionadd** *-synonym -option*

> > Add a *-synonym* for a given *-option*. The *-option* needs not to be defined at this time.

> **configure optionadd** *-synonym dbnam dbclass ?default? ?flags?*

> > Add a new option. If ?flags? is equal "1" then the option is readonly and can only be set in this call. Before adding a new option a *-option* method must created. The method will be called without any arguments. The method can access the new value using the *tko(-option)* array variable. If the method throws a n error the array variable will be reset to the old value.

> **configure optiondel** *-option*

> > Delete the given option and unset the entry in the tko array variable. The created *-option* method's are not deleted. This is the task of the caller.

> **configure optionvar**

> > The method return the global varname of the tko array variable holding all option values.

<a name="method-cget"></a>
**_tko_configure**

> This is an virtuel method of the **tko::widget** class. This method will be called at the end of each **configure** *-option value ..* call. It can be implemented in each class to amke necessary changes. If it is implemented it should also call **next** to notify underlying classes.

<a name="KEYWORDS"></a>
## KEYWORDS

canvas, svg, widget

<a name="COPYRIGHT"></a>
## COPYRIGHT

&copy; 2019- René Zaumseil <[email protected]>

BSD style license.

<a name="SEE-ALSO"></a>
## SEE ALSO

[frame][], [labelframe][], [toplevel][], [oo::class][]

<a name="KEYWORDS"></a>
## KEYWORDS

widget, oo

[options]: options.htm
[frame]: frame.htm
[labelframe]: labelframe.htm
[toplevel]: toplevel.htm
[graph]: graph.htm
[path]: path.htm
[Tkpath]: <https://sourceforge.net/projects/tclbitprint/>
[Rbc]: <https://sourceforge.net/projects/rbctoolkit/>


Deleted generic/rbc/rbcBind.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
/*
 * rbcBind.c --
 *
 *      This module implements object binding procedures for the rbc
 *      toolkit.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "rbcInt.h"

/*
 * Binding table procedures.
 */
#define REPICK_IN_PROGRESS (1<<0)
#define LEFT_GRABBED_ITEM  (1<<1)

#define ALL_BUTTONS_MASK \
    (Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask)

#ifndef VirtualEventMask
#define VirtualEventMask    (1L << 30)
#endif

#define ALL_VALID_EVENTS_MASK \
    (ButtonMotionMask | Button1MotionMask | Button2MotionMask | \
     Button3MotionMask | Button4MotionMask | Button5MotionMask | \
     ButtonPressMask | ButtonReleaseMask | EnterWindowMask | \
     LeaveWindowMask | KeyPressMask | KeyReleaseMask | \
     PointerMotionMask | VirtualEventMask)

static int      buttonMasks[] = {
    0,                          /* No buttons pressed */
    Button1Mask, Button2Mask, Button3Mask, Button4Mask, Button5Mask,
};

/*
* Prototypes for procedures referenced only in this file:
*/

static Tk_EventProc BindProc;
static void     DoEvent(
    RbcBindTable * bindPtr,
    XEvent * eventPtr,
    ClientData item,
    ClientData context);
static void     PickCurrentItem(
    RbcBindTable * bindPtr,
    XEvent * eventPtr);

/*
 * How to make drag&drop work?
 *
 *  Right now we generate pseudo <Enter> <Leave> events within
 *  button grab on an object.  They're marked NotifyVirtual instead
 *  of NotifyAncestor.  A better solution: generate new-style
 *  virtual <<DragEnter>> <<DragMotion>> <<DragLeave>> events.
 *  These virtual events don't have to exist as "real" event
 *  sequences, like virtual events do now.
 */

/*
 *--------------------------------------------------------------
 *
 * DoEvent --
 *
 *      This procedure is called to invoke binding processing
 *      for a new event that is associated with the current item
 *      for a legend.
 *
 *      Sets the binding tags for a graph object. This routine is
 *      called by Tk when an event occurs in the graph.  It fills
 *      an array of pointers with bind tag addresses.
 *
 *      The object addresses are strings hashed in one of two tag
 *      tables: one for elements and the another for markers.  Note
 *      that there's only one binding table for elements and markers.
 *      [We don't want to trigger both a marker and element bind
 *      command for the same event.]  But we don't want a marker and
 *      element with the same tag name to activate the others
 *      bindings. A tag "all" for markers should mean all markers, not
 *      all markers and elements.  As a result, element and marker
 *      tags are stored in separate hash tables, which means we can't
 *      generate the same tag address for both an elements and marker,
 *      even if they have the same name.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Depends on the bindings for the legend.  A binding script
 *      could delete an entry, so callers should protect themselves
 *      with Tcl_Preserve and Tcl_Release.
 *
 *--------------------------------------------------------------
 */
static void
DoEvent(
    RbcBindTable * bindPtr,     /* Binding information for widget in
                                 * which event occurred. */
    XEvent * eventPtr,          /* Real or simulated X event that
                                 * is to be processed. */
    ClientData item,            /* Item picked. */
    ClientData context)
{                               /* Context of item.  */
    RbcElement     *elemPtr;
    MakeTagProc    *tagProc;
    RbcGraph       *graphPtr;
    ClientData     *idArray;
    ClientData      tags[32];
    int nIds = 2; /* Always add the name of the object to the tag array. */
    register char **p;

    if ((bindPtr->tkwin == NULL) || (bindPtr->bindingTable == NULL)) {
        return;
    }
    if ((eventPtr->type == KeyPress) || (eventPtr->type == KeyRelease)) {
        item = bindPtr->focusItem;
        context = bindPtr->focusContext;
    }
    if (item == NULL) {
        return;
    }

    /*
     * Invoke the binding system.
     */
    graphPtr = (RbcGraph *) RbcGetBindingData(bindPtr);
    /*
     * Trick:   Markers, elements, and axes have the same first few
     *          fields in their structures, such as "type", "name", or
     *          "tags".  This is so we can look at graph objects
     *          interchangably.  It doesn't matter what we cast the
     *          object to.
     */
    elemPtr = (RbcElement *) item;

    if ((elemPtr->classUid == rbcLineElementUid)
        || (elemPtr->classUid == rbcStripElementUid)
        || (elemPtr->classUid == rbcBarElementUid)) {
        tagProc = RbcMakeElementTag;
    } else if ((elemPtr->classUid == rbcXAxisUid)
        || (elemPtr->classUid == rbcYAxisUid)) {
        tagProc = RbcMakeAxisTag;
    } else {
        tagProc = RbcMakeMarkerTag;
    }

    if (elemPtr->tags != NULL) {
        for (p = elemPtr->tags; *p != NULL; p++) {
            nIds++;
        }
    }
    if (nIds > 32) {
        idArray = (ClientData *) ckalloc(sizeof(ClientData) * nIds);
    } else {
        idArray = tags;
    }
    idArray[0] = (ClientData) (*tagProc) (graphPtr, elemPtr->name);
    idArray[1] = (ClientData)  (*tagProc) (graphPtr, elemPtr->classUid);
    if (nIds > 2) {
        for (p = elemPtr->tags; *p != NULL; p++) {
            idArray[nIds++] = (ClientData) (*tagProc) (graphPtr, *p);
        }
    }
    Tk_BindEvent(bindPtr->bindingTable, eventPtr, bindPtr->tkwin, nIds,idArray);
    if (nIds >= 32) {
        ckfree((char *) idArray);
    }

}

/*
 *--------------------------------------------------------------
 *
 * PickCurrentItem --
 *
 *      Find the topmost item in a legend that contains a given
 *      location and mark the the current item.  If the current
 *      item has changed, generate a fake exit event on the old
 *      current item and a fake enter event on the new current
 *      item.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The current item may change.  If it does, then the commands
 *      associated with item entry and exit could do just about
 *      anything.  A binding script could delete the legend, so
 *      callers should protect themselves with Tcl_Preserve and
 *      Tcl_Release.
 *
 *--------------------------------------------------------------
 */
static void
PickCurrentItem(
    RbcBindTable * bindPtr,     /* Binding table information. */
    XEvent * eventPtr)
{                               /* Event describing location of
                                 * mouse cursor.  Must be EnterWindow,
                                 * LeaveWindow, ButtonRelease, or
                                 * MotionNotify. */
    int             buttonDown;
    ClientData      newItem;
    ClientData      newContext;

    /*
     * Check whether or not a button is down.  If so, we'll log entry
     * and exit into and out of the current item, but not entry into
     * any other item.  This implements a form of grabbing equivalent
     * to what the X server does for windows.
     */
    buttonDown = (bindPtr->state & ALL_BUTTONS_MASK);
    if (!buttonDown) {
        bindPtr->flags &= ~LEFT_GRABBED_ITEM;
    }

    /*
     * Save information about this event in the widget.  The event in
     * the widget is used for two purposes:
     *
     * 1. Event bindings: if the current item changes, fake events are
     *    generated to allow item-enter and item-leave bindings to trigger.
     * 2. Reselection: if the current item gets deleted, can use the
     *    saved event to find a new current item.
     * Translate MotionNotify events into EnterNotify events, since that's
     * what gets reported to item handlers.
     */

    if (eventPtr != &bindPtr->pickEvent) {
        if ((eventPtr->type == MotionNotify)
            || (eventPtr->type == ButtonRelease)) {
            bindPtr->pickEvent.xcrossing.type = EnterNotify;
            bindPtr->pickEvent.xcrossing.serial = eventPtr->xmotion.serial;
            bindPtr->pickEvent.xcrossing.send_event =
                eventPtr->xmotion.send_event;
            bindPtr->pickEvent.xcrossing.display = eventPtr->xmotion.display;
            bindPtr->pickEvent.xcrossing.window = eventPtr->xmotion.window;
            bindPtr->pickEvent.xcrossing.root = eventPtr->xmotion.root;
            bindPtr->pickEvent.xcrossing.subwindow = None;
            bindPtr->pickEvent.xcrossing.time = eventPtr->xmotion.time;
            bindPtr->pickEvent.xcrossing.x = eventPtr->xmotion.x;
            bindPtr->pickEvent.xcrossing.y = eventPtr->xmotion.y;
            bindPtr->pickEvent.xcrossing.x_root = eventPtr->xmotion.x_root;
            bindPtr->pickEvent.xcrossing.y_root = eventPtr->xmotion.y_root;
            bindPtr->pickEvent.xcrossing.mode = NotifyNormal;
            bindPtr->pickEvent.xcrossing.detail = NotifyNonlinear;
            bindPtr->pickEvent.xcrossing.same_screen =
                eventPtr->xmotion.same_screen;
            bindPtr->pickEvent.xcrossing.focus = False;
            bindPtr->pickEvent.xcrossing.state = eventPtr->xmotion.state;
        } else {
            bindPtr->pickEvent = *eventPtr;
        }
    }
    bindPtr->activePick = TRUE;

    /*
     * If this is a recursive call (there's already a partially completed
     * call pending on the stack;  it's in the middle of processing a
     * Leave event handler for the old current item) then just return;
     * the pending call will do everything that's needed.
     */
    if (bindPtr->flags & REPICK_IN_PROGRESS) {
        return;
    }

    /*
     * A LeaveNotify event automatically means that there's no current
     * item, so the check for closest item can be skipped.
     */
    newContext = NULL;
    if (bindPtr->pickEvent.type != LeaveNotify) {
        int             x, y;

        x = bindPtr->pickEvent.xcrossing.x;
        y = bindPtr->pickEvent.xcrossing.y;
        newItem = (*bindPtr->pickProc) (bindPtr->clientData, x, y, &newContext);
    } else {
        newItem = NULL;
    }

    if (((newItem == bindPtr->currentItem)
            && (newContext == bindPtr->currentContext))
        && (!(bindPtr->flags & LEFT_GRABBED_ITEM))) {
        /*
         * Nothing to do:  the current item hasn't changed.
         */
        return;
    }
#ifndef FULLY_SIMULATE_GRAB
    if (((newItem != bindPtr->currentItem)
            || (newContext != bindPtr->currentContext)) && (buttonDown)) {
        bindPtr->flags |= LEFT_GRABBED_ITEM;
        return;
    }
#endif
    /*
     * Simulate a LeaveNotify event on the previous current item and
     * an EnterNotify event on the new current item.  Remove the "current"
     * tag from the previous current item and place it on the new current
     * item.
     */
    if ((bindPtr->currentItem != NULL) && ((newItem != bindPtr->currentItem)
            || (newContext != bindPtr->currentContext))
        && !(bindPtr->flags & LEFT_GRABBED_ITEM)) {
        XEvent          event;

        event = bindPtr->pickEvent;
        event.type = LeaveNotify;

        /*
         * If the event's detail happens to be NotifyInferior the
         * binding mechanism will discard the event.  To be consistent,
         * always use NotifyAncestor.
         */
        event.xcrossing.detail = NotifyAncestor;

        bindPtr->flags |= REPICK_IN_PROGRESS;
        DoEvent(bindPtr, &event, bindPtr->currentItem, bindPtr->currentContext);
        bindPtr->flags &= ~REPICK_IN_PROGRESS;

        /*
         * Note:  during DoEvent above, it's possible that
         * bindPtr->newItem got reset to NULL because the
         * item was deleted.
         */
    }
    if (((newItem != bindPtr->currentItem)
            || (newContext != bindPtr->currentContext)) && (buttonDown)) {
        XEvent          event;

        bindPtr->flags |= LEFT_GRABBED_ITEM;
        event = bindPtr->pickEvent;
        if ((newItem != bindPtr->newItem)
            || (newContext != bindPtr->newContext)) {
            ClientData      savedItem;
            ClientData      savedContext;

            /*
             * Generate <Enter> and <Leave> events for objects during
             * button grabs.  This isn't standard. But for example, it
             * allows one to provide balloon help on the individual
             * entries of the Hierbox widget.
             */
            savedItem = bindPtr->currentItem;
            savedContext = bindPtr->currentContext;
            if (bindPtr->newItem != NULL) {
                event.type = LeaveNotify;
                event.xcrossing.detail = NotifyVirtual /* Ancestor */ ;
                bindPtr->currentItem = bindPtr->newItem;
                DoEvent(bindPtr, &event, bindPtr->newItem, bindPtr->newContext);
            }
            bindPtr->newItem = newItem;
            bindPtr->newContext = newContext;
            if (newItem != NULL) {
                event.type = EnterNotify;
                event.xcrossing.detail = NotifyVirtual /* Ancestor */ ;
                bindPtr->currentItem = newItem;
                DoEvent(bindPtr, &event, newItem, newContext);
            }
            bindPtr->currentItem = savedItem;
            bindPtr->currentContext = savedContext;
        }
        return;
    }
    /*
     * Special note:  it's possible that
     *   bindPtr->newItem == bindPtr->currentItem
     * here.  This can happen, for example, if LEFT_GRABBED_ITEM was set.
     */

    bindPtr->flags &= ~LEFT_GRABBED_ITEM;
    bindPtr->currentItem = bindPtr->newItem = newItem;
    bindPtr->currentContext = bindPtr->newContext = newContext;
    if (bindPtr->currentItem != NULL) {
        XEvent          event;

        event = bindPtr->pickEvent;
        event.type = EnterNotify;
        event.xcrossing.detail = NotifyAncestor;
        DoEvent(bindPtr, &event, newItem, newContext);
    }
}

/*
 *--------------------------------------------------------------
 *
 * BindProc --
 *
 *      This procedure is invoked by the Tk dispatcher to handle
 *      events associated with bindings on items.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Depends on the command invoked as part of the binding
 *      (if there was any).
 *
 *--------------------------------------------------------------
 */
static void
BindProc(
    ClientData clientData,      /* Pointer to widget structure. */
    XEvent * eventPtr)
{                               /* Pointer to X event that just
                                 * happened. */
    RbcBindTable   *bindPtr = clientData;
    int             mask;

    Tcl_Preserve(bindPtr->clientData);

    /*
     * This code below keeps track of the current modifier state in
     * bindPtr->state.  This information is used to defer repicks of
     * the current item while buttons are down.
     */
    switch (eventPtr->type) {
    case ButtonPress:
    case ButtonRelease:
        mask = 0;
        if ((eventPtr->xbutton.button >= Button1)
            && (eventPtr->xbutton.button <= Button5)) {
            mask = buttonMasks[eventPtr->xbutton.button];
        }

        /*
         * For button press events, repick the current item using the
         * button state before the event, then process the event.  For
         * button release events, first process the event, then repick
         * the current item using the button state *after* the event
         * (the button has logically gone up before we change the
         * current item).
         */
        if (eventPtr->type == ButtonPress) {
            /*
             * On a button press, first repick the current item using
             * the button state before the event, the process the event.
             */
            bindPtr->state = eventPtr->xbutton.state;
            PickCurrentItem(bindPtr, eventPtr);
            bindPtr->state ^= mask;
            DoEvent(bindPtr, eventPtr, bindPtr->currentItem,
                bindPtr->currentContext);
        } else {
            /*
             * Button release: first process the event, with the button
             * still considered to be down.  Then repick the current
             * item under the assumption that the button is no longer down.
             */
            bindPtr->state = eventPtr->xbutton.state;
            DoEvent(bindPtr, eventPtr, bindPtr->currentItem,
                bindPtr->currentContext);
            eventPtr->xbutton.state ^= mask;
            bindPtr->state = eventPtr->xbutton.state;
            PickCurrentItem(bindPtr, eventPtr);
            eventPtr->xbutton.state ^= mask;
        }
        break;

    case EnterNotify:
    case LeaveNotify:
        bindPtr->state = eventPtr->xcrossing.state;
        PickCurrentItem(bindPtr, eventPtr);
        break;

    case MotionNotify:
        bindPtr->state = eventPtr->xmotion.state;
        PickCurrentItem(bindPtr, eventPtr);
        DoEvent(bindPtr, eventPtr, bindPtr->currentItem,
            bindPtr->currentContext);
        break;

    case KeyPress:
    case KeyRelease:
        bindPtr->state = eventPtr->xkey.state;
        PickCurrentItem(bindPtr, eventPtr);
        DoEvent(bindPtr, eventPtr, bindPtr->currentItem,
            bindPtr->currentContext);
        break;
    }
    Tcl_Release(bindPtr->clientData);
}

/*
 *--------------------------------------------------------------
 *
 * RbcConfigureBindings --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
RbcConfigureBindings(
    Tcl_Interp * interp,
    RbcBindTable * bindPtr,
    ClientData item,
    int argc,
    const char **argv)
{
    const char     *command;
    unsigned long   mask;
    const char     *seq;

    if (argc == 0) {
        Tk_GetAllBindings(interp, bindPtr->bindingTable, item);
        return TCL_OK;
    }
    if (argc == 1) {
        command = Tk_GetBinding(interp, bindPtr->bindingTable, item, argv[0]);
        if (command == NULL) {
            return TCL_ERROR;
        }
        Tcl_SetObjResult(interp, Tcl_NewStringObj(command, -1));
        return TCL_OK;
    }

    seq = argv[0];
    command = argv[1];

    if (command[0] == '\0') {
        return Tk_DeleteBinding(interp, bindPtr->bindingTable, item, seq);
    }

    if (command[0] == '+') {
        mask =
            Tk_CreateBinding(interp, bindPtr->bindingTable, item, seq,
            command + 1, TRUE);
    } else {
        mask =
            Tk_CreateBinding(interp, bindPtr->bindingTable, item, seq, command,
            FALSE);
    }
    if (mask == 0) {
        return TCL_ERROR;
    }
    if (mask & (unsigned) ~ALL_VALID_EVENTS_MASK) {
        Tk_DeleteBinding(interp, bindPtr->bindingTable, item, seq);
        Tcl_ResetResult(interp);
        Tcl_AppendResult(interp, "requested illegal events; ",
            "only key, button, motion, enter, leave, and virtual ",
            "events may be used", (char *) NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

#if (TCL_MAJOR_VERSION >= 8)

/*
 *--------------------------------------------------------------
 *
 * RbcConfigureBindingsFromObj --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
RbcConfigureBindingsFromObj(
    Tcl_Interp * interp,
    RbcBindTable * bindPtr,
    ClientData item,
    int objc,
    Tcl_Obj * const *objv)
{
    const char     *command;
    unsigned long   mask;
    char           *seq;
    char           *string;

    if (objc == 0) {
        Tk_GetAllBindings(interp, bindPtr->bindingTable, item);
        return TCL_OK;
    }
    string = Tcl_GetString(objv[0]);
    if (objc == 1) {
        command = Tk_GetBinding(interp, bindPtr->bindingTable, item, string);
        if (command == NULL) {
            Tcl_ResetResult(interp);
            Tcl_AppendResult(interp, "invalid binding event \"", string, "\"",
                (char *) NULL);
            return TCL_ERROR;
        }
        Tcl_SetObjResult(interp, Tcl_NewStringObj(command, -1));
        return TCL_OK;
    }

    seq = string;
    command = Tcl_GetString(objv[1]);

    if (command[0] == '\0') {
        return Tk_DeleteBinding(interp, bindPtr->bindingTable, item, seq);
    }

    if (command[0] == '+') {
        mask =
            Tk_CreateBinding(interp, bindPtr->bindingTable, item, seq,
            command + 1, TRUE);
    } else {
        mask =
            Tk_CreateBinding(interp, bindPtr->bindingTable, item, seq, command,
            FALSE);
    }
    if (mask == 0) {
        return TCL_ERROR;
    }
    if (mask & (unsigned) ~ALL_VALID_EVENTS_MASK) {
        Tk_DeleteBinding(interp, bindPtr->bindingTable, item, seq);
        Tcl_ResetResult(interp);
        Tcl_AppendResult(interp, "requested illegal events; ",
            "only key, button, motion, enter, leave, and virtual ",
            "events may be used", (char *) NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}
#endif

/*
 *--------------------------------------------------------------
 *
 * RbcCreateBindingTable --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
RbcBindTable   *
RbcCreateBindingTable(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    ClientData clientData,
    RbcBindPickProc * pickProc)
{
    unsigned int    mask;
    RbcBindTable   *bindPtr;

    bindPtr = RbcCalloc(1, sizeof(RbcBindTable));
    assert(bindPtr);
    bindPtr->clientData = clientData;
    bindPtr->pickProc = pickProc;
    bindPtr->tkwin = tkwin;
    bindPtr->bindingTable = Tk_CreateBindingTable(interp);
    mask =
        (KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
        EnterWindowMask | LeaveWindowMask | PointerMotionMask);
    Tk_CreateEventHandler(tkwin, mask, BindProc, bindPtr);
    return bindPtr;
}

/*
 *--------------------------------------------------------------
 *
 * RbcDestroyBindingTable --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcDestroyBindingTable(
    RbcBindTable * bindPtr)
{
    unsigned int    mask;

    Tk_DeleteBindingTable(bindPtr->bindingTable);
    mask =
        (KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
        EnterWindowMask | LeaveWindowMask | PointerMotionMask);
    Tk_DeleteEventHandler(bindPtr->tkwin, mask, BindProc, bindPtr);
    ckfree((char *) bindPtr);
}

/*
 *--------------------------------------------------------------
 *
 * RbcPickCurrentItem --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcPickCurrentItem(
    RbcBindTable * bindPtr)
{
    if (bindPtr->activePick) {
        PickCurrentItem(bindPtr, &(bindPtr->pickEvent));
    }
}

/*
 *--------------------------------------------------------------
 *
 * RbcDeleteBindings --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcDeleteBindings(
    RbcBindTable * bindPtr,
    ClientData object)
{
    Tk_DeleteAllBindings(bindPtr->bindingTable, object);

    /*
     * If this is the object currently picked, we need to repick one.
     */
    if (bindPtr->currentItem == object) {
        bindPtr->currentItem = NULL;
        bindPtr->currentContext = NULL;
    }
    if (bindPtr->newItem == object) {
        bindPtr->newItem = NULL;
        bindPtr->newContext = NULL;
    }
    if (bindPtr->focusItem == object) {
        bindPtr->focusItem = NULL;
        bindPtr->focusContext = NULL;
    }
}

/*
 *--------------------------------------------------------------
 *
 * RbcMoveBindingTable --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcMoveBindingTable(
    RbcBindTable * bindPtr,
    Tk_Window tkwin)
{
    unsigned int    mask;

    mask =
        (KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
        EnterWindowMask | LeaveWindowMask | PointerMotionMask);
    if (bindPtr->tkwin != NULL) {
        Tk_DeleteEventHandler(bindPtr->tkwin, mask, BindProc, bindPtr);
    }
    Tk_CreateEventHandler(tkwin, mask, BindProc, bindPtr);
    bindPtr->tkwin = tkwin;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted generic/rbc/rbcChain.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*
 * rbcChain.c --
 *
 * The module implements a generic linked list package.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "rbcInt.h"

#ifndef ALIGN
#define ALIGN(a) \
    (((size_t)a + (sizeof(double) - 1)) & (~(sizeof(double) - 1)))
#endif /* ALIGN */

/*
 *----------------------------------------------------------------------
 *
 * RbcChainCreate --
 *
 *      Creates a new linked list (chain) structure and initializes
 *      its pointers;
 *
 * Results:
 *      Returns a pointer to the newly created chain structure.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcChain       *
RbcChainCreate(
    )
{
    RbcChain       *chainPtr;

    chainPtr = (RbcChain *) ckalloc(sizeof(RbcChain));
    if (chainPtr != NULL) {
        RbcChainInit(chainPtr);
    }
    return chainPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainInit --
 *
 *      Initializes a linked list.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcChainInit(
    RbcChain * chainPtr)
{                               /* The chain to initialize */
    chainPtr->nLinks = 0;
    chainPtr->headPtr = chainPtr->tailPtr = NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainLinkAfter --
 *
 *      Inserts an entry following a given entry.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcChainLinkAfter(
    RbcChain * chainPtr,
    RbcChainLink * linkPtr,
    RbcChainLink * afterPtr)
{
    if (chainPtr->headPtr == NULL) {
        chainPtr->tailPtr = chainPtr->headPtr = linkPtr;
    } else {
        if (afterPtr == NULL) {
            /* Prepend to the front of the chain */
            linkPtr->nextPtr = chainPtr->headPtr;
            linkPtr->prevPtr = NULL;
            chainPtr->headPtr->prevPtr = linkPtr;
            chainPtr->headPtr = linkPtr;
        } else {
            linkPtr->nextPtr = afterPtr->nextPtr;
            linkPtr->prevPtr = afterPtr;
            if (afterPtr == chainPtr->tailPtr) {
                chainPtr->tailPtr = linkPtr;
            } else {
                afterPtr->nextPtr->prevPtr = linkPtr;
            }
            afterPtr->nextPtr = linkPtr;
        }
    }
    chainPtr->nLinks++;
}

/*----------------------------------------------------------------------
 *
 * RbcChainLinkBefore --
 *
 *      Inserts a link preceding a given link.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcChainLinkBefore(
    RbcChain * chainPtr,        /* Chain to contain new entry */
    RbcChainLink * linkPtr,     /* New entry to be inserted */
    RbcChainLink * beforePtr)
{                               /* Entry to link before */
    if (chainPtr->headPtr == NULL) {
        chainPtr->tailPtr = chainPtr->headPtr = linkPtr;
    } else {
        if (beforePtr == NULL) {
            /* Append to the end of the chain. */
            linkPtr->nextPtr = NULL;
            linkPtr->prevPtr = chainPtr->tailPtr;
            chainPtr->tailPtr->nextPtr = linkPtr;
            chainPtr->tailPtr = linkPtr;
        } else {
            linkPtr->prevPtr = beforePtr->prevPtr;
            linkPtr->nextPtr = beforePtr;
            if (beforePtr == chainPtr->headPtr) {
                chainPtr->headPtr = linkPtr;
            } else {
                beforePtr->prevPtr->nextPtr = linkPtr;
            }
            beforePtr->prevPtr = linkPtr;
        }
    }
    chainPtr->nLinks++;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainNewLink --
 *
 *      Creates a new link.
 *
 * Results:
 *      The return value is the pointer to the newly created link.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcChainLink   *
RbcChainNewLink(
    )
{
    RbcChainLink   *linkPtr;

    linkPtr = (RbcChainLink *) ckalloc(sizeof(RbcChainLink));
    assert(linkPtr);
    linkPtr->clientData = NULL;
    linkPtr->nextPtr = linkPtr->prevPtr = NULL;
    return linkPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainReset --
 *
 *      Removes all the links from the chain, freeing the memory for
 *      each link.  Memory pointed to by the link (clientData) is not
 *      freed.  It's the caller's responsibility to deallocate it.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcChainReset(
    RbcChain * chainPtr)
{                               /* Chain to clear */
    if (chainPtr != NULL) {
        RbcChainLink   *oldPtr;
        RbcChainLink   *linkPtr = chainPtr->headPtr;

        while (linkPtr != NULL) {
            oldPtr = linkPtr;
            linkPtr = linkPtr->nextPtr;
            ckfree((char *) oldPtr);
        }
        RbcChainInit(chainPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainDestroy
 *
 *      Frees all the nodes from the chain and deallocates the memory
 *      allocated for the chain structure itself.  It's assumed that
 *      the chain was previous allocated by RbcChainCreate.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */
void
RbcChainDestroy(
    RbcChain * chainPtr)
{                               /* The chain to destroy. */
    if (chainPtr != NULL) {
        RbcChainReset(chainPtr);
        ckfree((char *) chainPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainUnlinkLink --
 *
 *      Unlinks a link from the chain. The link is not deallocated,
 *      but only removed from the chain.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcChainUnlinkLink(
    RbcChain * chainPtr,
    RbcChainLink * linkPtr)
{
    /* Indicates if the link is actually removed from the chain. */
    int             unlinked;

    unlinked = FALSE;
    if (chainPtr->headPtr == linkPtr) {
        chainPtr->headPtr = linkPtr->nextPtr;
        unlinked = TRUE;
    }
    if (chainPtr->tailPtr == linkPtr) {
        chainPtr->tailPtr = linkPtr->prevPtr;
        unlinked = TRUE;
    }
    if (linkPtr->nextPtr != NULL) {
        linkPtr->nextPtr->prevPtr = linkPtr->prevPtr;
        unlinked = TRUE;
    }
    if (linkPtr->prevPtr != NULL) {
        linkPtr->prevPtr->nextPtr = linkPtr->nextPtr;
        unlinked = TRUE;
    }
    if (unlinked) {
        chainPtr->nLinks--;
    }
    linkPtr->prevPtr = linkPtr->nextPtr = NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainDeleteLink --
 *
 *      Unlinks and also frees the given link.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcChainDeleteLink(
    RbcChain * chainPtr,
    RbcChainLink * linkPtr)
{
    RbcChainUnlinkLink(chainPtr, linkPtr);
    ckfree((char *) linkPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainAppend --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcChainLink   *
RbcChainAppend(
    RbcChain * chainPtr,
    ClientData clientData)
{
    RbcChainLink   *linkPtr;

    linkPtr = RbcChainNewLink();
    RbcChainLinkBefore(chainPtr, linkPtr, (RbcChainLink *) NULL);
    RbcChainSetValue(linkPtr, clientData);
    return linkPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainPrepend --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcChainLink   *
RbcChainPrepend(
    RbcChain * chainPtr,
    ClientData clientData)
{
    RbcChainLink   *linkPtr;

    linkPtr = RbcChainNewLink();
    RbcChainLinkAfter(chainPtr, linkPtr, (RbcChainLink *) NULL);
    RbcChainSetValue(linkPtr, clientData);
    return linkPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainAllocLink --
 *
 *      Creates a new chain link.  Unlink RbcChainNewLink, this
 *      routine also allocates extra memory in the node for data.
 *
 * Results:
 *      The return value is the pointer to the newly created entry.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcChainLink   *
RbcChainAllocLink(
    unsigned int extraSize)
{
    RbcChainLink   *linkPtr;
    unsigned int    linkSize;

    linkSize = ALIGN(sizeof(RbcChainLink));
    linkPtr = RbcCalloc(1, linkSize + extraSize);
    assert(linkPtr);
    if (extraSize > 0) {
        /* Point clientData at the memory beyond the normal structure. */
        linkPtr->clientData = (ClientData) ((char *) linkPtr + linkSize);
    }
    return linkPtr;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































































































































































































































































































































































































































































































































































































































































Deleted generic/rbc/rbcConfig.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
/*
 * rbcConfig.c --
 *
 *      This module implements custom configuration options for the rbc
 *      toolkit.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "rbcInt.h"

#define PIXELS_NONNEGATIVE	0
#define PIXELS_POSITIVE		1
#define PIXELS_ANY		2

#define COUNT_NONNEGATIVE	0
#define COUNT_POSITIVE		1
#define COUNT_ANY		2

/*
 * ----------------------------------------------------------------------
 *
 * The following enumerated values are used as bit flags.
 *	FILL_NONE		Neither coordinate plane is specified
 *	FILL_X			Horizontal plane.
 *	FILL_Y			Vertical plane.
 *	FILL_BOTH		Both vertical and horizontal planes.
 *
 * ----------------------------------------------------------------------
 */
#define FILL_NONE	0
#define FILL_X		1
#define FILL_Y		2
#define FILL_BOTH	3

static int      StringToFill(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *FillToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcFillOption = {
    StringToFill, FillToString, (ClientData) 0
};

static int      StringToStyle(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *StyleToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcStyleOption = {
    StringToStyle, StyleToString, (ClientData) 0
};

static int      StringToPad(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int offset);
static const char *PadToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcPadOption = {
    StringToPad, PadToString, (ClientData) 0
};

static int      StringToDistance(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *DistanceToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcDistanceOption = {
    StringToDistance, DistanceToString, (ClientData) PIXELS_NONNEGATIVE
};

Tk_CustomOption rbcPositiveDistanceOption = {
    StringToDistance, DistanceToString, (ClientData) PIXELS_POSITIVE
};

Tk_CustomOption rbcAnyDistanceOption = {
    StringToDistance, DistanceToString, (ClientData) PIXELS_ANY
};

static int      StringToCount(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *CountToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcCountOption = {
    StringToCount, CountToString, (ClientData) COUNT_NONNEGATIVE
};

Tk_CustomOption rbcPositiveCountOption = {
    StringToCount, CountToString, (ClientData) COUNT_POSITIVE
};

static int      StringToDashes(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *DashesToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcDashesOption = {
    StringToDashes, DashesToString, (ClientData) 0
};

static int      StringToShadow(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *ShadowToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcShadowOption = {
    StringToShadow, ShadowToString, (ClientData) 0
};

static int      StringToState(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *StateToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcStateOption = {
    StringToState, StateToString, (ClientData) 0
};

static int      StringToList(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *ListToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcListOption = {
    StringToList, ListToString, (ClientData) 0
};

static int      StringToTile(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *value,
    char *widgRec,
    int flags);
static const char *TileToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcTileOption = {
    StringToTile, TileToString, (ClientData) 0
};

static int      GetInt(
    Tcl_Interp * interp,
    const char *string,
    int check,
    int *valuePtr);

/*
 *----------------------------------------------------------------------
 *
 * StringToFill --
 *
 *      Converts the fill style string into its numeric representation.
 *
 *      Valid style strings are:
 *
 *         "none"   Use neither plane.
 *         "x"      X-coordinate plane.
 *         "y"	    Y-coordinate plane.
 *         "both"   Use both coordinate planes.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToFill(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* Fill style string */
    char *widgRec,              /* Cubicle structure record */
    int offset)
{                               /* Offset of style in record */
    int            *fillPtr = (int *) (widgRec + offset);
    unsigned int    length;
    char            c;

    c = string[0];
    length = strlen(string);
    if ((c == 'n') && (strncmp(string, "none", length) == 0)) {
        *fillPtr = FILL_NONE;
    } else if ((c == 'x') && (strncmp(string, "x", length) == 0)) {
        *fillPtr = FILL_X;
    } else if ((c == 'y') && (strncmp(string, "y", length) == 0)) {
        *fillPtr = FILL_Y;
    } else if ((c == 'b') && (strncmp(string, "both", length) == 0)) {
        *fillPtr = FILL_BOTH;
    } else {
        Tcl_AppendResult(interp, "bad argument \"", string,
            "\": should be \"none\", \"x\", \"y\", or \"both\"", (char *) NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * FillToString --
 *
 *      Returns the fill style string based upon the fill flags.
 *
 * Results:
 *      The fill style string is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
FillToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Widget structure record */
    int offset,                 /* Offset of fill in widget record */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Not used. */
    int             fill = *(int *) (widgRec + offset);

    switch (fill) {
    case FILL_X:
        return "x";
    case FILL_Y:
        return "y";
    case FILL_NONE:
        return "none";
    case FILL_BOTH:
        return "both";
    default:
        return "unknown value";
    }
}


/*
 *----------------------------------------------------------------------
 *
 * StringToStyle --
 *
 *      Not possible. throw an error.
 *
 * Results:
 *      Return error message.
 *
 * Side Effects:
 *      None
 *
 *----------------------------------------------------------------------
 */
static int
StringToStyle(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* New string */
    char *widgRec,              /* Structure record */
    int offset)
{                               /* Offset of style in record */
    Tcl_AppendResult(interp, "-style can only be set in constructor", (char *) NULL);
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * StyleToString --
 *
 *      Returns the fill style string based upon the fill flags.
 *
 * Results:
 *      The string is returned.
 *
 * Side Effects:
 *      None
 *
 *----------------------------------------------------------------------
 */
static const char *
StyleToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Widget structure record */
    int offset,                 /* String in widget record */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Not used. */
    return (widgRec + offset);
}


/*
 *----------------------------------------------------------------------
 *
 * RbcGetPixels --
 *
 *      Like Tk_GetPixels, but checks for negative, zero.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcGetPixels(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    int check,                  /* Can be PIXELS_POSITIVE, PIXELS_NONNEGATIVE,
                                 * or PIXELS_ANY, */
    int *valuePtr)
{
    int             length;

    if (Tk_GetPixels(interp, tkwin, string, &length) != TCL_OK) {
        return TCL_ERROR;
    }
    if (length >= SHRT_MAX) {
        Tcl_AppendResult(interp, "bad distance \"", string, "\": ",
            "too big to represent", (char *) NULL);
        return TCL_ERROR;
    }
    switch (check) {
    case PIXELS_NONNEGATIVE:
        if (length < 0) {
            Tcl_AppendResult(interp, "bad distance \"", string, "\": ",
                "can't be negative", (char *) NULL);
            return TCL_ERROR;
        }
        break;
    case PIXELS_POSITIVE:
        if (length <= 0) {
            Tcl_AppendResult(interp, "bad distance \"", string, "\": ",
                "must be positive", (char *) NULL);
            return TCL_ERROR;
        }
        break;
    case PIXELS_ANY:
        break;
    }
    *valuePtr = length;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToDistance --
 *
 *      Like TK_CONFIG_PIXELS, but adds an extra check for negative
 *      values.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToDistance(
    ClientData clientData,      /* Indicated how to check distance */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Window */
    const char *string,         /* Pixel value string */
    char *widgRec,              /* Widget record */
    int offset)
{                               /* Offset of pixel size in record */
    int            *valuePtr = (int *) (widgRec + offset);
    return RbcGetPixels(interp, tkwin, string, (int) clientData, valuePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * DistanceToString --
 *
 *      Returns the string representing the positive pixel size.
 *
 * Results:
 *      The pixel size string is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
DistanceToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Widget structure record */
    int offset,                 /* Offset in widget record */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Not used. */
    int             value = *(int *) (widgRec + offset);
    char           *result;
    char            stringInt[200];

    sprintf(stringInt, "%d", value);
    result = RbcStrdup(stringInt);
    assert(result);
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * GetInt --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetInt(
    Tcl_Interp * interp,
    const char *string,
    int check,                  /* Can be COUNT_POSITIVE, COUNT_NONNEGATIVE,
                                 * or COUNT_ANY, */
    int *valuePtr)
{
    int             count;

    if (Tcl_GetInt(interp, string, &count) != TCL_OK) {
        return TCL_ERROR;
    }
    switch (check) {
    case COUNT_NONNEGATIVE:
        if (count < 0) {
            Tcl_AppendResult(interp, "bad value \"", string, "\": ",
                "can't be negative", (char *) NULL);
            return TCL_ERROR;
        }
        break;
    case COUNT_POSITIVE:
        if (count <= 0) {
            Tcl_AppendResult(interp, "bad value \"", string, "\": ",
                "must be positive", (char *) NULL);
            return TCL_ERROR;
        }
        break;
    case COUNT_ANY:
        break;
    }
    *valuePtr = count;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToCount --
 *
 *      Like TK_CONFIG_PIXELS, but adds an extra check for negative
 *      values.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToCount(
    ClientData clientData,      /* Indicated how to check distance */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* Pixel value string */
    char *widgRec,              /* Widget record */
    int offset)
{                               /* Offset of pixel size in record */
    int            *valuePtr = (int *) (widgRec + offset);
    return GetInt(interp, string, (int) clientData, valuePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * CountToString --
 *
 *      Returns the string representing the positive pixel size.
 *
 * Results:
 *      The pixel size string is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
CountToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Widget structure record */
    int offset,                 /* Offset in widget record */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Not used. */
    int             value = *(int *) (widgRec + offset);
    char           *result;
    char            stringInt[200];

    sprintf(stringInt, "%d", value);
    result = RbcStrdup(stringInt);
    assert(result);
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToPad --
 *
 *      Convert a string into two pad values.  The string may be in one of
 *      the following forms:
 *
 *          n      - n is a non-negative integer. This sets both
 *                   pad values to n.
 *          {n m}  - both n and m are non-negative integers. side1
 *                   is set to n, side2 is set to m.
 *
 * Results:
 *      If the string is successfully converted, TCL_OK is returned.
 *      Otherwise, TCL_ERROR is returned and an error message is left in
 *      interp->result.
 *
 * Side Effects:
 *      The padding structure passed is updated with the new values.
 *
 *----------------------------------------------------------------------
 */
static int
StringToPad(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Window */
    const char *string,         /* Pixel value string */
    char *widgRec,              /* Widget record */
    int offset)
{                               /* Offset of pad in widget */
    RbcPad         *padPtr = (RbcPad *) (widgRec + offset);
    int             nElem;
    int             pad, result;
    const char    **padArr;

    if (Tcl_SplitList(interp, string, &nElem, &padArr) != TCL_OK) {
        return TCL_ERROR;
    }
    result = TCL_ERROR;
    if ((nElem < 1) || (nElem > 2)) {
        Tcl_AppendResult(interp, "wrong # elements in padding list",
            (char *) NULL);
        goto error;
    }
    if (RbcGetPixels(interp, tkwin, padArr[0], PIXELS_NONNEGATIVE,
            &pad) != TCL_OK) {
        goto error;
    }
    padPtr->side1 = pad;
    if ((nElem > 1)
        && (RbcGetPixels(interp, tkwin, padArr[1], PIXELS_NONNEGATIVE,
                &pad) != TCL_OK)) {
        goto error;
    }
    padPtr->side2 = pad;
    result = TCL_OK;

  error:
    ckfree((char *) padArr);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * PadToString --
 *
 *     Converts the two pad values into a Tcl list.  Each pad has two
 *     pixel values.  For vertical pads, they represent the top and bottom
 *     margins.  For horizontal pads, they're the left and right margins.
 *     All pad values are non-negative integers.
 *
 * Results:
 *     The padding list is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
PadToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Structure record */
    int offset,                 /* Offset of pad in record */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Not used. */
    RbcPad         *padPtr = (RbcPad *) (widgRec + offset);
    char           *result;
    char            string[200];

    sprintf(string, "%d %d", padPtr->side1, padPtr->side2);
    result = RbcStrdup(string);
    if (result == NULL) {
        return "out of memory";
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToShadow --
 *
 *      Convert a string into two pad values.  The string may be in one of
 *      the following forms:
 *
 *          n      - n is a non-negative integer. This sets both
 *                   pad values to n.
 *          {n m}  - both n and m are non-negative integers. side1
 *                   is set to n, side2 is set to m.
 *
 * Results:
 *      If the string is successfully converted, TCL_OK is returned.
 *      Otherwise, TCL_ERROR is returned and an error message is left in
 *      interp->result.
 *
 * Side Effects:
 *      The padding structure passed is updated with the new values.
 *
 *----------------------------------------------------------------------
 */
static int
StringToShadow(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Window */
    const char *string,         /* Pixel value string */
    char *widgRec,              /* Widget record */
    int offset)
{                               /* Offset of pad in widget */
    RbcShadow      *shadowPtr = (RbcShadow *) (widgRec + offset);
    XColor         *colorPtr;
    int             dropOffset;

    colorPtr = NULL;
    dropOffset = 0;
    if ((string != NULL) && (string[0] != '\0')) {
        int             nElem;
        const char    **elemArr;

        if (Tcl_SplitList(interp, string, &nElem, &elemArr) != TCL_OK) {
            return TCL_ERROR;
        }
        if ((nElem < 1) || (nElem > 2)) {
            Tcl_AppendResult(interp, "wrong # elements in drop shadow value",
                (char *) NULL);
            ckfree((char *) elemArr);
            return TCL_ERROR;
        }
        colorPtr = Tk_GetColor(interp, tkwin, Tk_GetUid(elemArr[0]));
        if (colorPtr == NULL) {
            ckfree((char *) elemArr);
            return TCL_ERROR;
        }
        dropOffset = 1;
        if (nElem == 2) {
            if (RbcGetPixels(interp, tkwin, elemArr[1], PIXELS_NONNEGATIVE,
                    &dropOffset) != TCL_OK) {
                Tk_FreeColor(colorPtr);
                ckfree((char *) elemArr);
                return TCL_ERROR;
            }
        }
        ckfree((char *) elemArr);
    }
    if (shadowPtr->color != NULL) {
        Tk_FreeColor(shadowPtr->color);
    }
    shadowPtr->color = colorPtr;
    shadowPtr->offset = dropOffset;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ShadowToString --
 *
 *      Converts the two pad values into a Tcl list.  Each pad has two
 *      pixel values.  For vertical pads, they represent the top and bottom
 *      margins.  For horizontal pads, they're the left and right margins.
 *      All pad values are non-negative integers.
 *
 * Results:
 *      The padding list is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
ShadowToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Structure record */
    int offset,                 /* Offset of pad in record */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Not used. */
    RbcShadow      *shadowPtr = (RbcShadow *) (widgRec + offset);
    const char     *result;

    result = "";
    if (shadowPtr->color != NULL) {
        char            string[200];

        sprintf(string, "%s %d", Tk_NameOfColor(shadowPtr->color),
            shadowPtr->offset);
        result = RbcStrdup(string);
        *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * GetDashes --
 *
 *      Converts a Tcl list of dash values into a dash list ready for
 *      use with XSetDashes.
 *
 *      A valid list dash values can have zero through 11 elements
 *      (PostScript limit).  Values must be between 1 and 255. Although
 *      a list of 0 (like the empty string) means no dashes.
 *
 * Results:
 *      A standard Tcl result. If the list represented a valid dash
 *      list TCL_OK is returned and *dashesPtr* will contain the
 *      valid dash list. Otherwise, TCL_ERROR is returned and
 *      interp->result will contain an error message.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetDashes(
    Tcl_Interp * interp,
    const char *string,
    RbcDashes * dashesPtr)
{
    if ((string == NULL) || (*string == '\0')) {
        dashesPtr->values[0] = 0;
    } else if (strcmp(string, "dash") == 0) {
        dashesPtr->values[0] = 5;
        dashesPtr->values[1] = 2;
        dashesPtr->values[2] = 0;
    } else if (strcmp(string, "dot") == 0) {
        dashesPtr->values[0] = 1;
        dashesPtr->values[1] = 0;
    } else if (strcmp(string, "dashdot") == 0) {
        dashesPtr->values[0] = 2;
        dashesPtr->values[1] = 4;
        dashesPtr->values[2] = 2;
        dashesPtr->values[3] = 0;
    } else if (strcmp(string, "dashdotdot") == 0) {
        dashesPtr->values[0] = 2;
        dashesPtr->values[1] = 4;
        dashesPtr->values[2] = 2;
        dashesPtr->values[3] = 2;
        dashesPtr->values[4] = 0;
    } else {
        int             nValues;
        const char    **strArr;
        long int        value;
        register int    i;

        if (Tcl_SplitList(interp, string, &nValues, &strArr) != TCL_OK) {
            return TCL_ERROR;
        }
        if (nValues > 11) {
            /* This is the postscript limit */
            Tcl_AppendResult(interp, "too many values in dash list \"", string,
                "\"", (char *) NULL);
            ckfree((char *) strArr);
            return TCL_ERROR;
        }
        for (i = 0; i < nValues; i++) {
            if (Tcl_ExprLong(interp, strArr[i], &value) != TCL_OK) {
                ckfree((char *) strArr);
                return TCL_ERROR;
            }
            /*
             * Backward compatibility:
             * Allow list of 0 to turn off dashes
             */
            if ((value == 0) && (nValues == 1)) {
                break;
            }
            if ((value < 1) || (value > 255)) {
                Tcl_AppendResult(interp, "dash value \"", strArr[i],
                    "\" is out of range", (char *) NULL);
                ckfree((char *) strArr);
                return TCL_ERROR;
            }
            dashesPtr->values[i] = (unsigned char) value;
        }
        /* Make sure the array ends with a NUL byte  */
        dashesPtr->values[i] = 0;
        ckfree((char *) strArr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToDashes --
 *
 *      Convert the list of dash values into a dashes array.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      The Dashes structure is updated with the new dash list.
 *
 *----------------------------------------------------------------------
 */
static int
StringToDashes(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* New dash value list */
    char *widgRec,              /* Widget record */
    int offset)
{                               /* offset to Dashes structure */
    RbcDashes      *dashesPtr = (RbcDashes *) (widgRec + offset);

    return GetDashes(interp, string, dashesPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * DashesToString --
 *
 *      Convert the dashes array into a list of values.
 *
 * Results:
 *      The string representing the dashes returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
DashesToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Widget record */
    int offset,                 /* offset of Dashes in record */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Memory deallocation scheme to use */
    RbcDashes      *dashesPtr = (RbcDashes *) (widgRec + offset);
    Tcl_DString     dString;
    char           *p;
    char           *result;
    char            stringInt[200];

    if (dashesPtr->values[0] == 0) {
        return "";
    }
    Tcl_DStringInit(&dString);
    for (p = dashesPtr->values; *p != 0; p++) {
        sprintf(stringInt, "%d", *p);
        Tcl_DStringAppendElement(&dString, stringInt);
    }
    result = Tcl_DStringValue(&dString);
    if (result == dString.staticSpace) {
        result = RbcStrdup(result);
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToState --
 *
 *      Converts the string to a state value. Valid states are
 *      disabled, normal.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToState(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* String representation of option value */
    char *widgRec,              /* Widget structure record */
    int offset)
{                               /* Offset of field in record */
    int            *statePtr = (int *) (widgRec + offset);

    if (strcmp(string, "normal") == 0) {
        *statePtr = RBC_STATE_NORMAL;
    } else if (strcmp(string, "disabled") == 0) {
        *statePtr = RBC_STATE_DISABLED;
    } else if (strcmp(string, "active") == 0) {
        *statePtr = RBC_STATE_ACTIVE;
    } else {
        Tcl_AppendResult(interp, "bad state \"", string,
            "\": should be normal, active, or disabled", (char *) NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StateToString --
 *
 *      Returns the string representation of the state configuration field
 *
 * Results:
 *      The string is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
StateToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Widget structure record */
    int offset,                 /* Offset of fill in widget record */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Not used. */
    int             state = *(int *) (widgRec + offset);

    switch (state) {
    case RBC_STATE_ACTIVE:
        return "active";
    case RBC_STATE_DISABLED:
        return "disabled";
    case RBC_STATE_NORMAL:
        return "normal";
    default:
        return "???";
    }
}

/*
 *----------------------------------------------------------------------
 *
 * StringToList --
 *
 *      Converts the string to a list.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToList(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* String representation of option value */
    char *widgRec,              /* Widget structure record */
    int offset)
{                               /* Offset of field in record */
    const char   ***listPtr = (const char ***) (widgRec + offset);
    const char    **elemArr;
    int             nElem;

    if (*listPtr != NULL) {
        ckfree((char *) *listPtr);
        *listPtr = NULL;
    }
    if ((string == NULL) || (*string == '\0')) {
        return TCL_OK;
    }
    if (Tcl_SplitList(interp, string, &nElem, &elemArr) != TCL_OK) {
        return TCL_ERROR;
    }
    if (nElem > 0) {
        *listPtr = elemArr;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ListToString --
 *
 *      Returns the string representation of the state configuration field
 *
 * Results:
 *      The string is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
ListToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Widget structure record. */
    int offset,                 /* Offset of fill in widget record. */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Not used. */
    char          **list = *(char ***) (widgRec + offset);
    register char **p;
    char           *result;
    Tcl_DString     dString;

    if (list == NULL) {
        return "";
    }
    Tcl_DStringInit(&dString);
    for (p = list; *p != NULL; p++) {
        Tcl_DStringAppendElement(&dString, *p);
    }
    result = Tcl_DStringValue(&dString);
    if (result == dString.staticSpace) {
        result = RbcStrdup(result);
    }
    Tcl_DStringFree(&dString);
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToTile --
 *
 *      Converts the name of an image into a tile.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToTile(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Window on same display as tile */
    const char *string,         /* Name of image */
    char *widgRec,              /* Widget structure record */
    int offset)
{                               /* Offset of tile in record */
    RbcTile        *tilePtr = (RbcTile *) (widgRec + offset);
    RbcTile         tile, oldTile;

    oldTile = *tilePtr;
    tile = NULL;
    if ((string != NULL) && (*string != '\0')) {
        if (RbcGetTile(interp, tkwin, string, &tile) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    /* Don't delete the information for the old tile, until we know
     * that we successfully allocated a new one. */
    if (oldTile != NULL) {
        RbcFreeTile(oldTile);
    }
    *tilePtr = tile;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TileToString --
 *
 *      Returns the name of the tile.
 *
 * Results:
 *      The name of the tile is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
TileToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Widget structure record */
    int offset,                 /* Offset of tile in record */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Not used. */
    RbcTile         tile = *(RbcTile *) (widgRec + offset);

    return RbcNameOfTile(tile);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcConfigModified --
 *
 *      Given the configuration specifications and one or more option
 *      patterns (terminated by a NULL), indicate if any of the matching
 *      configuration options has been reset.
 *
 * Results:
 *      Returns 1 if one of the options has changed, 0 otherwise.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcConfigModified(
    Tk_ConfigSpec * specs,
    ...)
{
    va_list         argList;
    register Tk_ConfigSpec *specPtr;
    register char  *option;

    va_start(argList, specs);
    while ((option = va_arg(argList, char *)) != NULL) {
        for (specPtr = specs; specPtr->type != TK_CONFIG_END; specPtr++) {
            if ((Tcl_StringMatch(specPtr->argvName, option))
                && (specPtr->specFlags & TK_CONFIG_OPTION_SPECIFIED)) {
                va_end(argList);
                return 1;
            }
        }
    }
    va_end(argList);
    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcConfigureWidgetComponent --
 *
 *      Configures a component of a widget.  This is useful for
 *      widgets that have multiple components which aren't uniquely
 *      identified by a Tk_Window. It allows us, for example, set
 *      resources for axes of the graph widget. The graph really has
 *      only one window, but its convenient to specify components in a
 *      hierarchy of options.
 *
 *          *graph.x.logScale yes
 *          *graph.Axis.logScale yes
 *          *graph.temperature.scaleSymbols yes
 *          *graph.Element.scaleSymbols yes
 *
 *      This is really a hack to work around the limitations of the Tk
 *      resource database.  It creates a temporary window, needed to
 *      call Tk_ConfigureWidget, using the name of the component.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      A temporary window is created merely to pass to Tk_ConfigureWidget.
 *
 *----------------------------------------------------------------------
 */
int
RbcConfigureWidgetComponent(
    Tcl_Interp * interp,
    Tk_Window parent,           /* Window to associate with component */
    const char resName[],       /* Name of component */
    const char className[],
    const Tk_ConfigSpec * specsPtr,
    int argc,
    const char *argv[],
    char *widgRec,
    int flags)
{
    Tk_Window       tkwin;
    int             result;
    char           *tempName;
    int             isTemporary = FALSE;

    tempName = RbcStrdup(resName);

    /* Window name can't start with an upper case letter */
    tempName[0] = tolower(resName[0]);

    /*
     * Create component if a child window by the component's name
     * doesn't already exist.
     */
    tkwin = RbcFindChild(parent, tempName);
    if (tkwin == NULL) {
        tkwin = Tk_CreateWindow(interp, parent, tempName, (char *) NULL);
        isTemporary = TRUE;
    }
    if (tkwin == NULL) {
        Tcl_AppendResult(interp, "can't find window in \"", Tk_PathName(parent),
            "\"", (char *) NULL);
        return TCL_ERROR;
    }
    assert(Tk_Depth(tkwin) == Tk_Depth(parent));
    ckfree((char *) tempName);

    Tk_SetClass(tkwin, className);
    result =
        Tk_ConfigureWidget(interp, tkwin, specsPtr, argc, argv, widgRec, flags);
    if (isTemporary) {
        Tk_DestroyWindow(tkwin);
    }
    return result;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted generic/rbc/rbcGrAxis.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
/*
 * rbcGrAxis.c --
 *
 *      This module implements coordinate axes for the rbc graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "rbcInt.h"

#define AXIS_CONFIG_MAJOR (1<<4)        /* User specified major tick intervals. */
#define AXIS_CONFIG_MINOR (1<<5)        /* User specified minor tick intervals. */
#define AXIS_ONSCREEN	  (1<<6)        /* Axis is displayed on the screen via
                                         * the "use" operation */
#define AXIS_DIRTY	  (1<<7)
#define AXIS_ALLOW_NULL   (1<<12)

#define DEF_NUM_TICKS		10      /* Each major tick is 10% */
#define STATIC_TICK_SPACE	10

#define TICK_LABEL_SIZE		200
#define MAXTICKS		10001

/*
 * Round x in terms of units
 */
#define UROUND(x,u)		(Round((x)/(u))*(u))
#define UCEIL(x,u)		(ceil((x)/(u))*(u))
#define UFLOOR(x,u)		(floor((x)/(u))*(u))

#define LENGTH_MAJOR_TICK 	0.030   /* Length of a major tick */
#define LENGTH_MINOR_TICK 	0.015   /* Length of a minor (sub)tick */
#define LENGTH_LABEL_TICK 	0.040   /* Distance from graph to start of the
                                         * label */
#define NUMDIGITS		15      /* Specifies the number of
                                         * digits of accuracy used when
                                         * outputting axis tick labels. */
#define AVG_TICK_NUM_CHARS	16      /* Assumed average tick label size */

#define TICK_RANGE_TIGHT	0
#define TICK_RANGE_LOOSE	1
#define TICK_RANGE_ALWAYS_LOOSE	2

#define AXIS_TITLE_PAD		2       /* Padding for axis title. */
#define AXIS_LINE_PAD		1       /* Padding for axis line. */

#define HORIZMARGIN(m)	(!((m)->site & 0x1))    /* Even sites are horizontal */

typedef enum AxisComponents {
    MAJOR_TICK, MINOR_TICK, TICK_LABEL, AXIS_LINE
} AxisComponent;

/*
 * TickLabel --
 *
 * 	Structure containing the X-Y screen coordinates of the tick
 * 	label (anchored at its center).
 */
typedef struct {
    RbcPoint2D      anchorPos;
    int             width, height;
    char            string[1];
} TickLabel;

typedef struct {
    int             axis;       /* Length of the axis.  */
    int             t1;         /* Length of a major tick (in pixels). */
    int             t2;         /* Length of a minor tick (in pixels). */
    int             label;      /* Distance from axis to tick label.  */
} AxisInfo;

extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcPositiveDistanceOption;
extern Tk_CustomOption rbcShadowOption;
extern Tk_CustomOption rbcListOption;

static Tk_OptionParseProc StringToLimit;
static Tk_OptionPrintProc LimitToString;
static Tk_OptionParseProc StringToTicks;
static Tk_OptionPrintProc TicksToString;
static Tk_OptionParseProc StringToAxis;
static Tk_OptionPrintProc AxisToString;
static Tk_OptionParseProc StringToAnyAxis;
static Tk_OptionParseProc StringToFormat;
static Tk_OptionPrintProc FormatToString;
static Tk_OptionParseProc StringToLoose;
static Tk_OptionPrintProc LooseToString;

static Tk_CustomOption limitOption = {
    StringToLimit, LimitToString, (ClientData) 0
};

static Tk_CustomOption majorTicksOption = {
    StringToTicks, TicksToString, (ClientData) AXIS_CONFIG_MAJOR,
};

static Tk_CustomOption minorTicksOption = {
    StringToTicks, TicksToString, (ClientData) AXIS_CONFIG_MINOR,
};

Tk_CustomOption rbcXAxisOption = {
    StringToAxis, AxisToString, (ClientData) & rbcXAxisUid
};

Tk_CustomOption rbcYAxisOption = {
    StringToAxis, AxisToString, (ClientData) & rbcYAxisUid
};

Tk_CustomOption rbcAnyXAxisOption = {
    StringToAnyAxis, AxisToString, (ClientData) & rbcXAxisUid
};

Tk_CustomOption rbcAnyYAxisOption = {
    StringToAnyAxis, AxisToString, (ClientData) & rbcYAxisUid
};

static Tk_CustomOption formatOption = {
    StringToFormat, FormatToString, (ClientData) 0,
};

static Tk_CustomOption looseOption = {
    StringToLoose, LooseToString, (ClientData) 0,
};

/* Axis flags: */

#define DEF_AXIS_COMMAND            (char *)NULL
#define DEF_AXIS_DESCENDING         "no"
#define DEF_AXIS_FOREGROUND         "black"
#define DEF_AXIS_FG_MONO            "black"
#define DEF_AXIS_HIDE               "no"
#define DEF_AXIS_JUSTIFY            "center"
#define DEF_AXIS_LIMITS_FORMAT      (char *)NULL
#define DEF_AXIS_LINE_WIDTH         "1"
#define DEF_AXIS_LOGSCALE           "no"
#define DEF_AXIS_LOOSE              "no"
#define DEF_AXIS_RANGE              "0.0"
#define DEF_AXIS_ROTATE             "0.0"
#define DEF_AXIS_SCROLL_INCREMENT   "10"
#define DEF_AXIS_SHIFTBY            "0.0"
#define DEF_AXIS_SHOWTICKS          "yes"
#define DEF_AXIS_STEP               "0.0"
#define DEF_AXIS_STEP               "0.0"
#define DEF_AXIS_SUBDIVISIONS       "2"
#define DEF_AXIS_TAGS               "all"
#define DEF_AXIS_TICKS              "0"
#define DEF_AXIS_TICK_FONT          RBC_FONT_SMALL
#define DEF_AXIS_TICK_LENGTH        "8"
#define DEF_AXIS_TITLE_ALTERNATE    "0"
#define DEF_AXIS_TITLE_FG           "black"
#define DEF_AXIS_TITLE_FONT         RBC_FONT
#define DEF_AXIS_X_STEP_BARCHART    "1.0"
#define DEF_AXIS_X_SUBDIVISIONS_BARCHART    "0"
#define DEF_AXIS_BACKGROUND         (char *)NULL
#define DEF_AXIS_BORDERWIDTH        "0"
#define DEF_AXIS_RELIEF             "flat"

static Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_DOUBLE, "-autorange", "autoRange", "AutoRange", DEF_AXIS_RANGE,
            Tk_Offset(RbcAxis, windowSize),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_AXIS_BACKGROUND, Tk_Offset(RbcAxis, border),
        RBC_ALL_GRAPHS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, (char *) NULL, 0,
        0},
    {TK_CONFIG_CUSTOM, "-bindtags", "bindTags", "BindTags", DEF_AXIS_TAGS,
            Tk_Offset(RbcAxis, tags), RBC_ALL_GRAPHS | TK_CONFIG_NULL_OK,
        &rbcListOption},
    {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, (char *) NULL, 0,
        RBC_ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-borderwidth", "borderWidth", "BorderWidth",
            DEF_AXIS_BORDERWIDTH, Tk_Offset(RbcAxis, borderWidth),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_COLOR, "-color", "color", "Color", DEF_AXIS_FOREGROUND,
            Tk_Offset(RbcAxis, tickTextStyle.color),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-color", "color", "Color", DEF_AXIS_FG_MONO,
            Tk_Offset(RbcAxis, tickTextStyle.color),
        TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_STRING, "-command", "command", "Command", DEF_AXIS_COMMAND,
        Tk_Offset(RbcAxis, formatCmd), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS},
    {TK_CONFIG_BOOLEAN, "-descending", "descending", "Descending",
            DEF_AXIS_DESCENDING, Tk_Offset(RbcAxis, descending),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide", DEF_AXIS_HIDE,
            Tk_Offset(RbcAxis, hidden),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_JUSTIFY, "-justify", "justify", "Justify", DEF_AXIS_JUSTIFY,
            Tk_Offset(RbcAxis, titleTextStyle.justify),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-labeloffset", "labelOffset", "LabelOffset",
        (char *) NULL, Tk_Offset(RbcAxis, labelOffset), RBC_ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-limitscolor", "limitsColor", "Color",
            DEF_AXIS_FOREGROUND, Tk_Offset(RbcAxis, limitsTextStyle.color),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-limitscolor", "limitsColor", "Color", DEF_AXIS_FG_MONO,
            Tk_Offset(RbcAxis, limitsTextStyle.color),
        TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_FONT, "-limitsfont", "limitsFont", "Font", DEF_AXIS_TICK_FONT,
        Tk_Offset(RbcAxis, limitsTextStyle.font), RBC_ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-limitsformat", "limitsFormat", "LimitsFormat",
            (char *) NULL, Tk_Offset(RbcAxis, limitsFormats),
        TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS, &formatOption},
    {TK_CONFIG_CUSTOM, "-limitsshadow", "limitsShadow", "Shadow", (char *) NULL,
            Tk_Offset(RbcAxis, limitsTextStyle.shadow),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS, &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-limitsshadow", "limitsShadow", "Shadow", (char *) NULL,
            Tk_Offset(RbcAxis, limitsTextStyle.shadow),
        TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS, &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-linewidth", "lineWidth", "LineWidth",
            DEF_AXIS_LINE_WIDTH, Tk_Offset(RbcAxis, lineWidth),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_BOOLEAN, "-logscale", "logScale", "LogScale", DEF_AXIS_LOGSCALE,
            Tk_Offset(RbcAxis, logScale),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-loose", "loose", "Loose", DEF_AXIS_LOOSE, 0,
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT, &looseOption},
    {TK_CONFIG_CUSTOM, "-majorticks", "majorTicks", "MajorTicks", (char *) NULL,
            Tk_Offset(RbcAxis, t1Ptr), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS,
        &majorTicksOption},
    {TK_CONFIG_CUSTOM, "-max", "max", "Max", (char *) NULL, Tk_Offset(RbcAxis,
            reqMax), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS, &limitOption},
    {TK_CONFIG_CUSTOM, "-min", "min", "Min", (char *) NULL, Tk_Offset(RbcAxis,
            reqMin), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS, &limitOption},
    {TK_CONFIG_CUSTOM, "-minorticks", "minorTicks", "MinorTicks", (char *) NULL,
            Tk_Offset(RbcAxis, t2Ptr), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS,
        &minorTicksOption},
    {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", DEF_AXIS_RELIEF,
            Tk_Offset(RbcAxis, relief),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_DOUBLE, "-rotate", "rotate", "Rotate", DEF_AXIS_ROTATE,
            Tk_Offset(RbcAxis, tickTextStyle.theta),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_STRING, "-scrollcommand", "scrollCommand", "ScrollCommand",
            (char *) NULL, Tk_Offset(RbcAxis, scrollCmdPrefix),
        RBC_ALL_GRAPHS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-scrollincrement", "scrollIncrement", "ScrollIncrement",
            DEF_AXIS_SCROLL_INCREMENT, Tk_Offset(RbcAxis, scrollUnits),
            RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT,
        &rbcPositiveDistanceOption},
    {TK_CONFIG_CUSTOM, "-scrollmax", "scrollMax", "ScrollMax", (char *) NULL,
            Tk_Offset(RbcAxis, scrollMax), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS,
        &limitOption},
    {TK_CONFIG_CUSTOM, "-scrollmin", "scrollMin", "ScrollMin", (char *) NULL,
            Tk_Offset(RbcAxis, scrollMin), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS,
        &limitOption},
    {TK_CONFIG_DOUBLE, "-shiftby", "shiftBy", "ShiftBy", DEF_AXIS_SHIFTBY,
            Tk_Offset(RbcAxis, shiftBy),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-showticks", "showTicks", "ShowTicks",
            DEF_AXIS_SHOWTICKS, Tk_Offset(RbcAxis, showTicks),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_DOUBLE, "-stepsize", "stepSize", "StepSize", DEF_AXIS_STEP,
            Tk_Offset(RbcAxis, reqStep),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_DOUBLE, "-tickdivider", "tickDivider", "TickDivider",
            DEF_AXIS_STEP, Tk_Offset(RbcAxis, tickZoom),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_INT, "-subdivisions", "subdivisions", "Subdivisions",
            DEF_AXIS_SUBDIVISIONS, Tk_Offset(RbcAxis, reqNumMinorTicks),
        RBC_ALL_GRAPHS},
    {TK_CONFIG_FONT, "-tickfont", "tickFont", "Font", DEF_AXIS_TICK_FONT,
        Tk_Offset(RbcAxis, tickTextStyle.font), RBC_ALL_GRAPHS},
    {TK_CONFIG_PIXELS, "-ticklength", "tickLength", "TickLength",
            DEF_AXIS_TICK_LENGTH, Tk_Offset(RbcAxis, tickLength),
        RBC_ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-tickshadow", "tickShadow", "Shadow", (char *) NULL,
            Tk_Offset(RbcAxis, tickTextStyle.shadow),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS, &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-tickshadow", "tickShadow", "Shadow", (char *) NULL,
            Tk_Offset(RbcAxis, tickTextStyle.shadow),
        TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS, &rbcShadowOption},
    {TK_CONFIG_STRING, "-title", "title", "Title", (char *) NULL,
            Tk_Offset(RbcAxis, title),
        TK_CONFIG_DONT_SET_DEFAULT | TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS},
    {TK_CONFIG_BOOLEAN, "-titlealternate", "titleAlternate", "TitleAlternate",
            DEF_AXIS_TITLE_ALTERNATE, Tk_Offset(RbcAxis, titleAlternate),
        TK_CONFIG_DONT_SET_DEFAULT | RBC_ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-titlecolor", "titleColor", "Color", DEF_AXIS_FOREGROUND,
            Tk_Offset(RbcAxis, titleTextStyle.color),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-titlecolor", "titleColor", "TitleColor",
            DEF_AXIS_FG_MONO, Tk_Offset(RbcAxis, titleTextStyle.color),
        TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_FONT, "-titlefont", "titleFont", "Font", DEF_AXIS_TITLE_FONT,
        Tk_Offset(RbcAxis, titleTextStyle.font), RBC_ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-titleshadow", "titleShadow", "Shadow", (char *) NULL,
            Tk_Offset(RbcAxis, titleTextStyle.shadow),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS, &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-titleshadow", "titleShadow", "Shadow", (char *) NULL,
            Tk_Offset(RbcAxis, titleTextStyle.shadow),
        TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS, &rbcShadowOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

/* Rotation for each axis title */
static double   titleRotate[4] = {
    0.0, 90.0, 0.0, 270.0
};

/* Forward declarations */
static int      Round(
    register double x);
static void     SetAxisRange(
    RbcAxisRange * rangePtr,
    double min,
    double max);
static int      InRange(
    register double x,
    RbcAxisRange * rangePtr);
static int      AxisIsHorizontal(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr);
static void     FreeLabels(
    RbcChain * chainPtr);
static TickLabel *MakeLabel(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    double value);
static void     GetDataLimits(
    RbcAxis * axisPtr,
    double min,
    double max);
static void     FixAxisRange(
    RbcAxis * axisPtr);
static double   NiceNum(
    double x,
    int round);
static RbcTicks *GenerateTicks(
    RbcTickSweep * sweepPtr);
static void     LogScaleAxis(
    RbcAxis * axisPtr,
    double min,
    double max);
static void     LinearScaleAxis(
    RbcAxis * axisPtr,
    double min,
    double max);
static void     SweepTicks(
    RbcAxis * axisPtr);
static void     ResetTextStyles(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr);
static void     DestroyAxis(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr);
static void     AxisOffsets(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int margin,
    int axisOffset,
    AxisInfo * infoPtr);
static void     MakeAxisLine(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int line,
    RbcSegment2D * segPtr);
static void     MakeTick(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    double value,
    int tick,
    int line,
    RbcSegment2D * segPtr);
static void     MapAxis(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int offset,
    int margin);
static double   AdjustViewport(
    double offset,
    double windowSize);
static int      GetAxisScrollInfo(
    Tcl_Interp * interp,
    int argc,
    const char **argv,
    double *offsetPtr,
    double windowSize,
    double scrollUnits);
static void     DrawAxis(
    RbcGraph * graphPtr,
    Drawable drawable,
    RbcAxis * axisPtr);
static void     AxisToPostScript(
    RbcPsToken * psToken,
    RbcAxis * axisPtr);
static void     MakeGridLine(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    double value,
    RbcSegment2D * segPtr);
static void     GetAxisGeometry(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr);
static int      GetMarginGeometry(
    RbcGraph * graphPtr,
    RbcMargin * marginPtr);
static void     ComputeMargins(
    RbcGraph * graphPtr);
static RbcAxis *CreateAxis(
    RbcGraph * graphPtr,
    const char *name,
    int margin);
static int      ConfigureAxis(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr);
static int      NameToAxis(
    RbcGraph * graphPtr,
    const char *name,
    RbcAxis ** axisPtrPtr);
static int      GetAxis(
    RbcGraph * graphPtr,
    const char *name,
    Tk_Uid classUid,
    RbcAxis ** axisPtrPtr);
static void     FreeAxis(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr);

static int      BindOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int argc,
    const char **argv);
static int      CgetOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int argc,
    const char *argv[]);
static int      ConfigureOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int argc,
    const char *argv[]);
static int      GetOp(
    RbcGraph * graphPtr,
    int argc,
    const char *argv[]);
static int      LimitsOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int argc,
    const char **argv);
static int      InvTransformOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int argc,
    const char **argv);
static int      TransformOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int argc,
    const char **argv);
static int      UseOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int argc,
    const char **argv);
static int      CreateVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv);
static int      BindVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv);
static int      CgetVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv);
static int      ConfigureVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv);
static int      DeleteVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv);
static int      InvTransformVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv);
static int      LimitsVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv);
static int      NamesVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv);
static int      TransformVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv);
static int      ViewOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv);

/*
 *----------------------------------------------------------------------
 *
 * Round --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
Round(
    register double x)
{
    return (int) (x + ((x < 0.0) ? -0.5 : 0.5));
}

/*
 *----------------------------------------------------------------------
 *
 * SetAxisRange --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
SetAxisRange(
    RbcAxisRange * rangePtr,
    double min,
    double max)
{
    rangePtr->min = min;
    rangePtr->max = max;
    rangePtr->range = max - min;
    if (FABS(rangePtr->range) < DBL_EPSILON) {
        rangePtr->range = 1.0;
    }
    rangePtr->scale = 1.0 / rangePtr->range;
}

/*
 * ----------------------------------------------------------------------
 *
 * InRange --
 *
 *      Determines if a value lies within a given range.
 *
 *      The value is normalized and compared against the interval
 *      [0..1], where 0.0 is the minimum and 1.0 is the maximum.
 *      DBL_EPSILON is the smallest number that can be represented
 *      on the host machine, such that (1.0 + epsilon) != 1.0.
 *
 *      Please note, *max* can't equal *min*.
 *
 * Results:
 *      If the value is within the interval [min..max], 1 is
 *      returned; 0 otherwise.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
InRange(
    register double x,
    RbcAxisRange * rangePtr)
{
    if (rangePtr->range < DBL_EPSILON) {
        return (FABS(rangePtr->max - x) >= DBL_EPSILON);
    } else {
        double          norm;

        norm = (x - rangePtr->min) * rangePtr->scale;
        return ((norm >= -DBL_EPSILON) && ((norm - 1.0) < DBL_EPSILON));
    }
}

static int
AxisIsHorizontal(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr)
{
    return ((axisPtr->classUid == rbcYAxisUid) == graphPtr->inverted);
}

/* ----------------------------------------------------------------------
 * Custom option parse and print procedures
 * ----------------------------------------------------------------------
 */

/*
 *----------------------------------------------------------------------
 *
 * StringToAnyAxis --
 *
 *      Converts the name of an axis to a pointer to its axis structure.
 *
 * Results:
 *      The return value is a standard Tcl result.  The axis flags are
 *      written into the widget record.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToAnyAxis(
    ClientData clientData,      /* Class identifier of the type of
                                 * axis we are looking for. */
    Tcl_Interp * interp,        /* Interpreter to send results back to. */
    Tk_Window tkwin,            /* Used to look up pointer to graph. */
    const char *string,         /* String representing new value. */
    char *widgRec,              /* Pointer to structure record. */
    int offset)
{                               /* Offset of field in structure. */
    RbcAxis       **axisPtrPtr = (RbcAxis **) (widgRec + offset);
    Tk_Uid          classUid = *(Tk_Uid *) clientData;
    RbcGraph       *graphPtr;
    RbcAxis        *axisPtr;

    graphPtr = RbcGetGraphFromWindowData(tkwin);
    if (*axisPtrPtr != NULL) {
        FreeAxis(graphPtr, *axisPtrPtr);
    }
    if (string[0] == '\0') {
        axisPtr = NULL;
    } else if (GetAxis(graphPtr, string, classUid, &axisPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    *axisPtrPtr = axisPtr;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToAxis --
 *
 *      Converts the name of an axis to a pointer to its axis structure.
 *
 * Results:
 *      The return value is a standard Tcl result.  The axis flags are
 *      written into the widget record.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToAxis(
    ClientData clientData,      /* Class identifier of the type of
                                 * axis we are looking for. */
    Tcl_Interp * interp,        /* Interpreter to send results back to. */
    Tk_Window tkwin,            /* Used to look up pointer to graph. */
    const char *string,         /* String representing new value. */
    char *widgRec,              /* Pointer to structure record. */
    int offset)
{                               /* Offset of field in structure. */
    RbcAxis       **axisPtrPtr = (RbcAxis **) (widgRec + offset);
    Tk_Uid          classUid = *(Tk_Uid *) clientData;
    RbcGraph       *graphPtr;

    graphPtr = RbcGetGraphFromWindowData(tkwin);
    if (*axisPtrPtr != NULL) {
        FreeAxis(graphPtr, *axisPtrPtr);
    }
    if (GetAxis(graphPtr, string, classUid, axisPtrPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * AxisToString --
 *
 *      Convert the window coordinates into a string.
 *
 * Results:
 *      The string representing the coordinate position is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *----------------------------------------------------------------------
 */
static const char *
AxisToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Pointer to structure record . */
    int offset,                 /* Offset of field in structure. */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Not used. */
    RbcAxis        *axisPtr = *(RbcAxis **) (widgRec + offset);

    if (axisPtr == NULL) {
        return "";
    }
    return axisPtr->name;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToFormat --
 *
 *      Convert the name of virtual axis to an pointer.
 *
 * Results:
 *      The return value is a standard Tcl result.  The axis flags are
 *      written into the widget record.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToFormat(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to. */
    Tk_Window tkwin,            /* Used to look up pointer to graph */
    const char *string,         /* String representing new value. */
    char *widgRec,              /* Pointer to structure record. */
    int offset)
{                               /* Offset of field in structure. */
    RbcAxis        *axisPtr = (RbcAxis *) (widgRec);
    const char    **argv;
    int             argc;

    if (axisPtr->limitsFormats != NULL) {
        ckfree((char *) axisPtr->limitsFormats);
    }
    axisPtr->limitsFormats = NULL;
    axisPtr->nFormats = 0;

    if ((string == NULL) || (*string == '\0')) {
        return TCL_OK;
    }
    if (Tcl_SplitList(interp, string, &argc, &argv) != TCL_OK) {
        return TCL_ERROR;
    }
    if (argc > 2) {
        Tcl_AppendResult(interp, "too many elements in limits format list \"",
            string, "\"", (char *) NULL);
        ckfree((char *) argv);  /*TODO check really? */
        return TCL_ERROR;
    }
    axisPtr->limitsFormats = argv;
    axisPtr->nFormats = argc;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * FormatToString --
 *
 *      Convert the window coordinates into a string.
 *
 * Results:
 *      The string representing the coordinate position is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
FormatToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Widget record */
    int offset,                 /* offset of limits field */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Not used. */
    RbcAxis        *axisPtr = (RbcAxis *) (widgRec);

    if (axisPtr->nFormats == 0) {
        return "";
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return Tcl_Merge(axisPtr->nFormats, axisPtr->limitsFormats);
}

/*
 * ----------------------------------------------------------------------
 *
 * StringToLimit --
 *
 *      Convert the string representation of an axis limit into its numeric
 *      form.
 *
 * Results:
 *      The return value is a standard Tcl result.  The symbol type is
 *      written into the widget record.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
StringToLimit(
    ClientData clientData,      /* Either AXIS_CONFIG_MIN or AXIS_CONFIG_MAX.
                                 * Indicates which axis limit to set. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* String representing new value. */
    char *widgRec,              /* Pointer to structure record. */
    int offset)
{                               /* Offset of field in structure. */
    double         *limitPtr = (double *) (widgRec + offset);

    if ((string == NULL) || (*string == '\0')) {
        *limitPtr = rbcNaN;
    } else if (Tcl_ExprDouble(interp, string, limitPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * LimitToString --
 *
 *      Convert the floating point axis limits into a string.
 *
 * Results:
 *      The string representation of the limits is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static const char *
LimitToString(
    ClientData clientData,      /* Either LMIN or LMAX */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr)
{
    double          limit = *(double *) (widgRec + offset);
    const char     *result;

    result = "";
    if (!TclIsNaN(limit)) {
        char            string[TCL_DOUBLE_SPACE + 1];
        RbcGraph       *graphPtr;

        graphPtr = RbcGetGraphFromWindowData(tkwin);
        Tcl_PrintDouble(graphPtr->interp, limit, string);
        result = RbcStrdup(string);
        if (result == NULL) {
            return "";
        }
        *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    }
    return result;
}

/*
 * ----------------------------------------------------------------------
 *
 * StringToTicks --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
StringToTicks(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* String representing new value. */
    char *widgRec,              /* Pointer to structure record. */
    int offset)
{                               /* Offset of field in structure. */
    unsigned int    mask = (unsigned int) clientData;
    RbcAxis        *axisPtr = (RbcAxis *) widgRec;
    RbcTicks      **ticksPtrPtr = (RbcTicks **) (widgRec + offset);
    int             nTicks;
    RbcTicks       *ticksPtr;

    nTicks = 0;
    ticksPtr = NULL;
    if ((string != NULL) && (*string != '\0')) {
        int             nExprs;
        const char    **exprArr;

        if (Tcl_SplitList(interp, string, &nExprs, &exprArr) != TCL_OK) {
            return TCL_ERROR;
        }
        if (nExprs > 0) {
            register int    i;
            int             result = TCL_ERROR;
            double          value;

            ticksPtr =
                (RbcTicks *) ckalloc(sizeof(RbcTicks) +
                (nExprs * sizeof(double)));
            assert(ticksPtr);
            for (i = 0; i < nExprs; i++) {
                result = Tcl_ExprDouble(interp, exprArr[i], &value);
                if (result != TCL_OK) {
                    break;
                }
                ticksPtr->values[i] = value;
            }
            ckfree((char *) exprArr);
            if (result != TCL_OK) {
                ckfree((char *) ticksPtr);
                return TCL_ERROR;
            }
            nTicks = nExprs;
        }
    }
    axisPtr->flags &= ~mask;
    if (ticksPtr != NULL) {
        axisPtr->flags |= mask;
        ticksPtr->nTicks = nTicks;
    }
    if (*ticksPtrPtr != NULL) {
        ckfree((char *) *ticksPtrPtr);
    }
    *ticksPtrPtr = ticksPtr;
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * TicksToString --
 *
 *      Convert array of tick coordinates to a list.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static const char *
TicksToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr)
{
    RbcTicks       *ticksPtr = *(RbcTicks **) (widgRec + offset);
    char            string[TCL_DOUBLE_SPACE + 1];
    register int    i;
    char           *result;
    Tcl_DString     dString;
    RbcGraph       *graphPtr;

    if (ticksPtr == NULL) {
        return "";
    }
    Tcl_DStringInit(&dString);
    graphPtr = RbcGetGraphFromWindowData(tkwin);
    for (i = 0; i < ticksPtr->nTicks; i++) {
        Tcl_PrintDouble(graphPtr->interp, ticksPtr->values[i], string);
        Tcl_DStringAppendElement(&dString, string);
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    result = RbcStrdup(Tcl_DStringValue(&dString));
    Tcl_DStringFree(&dString);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToLoose --
 *
 *      Convert a string to one of three values.
 *      	0 - false, no, off
 *      	1 - true, yes, on
 *      	2 - always
 *
 * Results:
 *      If the string is successfully converted, TCL_OK is returned.
 *      Otherwise, TCL_ERROR is returned and an error message is left in
 *      interpreter's result field.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToLoose(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* String representing new value. */
    char *widgRec,              /* Pointer to structure record. */
    int offset)
{                               /* Offset of field in structure. */
    RbcAxis        *axisPtr = (RbcAxis *) (widgRec);
    register int    i;
    int             argc;
    const char    **argv;
    int             values[2];

    if (Tcl_SplitList(interp, string, &argc, &argv) != TCL_OK) {
        return TCL_ERROR;
    }
    if ((argc < 1) || (argc > 2)) {
        Tcl_AppendResult(interp, "wrong # elements in loose value \"",
            string, "\"", (char *) NULL);
        return TCL_ERROR;
    }
    for (i = 0; i < argc; i++) {
        if ((argv[i][0] == 'a') && (strcmp(argv[i], "always") == 0)) {
            values[i] = TICK_RANGE_ALWAYS_LOOSE;
        } else {
            int             bool;

            if (Tcl_GetBoolean(interp, argv[i], &bool) != TCL_OK) {
                ckfree((char *) argv);
                return TCL_ERROR;
            }
            values[i] = bool;
        }
    }
    axisPtr->looseMin = axisPtr->looseMax = values[0];
    if (argc > 1) {
        axisPtr->looseMax = values[1];
    }
    ckfree((char *) argv);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * LooseToString --
 *
 *      TODO: Description
 *
 * Results:
 *      The string representation of the auto boolean is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
LooseToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Widget record */
    int offset,                 /* offset of flags field in record */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Memory deallocation scheme to use */
    RbcAxis        *axisPtr = (RbcAxis *) widgRec;
    Tcl_DString     dString;
    char           *result;

    Tcl_DStringInit(&dString);
    if (axisPtr->looseMin == TICK_RANGE_TIGHT) {
        Tcl_DStringAppendElement(&dString, "0");
    } else if (axisPtr->looseMin == TICK_RANGE_LOOSE) {
        Tcl_DStringAppendElement(&dString, "1");
    } else if (axisPtr->looseMin == TICK_RANGE_ALWAYS_LOOSE) {
        Tcl_DStringAppendElement(&dString, "always");
    }
    if (axisPtr->looseMin != axisPtr->looseMax) {
        if (axisPtr->looseMax == TICK_RANGE_TIGHT) {
            Tcl_DStringAppendElement(&dString, "0");
        } else if (axisPtr->looseMax == TICK_RANGE_LOOSE) {
            Tcl_DStringAppendElement(&dString, "1");
        } else if (axisPtr->looseMax == TICK_RANGE_ALWAYS_LOOSE) {
            Tcl_DStringAppendElement(&dString, "always");
        }
    }
    result = RbcStrdup(Tcl_DStringValue(&dString));
    Tcl_DStringFree(&dString);
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * FreeLabels --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
FreeLabels(
    RbcChain * chainPtr)
{
    RbcChainLink   *linkPtr;
    TickLabel      *labelPtr;

    for (linkPtr = RbcChainFirstLink(chainPtr); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        labelPtr = RbcChainGetValue(linkPtr);
        ckfree((char *) labelPtr);
    }
    RbcChainReset(chainPtr);
}

/*
 * ----------------------------------------------------------------------
 *
 * MakeLabel --
 *
 *      Converts a floating point tick value to a string to be used as its
 *      label.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Returns a new label in the string character buffer.  The formatted
 *      tick label will be displayed on the graph.
 *
 * ----------------------------------------------------------------------
 */
static TickLabel *
MakeLabel(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,          /* Axis structure */
    double value)
{                               /* Value to be convert to a decimal string */
    char            string[TICK_LABEL_SIZE + 1];
    TickLabel      *labelPtr;

    /* Generate a default tick label based upon the tick value.  */
    if (axisPtr->logScale) {
        sprintf(string, "1E%d", ROUND(value));
    } else {
        sprintf(string, "%.*g", NUMDIGITS, value);
    }

    if (axisPtr->formatCmd != NULL) {
        Tcl_Interp     *interp = graphPtr->interp;
        Tk_Window       tkwin = graphPtr->tkwin;

        /*
         * A Tcl proc was designated to format tick labels. Append the path
         * name of the widget and the default tick label as arguments when
         * invoking it. Copy and save the new label from interp->result.
         */
        Tcl_ResetResult(interp);
        if (Tcl_VarEval(interp, axisPtr->formatCmd, " ", Tk_PathName(tkwin),
                " ", string, (char *) NULL) != TCL_OK) {
            Tcl_BackgroundError(interp);
        } else {
            /*
             * The proc could return a string of any length, so arbitrarily
             * limit it to what will fit in the return string.
             */
            strncpy(string, Tcl_GetStringResult(interp), TICK_LABEL_SIZE);
            string[TICK_LABEL_SIZE] = '\0';

            Tcl_ResetResult(interp);    /* Clear the interpreter's result. */
        }
    }
    labelPtr = (TickLabel *) ckalloc(sizeof(TickLabel) + strlen(string));
    assert(labelPtr);
    strcpy(labelPtr->string, string);
    labelPtr->anchorPos.x = labelPtr->anchorPos.y = DBL_MAX;
    return labelPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcInvHMap --
 *
 *      Maps the given screen coordinate back to a graph coordinate.
 *      Called by the graph locater routine.
 *
 * Results:
 *      Returns the graph coordinate value at the given window
 *      y-coordinate.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
double
RbcInvHMap(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    double x)
{
    double          value;

    x = (double) (x - graphPtr->hOffset) * graphPtr->hScale;
    if (axisPtr->descending) {
        x = 1.0 - x;
    }
    value = (x * axisPtr->axisRange.range) + axisPtr->axisRange.min;
    if (axisPtr->logScale) {
        value = EXP10(value);
    }
    return value;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcInvVMap --
 *
 *      Maps the given window y-coordinate back to a graph coordinate
 *      value. Called by the graph locater routine.
 *
 * Results:
 *      Returns the graph coordinate value at the given window
 *      y-coordinate.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
double
RbcInvVMap(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    double y)
{
    double          value;

    y = (double) (y - graphPtr->vOffset) * graphPtr->vScale;
    if (axisPtr->descending) {
        y = 1.0 - y;
    }
    value = ((1.0 - y) * axisPtr->axisRange.range) + axisPtr->axisRange.min;
    if (axisPtr->logScale) {
        value = EXP10(value);
    }
    return value;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcHMap --
 *
 *      Map the given graph coordinate value to its axis, returning a window
 *      position.
 *
 * Results:
 *      Returns a double precision number representing the window coordinate
 *      position on the given axis.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
double
RbcHMap(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    double x)
{
    if ((axisPtr->logScale) && (x != 0.0)) {
        x = log10(FABS(x));
    }
    /* Map graph coordinate to normalized coordinates [0..1] */
    x = (x - axisPtr->axisRange.min) * axisPtr->axisRange.scale;
    if (axisPtr->descending) {
        x = 1.0 - x;
    }
    return (x * graphPtr->hRange + graphPtr->hOffset);
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVMap --
 *
 *      Map the given graph coordinate value to its axis, returning a window
 *      position.
 *
 * Results:
 *      Returns a double precision number representing the window coordinate
 *      position on the given axis.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
double
RbcVMap(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    double y)
{
    if ((axisPtr->logScale) && (y != 0.0)) {
        y = log10(FABS(y));
    }
    /* Map graph coordinate to normalized coordinates [0..1] */
    y = (y - axisPtr->axisRange.min) * axisPtr->axisRange.scale;
    if (axisPtr->descending) {
        y = 1.0 - y;
    }
    return (((1.0 - y) * graphPtr->vRange) + graphPtr->vOffset);
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcMap2D --
 *
 *      Maps the given graph x,y coordinate values to a window position.
 *
 * Results:
 *      Returns a XPoint structure containing the window coordinates of
 *      the given graph x,y coordinate.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
RbcPoint2D
RbcMap2D(
    RbcGraph * graphPtr,
    double x,                   /* Graph x coordinate */
    double y,                   /* Graph y coordinate */
    RbcAxis2D * axesPtr)
{                               /* Specifies which axes to use */
    RbcPoint2D      point;

    if (graphPtr->inverted) {
        point.x = RbcHMap(graphPtr, axesPtr->y, y);
        point.y = RbcVMap(graphPtr, axesPtr->x, x);
    } else {
        point.x = RbcHMap(graphPtr, axesPtr->x, x);
        point.y = RbcVMap(graphPtr, axesPtr->y, y);
    }
    return point;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcInvMap2D --
 *
 *      Maps the given window x,y coordinates to graph values.
 *
 * Results:
 *      Returns a structure containing the graph coordinates of
 *      the given window x,y coordinate.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
RbcPoint2D
RbcInvMap2D(
    RbcGraph * graphPtr,
    double x,                   /* Window x coordinate */
    double y,                   /* Window y coordinate */
    RbcAxis2D * axesPtr)
{                               /* Specifies which axes to use */
    RbcPoint2D      point;

    if (graphPtr->inverted) {
        point.x = RbcInvVMap(graphPtr, axesPtr->x, y);
        point.y = RbcInvHMap(graphPtr, axesPtr->y, x);
    } else {
        point.x = RbcInvHMap(graphPtr, axesPtr->x, x);
        point.y = RbcInvVMap(graphPtr, axesPtr->y, y);
    }
    return point;
}

/*
 *----------------------------------------------------------------------
 *
 * GetDataLimits --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
GetDataLimits(
    RbcAxis * axisPtr,
    double min,
    double max)
{
    if (axisPtr->valueRange.min > min) {
        axisPtr->valueRange.min = min;
    }
    if (axisPtr->valueRange.max < max) {
        axisPtr->valueRange.max = max;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * FixAxisRange --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
FixAxisRange(
    RbcAxis * axisPtr)
{
    double          min, max;
    /*
     * When auto-scaling, the axis limits are the bounds of the element
     * data.  If no data exists, set arbitrary limits (wrt to log/linear
     * scale).
     */
    min = axisPtr->valueRange.min;
    max = axisPtr->valueRange.max;

    if (min == DBL_MAX) {
        if (!TclIsNaN(axisPtr->reqMin)) {
            min = axisPtr->reqMin;
        } else {
            min = (axisPtr->logScale) ? 0.001 : 0.0;
        }
    }
    if (max == -DBL_MAX) {
        if (!TclIsNaN(axisPtr->reqMax)) {
            max = axisPtr->reqMax;
        } else {
            max = 1.0;
        }
    }
    if (min >= max) {
        double          value;

        /*
         * There is no range of data (i.e. min is not less than max),
         * so manufacture one.
         */
        value = min;
        if (value == 0.0) {
            min = -0.1, max = 0.1;
        } else {
            double          x;

            x = FABS(value) * 0.1;
            min = value - x, max = value + x;
        }
    }
    SetAxisRange(&axisPtr->valueRange, min, max);

    /*
     * The axis limits are either the current data range or overridden
     * by the values selected by the user with the -min or -max
     * options.
     */
    axisPtr->min = min;
    axisPtr->max = max;
    if (!TclIsNaN(axisPtr->reqMin)) {
        axisPtr->min = axisPtr->reqMin;
    }
    if (!TclIsNaN(axisPtr->reqMax)) {
        axisPtr->max = axisPtr->reqMax;
    }

    if (axisPtr->max < axisPtr->min) {

        /*
         * If the limits still don't make sense, it's because one
         * limit configuration option (-min or -max) was set and the
         * other default (based upon the data) is too small or large.
         * Remedy this by making up a new min or max from the
         * user-defined limit.
         */

        if (TclIsNaN(axisPtr->reqMin)) {
            axisPtr->min = axisPtr->max - (FABS(axisPtr->max) * 0.1);
        }
        if (TclIsNaN(axisPtr->reqMax)) {
            axisPtr->max = axisPtr->min + (FABS(axisPtr->max) * 0.1);
        }
    }
    /*
     * If a window size is defined, handle auto ranging by shifting
     * the axis limits.
     */
    if ((axisPtr->windowSize > 0.0) &&
        (TclIsNaN(axisPtr->reqMin)) && (TclIsNaN(axisPtr->reqMax))) {
        if (axisPtr->shiftBy < 0.0) {
            axisPtr->shiftBy = 0.0;
        }
        max = axisPtr->min + axisPtr->windowSize;
        if (axisPtr->max >= max) {
            if (axisPtr->shiftBy > 0.0) {
                max = UCEIL(axisPtr->max, axisPtr->shiftBy);
            }
            axisPtr->min = max - axisPtr->windowSize;
        }
        axisPtr->max = max;
    }
    if ((axisPtr->max != axisPtr->prevMax) ||
        (axisPtr->min != axisPtr->prevMin)) {
        /* Indicate if the axis limits have changed */
        axisPtr->flags |= AXIS_DIRTY;
        /* and save the previous minimum and maximum values */
        axisPtr->prevMin = axisPtr->min;
        axisPtr->prevMax = axisPtr->max;
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * NiceNum --
 *
 *      Reference: Paul Heckbert, "Nice Numbers for Graph Labels",
 *             Graphics Gems, pp 61-63.
 *
 *      Finds a "nice" number approximately equal to x.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static double
NiceNum(
    double x,
    int round)
{                               /* If non-zero, round. Otherwise take ceiling
                                 * of value. */
    double          expt;       /* Exponent of x */
    double          frac;       /* Fractional part of x */
    double          nice;       /* Nice, rounded fraction */

    expt = floor(log10(x));
    frac = x / EXP10(expt);     /* between 1 and 10 */
    if (round) {
        if (frac < 1.5) {
            nice = 1.0;
        } else if (frac < 3.0) {
            nice = 2.0;
        } else if (frac < 7.0) {
            nice = 5.0;
        } else {
            nice = 10.0;
        }
    } else {
        if (frac <= 1.0) {
            nice = 1.0;
        } else if (frac <= 2.0) {
            nice = 2.0;
        } else if (frac <= 5.0) {
            nice = 5.0;
        } else {
            nice = 10.0;
        }
    }
    return nice * EXP10(expt);
}

/*
 *----------------------------------------------------------------------
 *
 * GenerateTicks --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static RbcTicks *
GenerateTicks(
    RbcTickSweep * sweepPtr)
{
    RbcTicks       *ticksPtr;
    register int    i;

    ticksPtr =
        (RbcTicks *) ckalloc(sizeof(RbcTicks) +
        (sweepPtr->nSteps * sizeof(double)));
    assert(ticksPtr);

    if (sweepPtr->step == 0.0) {
        static double   logTable[] = {  /* Precomputed log10 values [1..10] */
            0.0,
            0.301029995663981, 0.477121254719662,
            0.602059991327962, 0.698970004336019,
            0.778151250383644, 0.845098040014257,
            0.903089986991944, 0.954242509439325,
            1.0
        };
        /* Hack: A zero step indicates to use log values. */
        for (i = 0; i < sweepPtr->nSteps; i++) {
            ticksPtr->values[i] = logTable[i];
        }
    } else {
        double          value;

        value = sweepPtr->initial;      /* Start from smallest axis tick */
        for (i = 0; i < sweepPtr->nSteps; i++) {
            value = UROUND(value, sweepPtr->step);
            ticksPtr->values[i] = value;
            value += sweepPtr->step;
        }
    }
    ticksPtr->nTicks = sweepPtr->nSteps;
    return ticksPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * LogScaleAxis --
 *
 *      Determine the range and units of a log scaled axis.
 *
 *      Unless the axis limits are specified, the axis is scaled
 *      automatically, where the smallest and largest major ticks encompass
 *      the range of actual data values.  When an axis limit is specified,
 *      that value represents the smallest(min)/largest(max) value in the
 *      displayed range of values.
 *
 *      Both manual and automatic scaling are affected by the step used.  By
 *      default, the step is the largest power of ten to divide the range in
 *      more than one piece.
 *
 *      Automatic scaling:
 *      Find the smallest number of units which contain the range of values.
 *      The minimum and maximum major tick values will be represent the
 *      range of values for the axis. This greatest number of major ticks
 *      possible is 10.
 *
 *      Manual scaling:
 *          Make the minimum and maximum data values the represent the range of
 *          the values for the axis.  The minimum and maximum major ticks will be
 *          inclusive of this range.  This provides the largest area for plotting
 *          and the expected results when the axis min and max values have be set
 *          by the user (.e.g zooming).  The maximum number of major ticks is 20.
 *
 *          For log scale, there's the possibility that the minimum and
 *          maximum data values are the same magnitude.  To represent the
 *          points properly, at least one full decade should be shown.
 *          However, if you zoom a log scale plot, the results should be
 *          predictable. Therefore, in that case, show only minor ticks.
 *          Lastly, there should be an appropriate way to handle numbers
 *          <=0.
 *
 *              maxY
 *                |    units = magnitude (of least significant digit)
 *                |    high  = largest unit tick < max axis value
 *          high _|    low   = smallest unit tick > min axis value
 *                |
 *                |    range = high - low
 *                |    # ticks = greatest factor of range/units
 *               _|
 *            U   |
 *            n   |
 *            i   |
 *            t  _|
 *                |
 *                |
 *                |
 *           low _|
 *                |
 *                |_minX________________maxX__
 *                |   |       |      |       |
 *         minY  low                        high
 *               minY
 *
 *
 *      numTicks = Number of ticks
 *      min = Minimum value of axis
 *      max = Maximum value of axis
 *      range    = Range of values (max - min)
 *
 *      If the number of decades is greater than ten, it is assumed
 *      that the full set of log-style ticks can't be drawn properly.
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ---------------------------------------------------------------------- */
static void
LogScaleAxis(
    RbcAxis * axisPtr,
    double min,
    double max)
{
    double          range;
    double          tickMin, tickMax;
    double          majorStep, minorStep;
    int             nMajor, nMinor;

    min = (min != 0.0) ? log10(FABS(min)) : 0.0;
    max = (max != 0.0) ? log10(FABS(max)) : 1.0;

    tickMin = floor(min);
    tickMax = ceil(max);
    range = tickMax - tickMin;

    if (range > 10) {
        /* There are too many decades to display a major tick at every
         * decade.  Instead, treat the axis as a linear scale.  */
        range = NiceNum(range, 0);
        majorStep = NiceNum(range / DEF_NUM_TICKS, 1);
        tickMin = UFLOOR(tickMin, majorStep);
        tickMax = UCEIL(tickMax, majorStep);
        nMajor = (int) ((tickMax - tickMin) / majorStep) + 1;
        minorStep = EXP10(floor(log10(majorStep)));
        if (minorStep == majorStep) {
            nMinor = 4, minorStep = 0.2;
        } else {
            nMinor = Round(majorStep / minorStep) - 1;
        }
    } else {
        if (tickMin == tickMax) {
            tickMax++;
        }
        majorStep = 1.0;
        nMajor = (int) (tickMax - tickMin + 1); /* FIXME: Check this. */

        minorStep = 0.0;        /* This is a special hack to pass
                                 * information to the GenerateTicks
                                 * routine. An interval of 0.0 tells
                                 *      1) this is a minor sweep and
                                 *      2) the axis is log scale.
                                 */
        nMinor = 10;
    }
    if ((axisPtr->looseMin == TICK_RANGE_TIGHT) ||
        ((axisPtr->looseMin == TICK_RANGE_LOOSE) &&
            (!TclIsNaN(axisPtr->reqMin)))) {
        tickMin = min;
        nMajor++;
    }
    if ((axisPtr->looseMax == TICK_RANGE_TIGHT) ||
        ((axisPtr->looseMax == TICK_RANGE_LOOSE) &&
            (!TclIsNaN(axisPtr->reqMax)))) {
        tickMax = max;
    }
    axisPtr->majorSweep.step = majorStep;
    axisPtr->majorSweep.initial = floor(tickMin);
    axisPtr->majorSweep.nSteps = nMajor;
    axisPtr->minorSweep.initial = axisPtr->minorSweep.step = minorStep;
    axisPtr->minorSweep.nSteps = nMinor;

    SetAxisRange(&axisPtr->axisRange, tickMin, tickMax);
}

/*
 * ----------------------------------------------------------------------
 *
 * LinearScaleAxis --
 *
 *      Determine the units of a linear scaled axis.
 *
 *      The axis limits are either the range of the data values mapped
 *      to the axis (autoscaled), or the values specified by the -min
 *      and -max options (manual).
 *
 *      If autoscaled, the smallest and largest major ticks will
 *      encompass the range of data values.  If the -loose option is
 *      selected, the next outer ticks are choosen.  If tight, the
 *      ticks are at or inside of the data limits are used.
 *
 *      If manually set, the ticks are at or inside the data limits
 *      are used.  This makes sense for zooming.  You want the
 *      selected range to represent the next limit, not something a
 *      bit bigger.
 *
 *      Note: I added an "always" value to the -loose option to force
 *            the manually selected axes to be loose. It's probably
 *            not a good idea.
 *
 *              maxY
 *                |    units = magnitude (of least significant digit)
 *                |    high  = largest unit tick < max axis value
 *          high _|    low   = smallest unit tick > min axis value
 *                |
 *                |    range = high - low
 *                |    # ticks = greatest factor of range/units
 *               _|
 *            U   |
 *            n   |
 *            i   |
 *            t  _|
 *                |
 *                |
 *                |
 *           low _|
 *                |
 *                |_minX________________maxX__
 *                |   |       |      |       |
 *         minY  low                        high
 *               minY
 *
 *      numTicks = Number of ticks
 *      min = Minimum value of axis
 *      max = Maximum value of axis
 *      range    = Range of values (max - min)
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      The axis tick information is set.  The actual tick values will
 *      be generated later.
 *
 * ----------------------------------------------------------------------
 */
static void
LinearScaleAxis(
    RbcAxis * axisPtr,
    double min,
    double max)
{
    double          range, step;
    double          tickMin, tickMax;
    double          axisMin, axisMax;
    int             nTicks;

    range = max - min;

    /* Calculate the major tick stepping. */
    if (axisPtr->reqStep > 0.0) {
        /* An interval was designated by the user.  Keep scaling it
         * until it fits comfortably within the current range of the
         * axis.  */
        step = axisPtr->reqStep;
        while ((2 * step) >= range) {
            step *= 0.5;
        }
    } else {
        range = NiceNum(range, 0);
        step = NiceNum(range / DEF_NUM_TICKS, 1);
    }

    /* Find the outer tick values. Add 0.0 to prevent getting -0.0. */
    axisMin = tickMin = floor(min / step) * step + 0.0;
    axisMax = tickMax = ceil(max / step) * step + 0.0;

    nTicks = Round((tickMax - tickMin) / step) + 1;
    axisPtr->majorSweep.step = step;
    axisPtr->majorSweep.initial = tickMin;
    axisPtr->majorSweep.nSteps = nTicks;

    /*
     * The limits of the axis are either the range of the data
     * ("tight") or at the next outer tick interval ("loose").  The
     * looseness or tightness has to do with how the axis fits the
     * range of data values.  This option is overridden when
     * the user sets an axis limit (by either -min or -max option).
     * The axis limit is always at the selected limit (otherwise we
     * assume that user would have picked a different number).
     */
    if ((axisPtr->looseMin == TICK_RANGE_TIGHT) ||
        ((axisPtr->looseMin == TICK_RANGE_LOOSE) &&
            (!TclIsNaN(axisPtr->reqMin)))) {
        axisMin = min;
    }
    if ((axisPtr->looseMax == TICK_RANGE_TIGHT) ||
        ((axisPtr->looseMax == TICK_RANGE_LOOSE) &&
            (!TclIsNaN(axisPtr->reqMax)))) {
        axisMax = max;
    }
    SetAxisRange(&axisPtr->axisRange, axisMin, axisMax);

    /* Now calculate the minor tick step and number. */

    if ((axisPtr->reqNumMinorTicks > 0) &&
        ((axisPtr->flags & AXIS_CONFIG_MAJOR) == 0)) {
        nTicks = axisPtr->reqNumMinorTicks - 1;
        step = 1.0 / (nTicks + 1);
    } else {
        nTicks = 0;             /* No minor ticks. */
        step = 0.5;             /* Don't set the minor tick interval
                                 * to 0.0. It makes the GenerateTicks
                                 * routine create minor log-scale tick
                                 * marks.  */
    }
    axisPtr->minorSweep.initial = axisPtr->minorSweep.step = step;
    axisPtr->minorSweep.nSteps = nTicks;
}

/*
 *----------------------------------------------------------------------
 *
 * SweepTicks --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
SweepTicks(
    RbcAxis * axisPtr)
{
    if ((axisPtr->flags & AXIS_CONFIG_MAJOR) == 0) {
        if (axisPtr->t1Ptr != NULL) {
            ckfree((char *) axisPtr->t1Ptr);
        }
        axisPtr->t1Ptr = GenerateTicks(&axisPtr->majorSweep);
    }
    if ((axisPtr->flags & AXIS_CONFIG_MINOR) == 0) {
        if (axisPtr->t2Ptr != NULL) {
            ckfree((char *) axisPtr->t2Ptr);
        }
        axisPtr->t2Ptr = GenerateTicks(&axisPtr->minorSweep);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcResetAxes --
 *
 *      TODO: Description
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
void
RbcResetAxes(
    RbcGraph * graphPtr)
{
    RbcChainLink   *linkPtr;
    RbcElement     *elemPtr;
    RbcAxis        *axisPtr;
    Tcl_HashEntry  *hPtr;
    Tcl_HashSearch  cursor;
    RbcExtents2D    exts;
    double          min, max;

    /* FIXME: This should be called whenever the display list of
     *        elements change. Maybe yet another flag INIT_STACKS to
     *        indicate that the element display list has changed.
     *        Needs to be done before the axis limits are set.
     */
    RbcInitFreqTable(graphPtr);
    if ((graphPtr->mode == MODE_STACKED) && (graphPtr->nStacks > 0)) {
        RbcComputeStacks(graphPtr);
    }
    /*
     * Step 1:  Reset all axes. Initialize the data limits of the axis to
     *          impossible values.
     */
    for (hPtr = Tcl_FirstHashEntry(&graphPtr->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);
        axisPtr->min = axisPtr->valueRange.min = DBL_MAX;
        axisPtr->max = axisPtr->valueRange.max = -DBL_MAX;
    }

    /*
     * Step 2:  For each element that's to be displayed, get the smallest
     *          and largest data values mapped to each X and Y-axis.  This
     *          will be the axis limits if the user doesn't override them
     *          with -min and -max options.
     */
    for (linkPtr = RbcChainFirstLink(graphPtr->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        (*elemPtr->procsPtr->extentsProc) (elemPtr, &exts);
        GetDataLimits(elemPtr->axes.x, exts.left, exts.right);
        GetDataLimits(elemPtr->axes.y, exts.top, exts.bottom);
    }
    /*
     * Step 3:  Now that we know the range of data values for each axis,
     *          set axis limits and compute a sweep to generate tick values.
     */
    for (hPtr = Tcl_FirstHashEntry(&graphPtr->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);
        FixAxisRange(axisPtr);

        /* Calculate min/max tick (major/minor) layouts */
        min = axisPtr->min;
        max = axisPtr->max;
        if ((!TclIsNaN(axisPtr->scrollMin)) && (min < axisPtr->scrollMin)) {
            min = axisPtr->scrollMin;
        }
        if ((!TclIsNaN(axisPtr->scrollMax)) && (max > axisPtr->scrollMax)) {
            max = axisPtr->scrollMax;
        }
        if (axisPtr->logScale) {
            LogScaleAxis(axisPtr, min, max);
        } else {
            LinearScaleAxis(axisPtr, min, max);
        }

        if ((axisPtr->flags & (AXIS_DIRTY | AXIS_ONSCREEN)) ==
            (AXIS_DIRTY | AXIS_ONSCREEN)) {
            graphPtr->flags |= RBC_REDRAW_BACKING_STORE;
        }
    }

    graphPtr->flags &= ~RBC_RESET_AXES;

    /*
     * When any axis changes, we need to layout the entire graph.
     */
    graphPtr->flags |= (RBC_GET_AXIS_GEOMETRY | RBC_LAYOUT_NEEDED |
        RBC_MAP_ALL | RBC_REDRAW_WORLD);
}

/*
 * ----------------------------------------------------------------------
 *
 * ResetTextStyles --
 *
 *      Configures axis attributes (font, line width, label, etc) and
 *      allocates a new (possibly shared) graphics context.  Line cap
 *      style is projecting.  This is for the problem of when a tick
 *      sits directly at the end point of the axis.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      Axis resources are allocated (GC, font). Axis layout is
 *      deferred until the height and width of the window are known.
 *
 * ----------------------------------------------------------------------
 */
static void
ResetTextStyles(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr)
{
    GC              newGC;
    XGCValues       gcValues;
    unsigned long   gcMask;

    RbcResetTextStyle(graphPtr->tkwin, &axisPtr->titleTextStyle);
    RbcResetTextStyle(graphPtr->tkwin, &axisPtr->tickTextStyle);
    RbcResetTextStyle(graphPtr->tkwin, &axisPtr->limitsTextStyle);

    gcMask = (GCForeground | GCLineWidth | GCCapStyle);
    gcValues.foreground = axisPtr->tickTextStyle.color->pixel;
    gcValues.line_width = RbcLineWidth(axisPtr->lineWidth);
    gcValues.cap_style = CapProjecting;

    newGC = Tk_GetGC(graphPtr->tkwin, gcMask, &gcValues);
    if (axisPtr->tickGC != NULL) {
        Tk_FreeGC(graphPtr->display, axisPtr->tickGC);
    }
    axisPtr->tickGC = newGC;
}

/*
 * ----------------------------------------------------------------------
 *
 * DestroyAxis --
 *
 *      TODO: Description
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Resources (font, color, gc, labels, etc.) associated with the
 *      axis are deallocated.
 *
 * ----------------------------------------------------------------------
 */
static void
DestroyAxis(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr)
{
    int             flags;

    flags = RbcGraphType(graphPtr);
    Tk_FreeOptions(configSpecs, (char *) axisPtr, graphPtr->display, flags);
    if (graphPtr->bindTable != NULL) {
        RbcDeleteBindings(graphPtr->bindTable, axisPtr);
    }
    if (axisPtr->linkPtr != NULL) {
        RbcChainDeleteLink(axisPtr->chainPtr, axisPtr->linkPtr);
    }
    if (axisPtr->name != NULL) {
        ckfree((char *) axisPtr->name);
    }
    if (axisPtr->hashPtr != NULL) {
        Tcl_DeleteHashEntry(axisPtr->hashPtr);
    }
    RbcFreeTextStyle(graphPtr->display, &axisPtr->titleTextStyle);
    RbcFreeTextStyle(graphPtr->display, &axisPtr->limitsTextStyle);
    RbcFreeTextStyle(graphPtr->display, &axisPtr->tickTextStyle);

    if (axisPtr->tickGC != NULL) {
        Tk_FreeGC(graphPtr->display, axisPtr->tickGC);
    }
    if (axisPtr->t1Ptr != NULL) {
        ckfree((char *) axisPtr->t1Ptr);
    }
    if (axisPtr->t2Ptr != NULL) {
        ckfree((char *) axisPtr->t2Ptr);
    }
    if (axisPtr->limitsFormats != NULL) {
        ckfree((char *) axisPtr->limitsFormats);
    }
    FreeLabels(axisPtr->tickLabels);
    RbcChainDestroy(axisPtr->tickLabels);
    if (axisPtr->segments != NULL) {
        ckfree((char *) axisPtr->segments);
    }
    if (axisPtr->tags != NULL) {
        ckfree((char *) axisPtr->tags);
    }
    ckfree((char *) axisPtr);
}

/*
 * ----------------------------------------------------------------------
 *
 * AxisOffsets --
 *
 *      Determines the sites of the axis, major and minor ticks,
 *      and title of the axis.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static void
AxisOffsets(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int margin,
    int axisOffset,
    AxisInfo * infoPtr)
{
    int             pad;        /* Offset of axis from interior region. This
                                 * includes a possible border and the axis
                                 * line width. */
    int             p;
    int             majorOffset, minorOffset, labelOffset;
    int             offset;
    int             x, y;

    axisPtr->titleTextStyle.theta = titleRotate[margin];

    majorOffset = minorOffset = 0;
    labelOffset = AXIS_TITLE_PAD;
    if (axisPtr->lineWidth > 0) {
        majorOffset = ABS(axisPtr->tickLength);
        minorOffset = 10 * majorOffset / 15;
        labelOffset = majorOffset + AXIS_TITLE_PAD + axisPtr->lineWidth / 2;
    }
    /* Adjust offset for the interior border width and the line width */
    pad = axisPtr->lineWidth + 1;
    if (graphPtr->plotBorderWidth > 0) {
        pad += graphPtr->plotBorderWidth + 1;
    }
    offset = axisOffset + 1 + pad;
    if ((margin == RBC_MARGIN_LEFT) || (margin == RBC_MARGIN_TOP)) {
        majorOffset = -majorOffset;
        minorOffset = -minorOffset;
        labelOffset = -labelOffset;
    }
    /*
     * Pre-calculate the x-coordinate positions of the axis, tick labels, and
     * the individual major and minor ticks.
     */
    p = 0;                      /* Suppress compiler warning */

    switch (margin) {
    case RBC_MARGIN_TOP:
        p = graphPtr->top - axisOffset - pad;
        if (axisPtr->titleAlternate) {
            x = graphPtr->right + AXIS_TITLE_PAD;
            y = graphPtr->top - axisOffset - (axisPtr->height / 2);
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_W;
        } else {
            x = (graphPtr->right + graphPtr->left) / 2;
            y = graphPtr->top - axisOffset - axisPtr->height - AXIS_TITLE_PAD;
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_N;
        }
        axisPtr->tickTextStyle.anchor = TK_ANCHOR_S;
        offset = axisPtr->borderWidth + axisPtr->lineWidth / 2;
        axisPtr->region.left = graphPtr->hOffset - offset - 2;
        axisPtr->region.right = graphPtr->hOffset + graphPtr->hRange +
            offset - 1;
        axisPtr->region.top = p + labelOffset - 1;
        axisPtr->region.bottom = p;
        axisPtr->titlePos.x = x;
        axisPtr->titlePos.y = y;
        break;

    case RBC_MARGIN_BOTTOM:
        p = graphPtr->bottom + axisOffset + pad;
        if (axisPtr->titleAlternate) {
            x = graphPtr->right + AXIS_TITLE_PAD;
            y = graphPtr->bottom + axisOffset + (axisPtr->height / 2);
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_W;
        } else {
            x = (graphPtr->right + graphPtr->left) / 2;
            y = graphPtr->bottom + axisOffset + axisPtr->height +
                AXIS_TITLE_PAD;
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_S;
        }
        axisPtr->tickTextStyle.anchor = TK_ANCHOR_N;
        offset = axisPtr->borderWidth + axisPtr->lineWidth / 2;
        axisPtr->region.left = graphPtr->hOffset - offset - 2;
        axisPtr->region.right = graphPtr->hOffset + graphPtr->hRange +
            offset - 1;

        axisPtr->region.top = graphPtr->bottom + axisOffset +
            axisPtr->lineWidth - axisPtr->lineWidth / 2;
        axisPtr->region.bottom = graphPtr->bottom + axisOffset +
            axisPtr->lineWidth + labelOffset + 1;
        axisPtr->titlePos.x = x;
        axisPtr->titlePos.y = y;
        break;

    case RBC_MARGIN_LEFT:
        p = graphPtr->left - axisOffset - pad;
        if (axisPtr->titleAlternate) {
            x = graphPtr->left - axisOffset - (axisPtr->width / 2);
            y = graphPtr->top - AXIS_TITLE_PAD;
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_SW;
        } else {
            x = graphPtr->left - axisOffset - axisPtr->width -
                graphPtr->plotBorderWidth;
            y = (graphPtr->bottom + graphPtr->top) / 2;
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_W;
        }
        axisPtr->tickTextStyle.anchor = TK_ANCHOR_E;
        axisPtr->region.left = graphPtr->left - offset + labelOffset - 1;
        axisPtr->region.right = graphPtr->left - offset + 2;

        offset = axisPtr->borderWidth + axisPtr->lineWidth / 2;
        axisPtr->region.top = graphPtr->vOffset - offset - 2;
        axisPtr->region.bottom = graphPtr->vOffset + graphPtr->vRange +
            offset - 1;
        axisPtr->titlePos.x = x;
        axisPtr->titlePos.y = y;
        break;

    case RBC_MARGIN_RIGHT:
        p = graphPtr->right + axisOffset + pad;
        if (axisPtr->titleAlternate) {
            x = graphPtr->right + axisOffset + (axisPtr->width / 2);
            y = graphPtr->top - AXIS_TITLE_PAD;
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_SE;
        } else {
            x = graphPtr->right + axisOffset + axisPtr->width + AXIS_TITLE_PAD;
            y = (graphPtr->bottom + graphPtr->top) / 2;
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_E;
        }
        axisPtr->tickTextStyle.anchor = TK_ANCHOR_W;

        axisPtr->region.left = graphPtr->right + axisOffset +
            axisPtr->lineWidth - axisPtr->lineWidth / 2;
        axisPtr->region.right = graphPtr->right + axisOffset +
            labelOffset + axisPtr->lineWidth + 1;

        offset = axisPtr->borderWidth + axisPtr->lineWidth / 2;
        axisPtr->region.top = graphPtr->vOffset - offset - 2;
        axisPtr->region.bottom = graphPtr->vOffset + graphPtr->vRange +
            offset - 1;
        axisPtr->titlePos.x = x;
        axisPtr->titlePos.y = y;
        break;

    case RBC_MARGIN_NONE:
        break;
    }
    infoPtr->axis = p - (axisPtr->lineWidth / 2);
    infoPtr->t1 = p + majorOffset;
    infoPtr->t2 = p + minorOffset;
    infoPtr->label = p + labelOffset;

    if (axisPtr->tickLength < 0) {
        int             hold;

        hold = infoPtr->t1;
        infoPtr->t1 = infoPtr->axis;
        infoPtr->axis = hold;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MakeAxisLine --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
MakeAxisLine(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,          /* Axis information */
    int line,
    RbcSegment2D * segPtr)
{
    double          min, max;

    min = axisPtr->axisRange.min;
    max = axisPtr->axisRange.max;
    if (axisPtr->logScale) {
        min = EXP10(min);
        max = EXP10(max);
    }
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
        segPtr->p.x = RbcHMap(graphPtr, axisPtr, min);
        segPtr->q.x = RbcHMap(graphPtr, axisPtr, max);
        segPtr->p.y = segPtr->q.y = line;
    } else {
        segPtr->q.x = segPtr->p.x = line;
        segPtr->p.y = RbcVMap(graphPtr, axisPtr, min);
        segPtr->q.y = RbcVMap(graphPtr, axisPtr, max);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MakeTick --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
MakeTick(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    double value,
    int tick,                   /* Lengths of tick. */
    int line,                   /* Lengths of axis line. */
    RbcSegment2D * segPtr)
{
    if (axisPtr->logScale) {
        value = EXP10(value);
    }
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
        segPtr->p.x = segPtr->q.x = RbcHMap(graphPtr, axisPtr, value);
        segPtr->p.y = line;
        segPtr->q.y = tick;
    } else {
        segPtr->p.x = line;
        segPtr->p.y = segPtr->q.y = RbcVMap(graphPtr, axisPtr, value);
        segPtr->q.x = tick;
    }
}

/*
 * -----------------------------------------------------------------
 *
 * MapAxis --
 *
 *      Pre-calculates positions of the axis, ticks, and labels (to be
 *      used later when displaying the axis).  Calculates the values
 *      for each major and minor tick and checks to see if they are in
 *      range (the outer ticks may be outside of the range of plotted
 *      values).
 *
 *      Line segments for the minor and major ticks are saved into one
 *      XSegment array so that they can be drawn by a single
 *      XDrawSegments call. The positions of the tick labels are also
 *      computed and saved.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Line segments and tick labels are saved and used later to draw
 *      the axis.
 *
 * -----------------------------------------------------------------
 */
static void
MapAxis(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int offset,
    int margin)
{
    int             arraySize;
    int             nMajorTicks, nMinorTicks;
    AxisInfo        info;
    RbcSegment2D   *segments;
    RbcSegment2D   *segPtr;

    AxisOffsets(graphPtr, axisPtr, margin, offset, &info);

    /* Save all line coordinates in an array of line segments. */

    if (axisPtr->segments != NULL) {
        ckfree((char *) axisPtr->segments);
    }
    nMajorTicks = nMinorTicks = 0;
    if (axisPtr->t1Ptr != NULL) {
        nMajorTicks = axisPtr->t1Ptr->nTicks;
    }
    if (axisPtr->t2Ptr != NULL) {
        nMinorTicks = axisPtr->t2Ptr->nTicks;
    }
    arraySize = 1 + (nMajorTicks * (nMinorTicks + 1));
    segments = (RbcSegment2D *) ckalloc(arraySize * sizeof(RbcSegment2D));
    assert(segments);

    segPtr = segments;
    if (axisPtr->lineWidth > 0) {
        /* Axis baseline */
        MakeAxisLine(graphPtr, axisPtr, info.axis, segPtr);
        segPtr++;
    }
    if (axisPtr->showTicks) {
        double          t1, t2;
        double          labelPos;
        register int    i, j;
        int             isHoriz;
        TickLabel      *labelPtr;
        RbcChainLink   *linkPtr;
        RbcSegment2D    seg;

        isHoriz = AxisIsHorizontal(graphPtr, axisPtr);
        for (i = 0; i < axisPtr->t1Ptr->nTicks; i++) {
            t1 = axisPtr->t1Ptr->values[i];
            /* Minor ticks */
            for (j = 0; j < axisPtr->t2Ptr->nTicks; j++) {
                t2 = t1 +
                    (axisPtr->majorSweep.step * axisPtr->t2Ptr->values[j]);
                if (InRange(t2, &axisPtr->axisRange)) {
                    MakeTick(graphPtr, axisPtr, t2, info.t2, info.axis, segPtr);
                    segPtr++;
                }
            }
            if (!InRange(t1, &axisPtr->axisRange)) {
                continue;
            }
            /* Major tick */
            MakeTick(graphPtr, axisPtr, t1, info.t1, info.axis, segPtr);
            segPtr++;
        }

        linkPtr = RbcChainFirstLink(axisPtr->tickLabels);
        labelPos = (double) info.label;

        for (i = 0; i < axisPtr->t1Ptr->nTicks; i++) {
            t1 = axisPtr->t1Ptr->values[i];
            if (axisPtr->labelOffset) {
                t1 += axisPtr->majorSweep.step * 0.5;
            }
            if (!InRange(t1, &axisPtr->axisRange)) {
                continue;
            }
            labelPtr = RbcChainGetValue(linkPtr);
            linkPtr = RbcChainNextLink(linkPtr);
            MakeTick(graphPtr, axisPtr, t1, info.t1, info.axis, &seg);
            /* Save tick label X-Y position. */
            if (isHoriz) {
                labelPtr->anchorPos.x = seg.p.x;
                labelPtr->anchorPos.y = labelPos;
            } else {
                labelPtr->anchorPos.x = labelPos;
                labelPtr->anchorPos.y = seg.p.y;
            }
        }
    }
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
        axisPtr->width = graphPtr->right - graphPtr->left;
    } else {
        axisPtr->height = graphPtr->bottom - graphPtr->top;
    }
    axisPtr->segments = segments;
    axisPtr->nSegments = segPtr - segments;
    assert(axisPtr->nSegments <= arraySize);
}

/*
 *----------------------------------------------------------------------
 *
 * AdjustViewport --
 *
 *      Adjusts the offsets of the viewport according to the scroll mode.
 *      This is to accommodate both "listbox" and "canvas" style scrolling.
 *
 *      "canvas"	The viewport scrolls within the range of world
 *              coordinates.  This way the viewport always displays
 *              a full page of the world.  If the world is smaller
 *              than the viewport, then (bizarrely) the world and
 *              viewport are inverted so that the world moves up
 *              and down within the viewport.
 *
 *      "listbox"	The viewport can scroll beyond the range of world
 *              coordinates.  Every entry can be displayed at the
 *              top of the viewport.  This also means that the
 *              scrollbar thumb weirdly shrinks as the last entry
 *              is scrolled upward.
 *
 * Results:
 *      The corrected offset is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static double
AdjustViewport(
    double offset,
    double windowSize)
{
    /*
     * Canvas-style scrolling allows the world to be scrolled
     * within the window.
     */
    if (windowSize > 1.0) {
        if (windowSize < (1.0 - offset)) {
            offset = 1.0 - windowSize;
        }
        if (offset > 0.0) {
            offset = 0.0;
        }
    } else {
        if ((offset + windowSize) > 1.0) {
            offset = 1.0 - windowSize;
        }
        if (offset < 0.0) {
            offset = 0.0;
        }
    }
    return offset;
}

/*
 *----------------------------------------------------------------------
 *
 * GetAxisScrollInfo --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetAxisScrollInfo(
    Tcl_Interp * interp,
    int argc,
    const char **argv,
    double *offsetPtr,
    double windowSize,
    double scrollUnits)
{
    char            c;
    unsigned int    length;
    double          offset;
    int             count;
    double          fract;

    offset = *offsetPtr;
    c = argv[0][0];
    length = strlen(argv[0]);
    if ((c == 's') && (strncmp(argv[0], "scroll", length) == 0)) {
        assert(argc == 3);
        /* scroll number unit/page */
        if (Tcl_GetInt(interp, argv[1], &count) != TCL_OK) {
            return TCL_ERROR;
        }
        c = argv[2][0];
        length = strlen(argv[2]);
        if ((c == 'u') && (strncmp(argv[2], "units", length) == 0)) {
            fract = (double) count *scrollUnits;
        } else if ((c == 'p') && (strncmp(argv[2], "pages", length) == 0)) {
            /* A page is 90% of the view-able window. */
            fract = (double) count *windowSize * 0.9;
        } else {
            Tcl_AppendResult(interp, "unknown \"scroll\" units \"", argv[2],
                "\"", (char *) NULL);
            return TCL_ERROR;
        }
        offset += fract;
    } else if ((c == 'm') && (strncmp(argv[0], "moveto", length) == 0)) {
        assert(argc == 2);
        /* moveto fraction */
        if (Tcl_GetDouble(interp, argv[1], &fract) != TCL_OK) {
            return TCL_ERROR;
        }
        offset = fract;
    } else {
        /* Treat like "scroll units" */
        if (Tcl_GetInt(interp, argv[0], &count) != TCL_OK) {
            return TCL_ERROR;
        }
        fract = (double) count *scrollUnits;
        offset += fract;
        /* CHECK THIS: return TCL_OK; */
    }
    *offsetPtr = AdjustViewport(offset, windowSize);
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------
 *
 * DrawAxis --
 *
 *      Draws the axis, ticks, and labels onto the canvas.
 *
 *      Initializes and passes text attribute information through
 *      TextStyle structure.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Axis gets drawn on window.
 *
 * -----------------------------------------------------------------
 */
static void
DrawAxis(
    RbcGraph * graphPtr,
    Drawable drawable,
    RbcAxis * axisPtr)
{
    if (axisPtr->border != NULL) {
        Tk_Fill3DRectangle(graphPtr->tkwin, drawable, axisPtr->border,
            axisPtr->region.left + graphPtr->plotBorderWidth,
            axisPtr->region.top + graphPtr->plotBorderWidth,
            axisPtr->region.right - axisPtr->region.left,
            axisPtr->region.bottom - axisPtr->region.top,
            axisPtr->borderWidth, axisPtr->relief);
    }
    if (axisPtr->title != NULL) {
        RbcDrawText(graphPtr->tkwin, drawable, axisPtr->title,
            &axisPtr->titleTextStyle, (int) axisPtr->titlePos.x,
            (int) axisPtr->titlePos.y);
    }
    if (axisPtr->scrollCmdPrefix != NULL) {
        double          viewWidth, viewMin, viewMax;
        double          worldWidth, worldMin, worldMax;
        double          fract;
        int             isHoriz;

        worldMin = axisPtr->valueRange.min;
        worldMax = axisPtr->valueRange.max;
        if (!TclIsNaN(axisPtr->scrollMin)) {
            worldMin = axisPtr->scrollMin;
        }
        if (!TclIsNaN(axisPtr->scrollMax)) {
            worldMax = axisPtr->scrollMax;
        }
        viewMin = axisPtr->min;
        viewMax = axisPtr->max;
        if (viewMin < worldMin) {
            viewMin = worldMin;
        }
        if (viewMax > worldMax) {
            viewMax = worldMax;
        }
        if (axisPtr->logScale) {
            worldMin = log10(worldMin);
            worldMax = log10(worldMax);
            viewMin = log10(viewMin);
            viewMax = log10(viewMax);
        }
        worldWidth = worldMax - worldMin;
        viewWidth = viewMax - viewMin;
        isHoriz = AxisIsHorizontal(graphPtr, axisPtr);

        if (isHoriz != axisPtr->descending) {
            fract = (viewMin - worldMin) / worldWidth;
        } else {
            fract = (worldMax - viewMax) / worldWidth;
        }
        fract = AdjustViewport(fract, viewWidth / worldWidth);

        if (isHoriz != axisPtr->descending) {
            viewMin = (fract * worldWidth);
            axisPtr->min = viewMin + worldMin;
            axisPtr->max = axisPtr->min + viewWidth;
            viewMax = viewMin + viewWidth;
            if (axisPtr->logScale) {
                axisPtr->min = EXP10(axisPtr->min);
                axisPtr->max = EXP10(axisPtr->max);
            }
            RbcUpdateScrollbar(graphPtr->interp, axisPtr->scrollCmdPrefix,
                (viewMin / worldWidth), (viewMax / worldWidth));
        } else {
            viewMax = (fract * worldWidth);
            axisPtr->max = worldMax - viewMax;
            axisPtr->min = axisPtr->max - viewWidth;
            viewMin = viewMax + viewWidth;
            if (axisPtr->logScale) {
                axisPtr->min = EXP10(axisPtr->min);
                axisPtr->max = EXP10(axisPtr->max);
            }
            RbcUpdateScrollbar(graphPtr->interp, axisPtr->scrollCmdPrefix,
                (viewMax / worldWidth), (viewMin / worldWidth));
        }
    }
    if (axisPtr->showTicks) {
        register RbcChainLink *linkPtr;
        TickLabel      *labelPtr;

        for (linkPtr = RbcChainFirstLink(axisPtr->tickLabels); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            /* Draw major tick labels */
            labelPtr = RbcChainGetValue(linkPtr);
            RbcDrawText(graphPtr->tkwin, drawable, labelPtr->string,
                &axisPtr->tickTextStyle, (int) labelPtr->anchorPos.x,
                (int) labelPtr->anchorPos.y);
        }
    }
    if ((axisPtr->nSegments > 0) && (axisPtr->lineWidth > 0)) {
        /* Draw the tick marks and axis line. */
        RbcDraw2DSegments(graphPtr->display, drawable, axisPtr->tickGC,
            axisPtr->segments, axisPtr->nSegments);
    }
}

/*
 * -----------------------------------------------------------------
 *
 * AxisToPostScript --
 *
 *      Generates PostScript output to draw the axis, ticks, and
 *      labels.
 *
 *      Initializes and passes text attribute information through
 *      TextStyle structure.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      PostScript output is left in graphPtr->interp->result;
 *
 * -----------------------------------------------------------------
 */
static void
AxisToPostScript(
    RbcPsToken * psToken,
    RbcAxis * axisPtr)
{
    if (axisPtr->title != NULL) {
        RbcTextToPostScript(psToken, axisPtr->title, &axisPtr->titleTextStyle,
            axisPtr->titlePos.x, axisPtr->titlePos.y);
    }
    if (axisPtr->showTicks) {
        register RbcChainLink *linkPtr;
        TickLabel      *labelPtr;

        for (linkPtr = RbcChainFirstLink(axisPtr->tickLabels);
            linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
            labelPtr = RbcChainGetValue(linkPtr);
            RbcTextToPostScript(psToken, labelPtr->string,
                &axisPtr->tickTextStyle, labelPtr->anchorPos.x,
                labelPtr->anchorPos.y);
        }
    }
    if ((axisPtr->nSegments > 0) && (axisPtr->lineWidth > 0)) {
        RbcLineAttributesToPostScript(psToken, axisPtr->tickTextStyle.color,
            axisPtr->lineWidth, (RbcDashes *) NULL, CapButt, JoinMiter);
        Rbc2DSegmentsToPostScript(psToken, axisPtr->segments,
            axisPtr->nSegments);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MakeGridLine --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
MakeGridLine(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    double value,
    RbcSegment2D * segPtr)
{
    if (axisPtr->logScale) {
        value = EXP10(value);
    }
    /* Grid lines run orthogonally to the axis */
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
        segPtr->p.y = graphPtr->top;
        segPtr->q.y = graphPtr->bottom;
        segPtr->p.x = segPtr->q.x = RbcHMap(graphPtr, axisPtr, value);
    } else {
        segPtr->p.x = graphPtr->left;
        segPtr->q.x = graphPtr->right;
        segPtr->p.y = segPtr->q.y = RbcVMap(graphPtr, axisPtr, value);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGetAxisSegments --
 *
 *      Assembles the grid lines associated with an axis. Generates
 *      tick positions if necessary (this happens when the axis is
 *      not a logical axis too).
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcGetAxisSegments(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    RbcSegment2D ** segPtrPtr,
    int *nSegmentsPtr)
{
    int             needed;
    RbcTicks       *t1Ptr, *t2Ptr;
    register int    i;
    double          value;
    RbcSegment2D   *segments, *segPtr;

    *nSegmentsPtr = 0;
    *segPtrPtr = NULL;
    if (axisPtr == NULL) {
        return;
    }
    t1Ptr = axisPtr->t1Ptr;
    if (t1Ptr == NULL) {
        t1Ptr = GenerateTicks(&axisPtr->majorSweep);
    }
    t2Ptr = axisPtr->t2Ptr;
    if (t2Ptr == NULL) {
        t2Ptr = GenerateTicks(&axisPtr->minorSweep);
    }

    needed = t1Ptr->nTicks;
    if (graphPtr->gridPtr->minorGrid) {
        needed += (t1Ptr->nTicks * t2Ptr->nTicks);
    }
    if (needed == 0) {
        return;
    }
    segments = (RbcSegment2D *) ckalloc(sizeof(RbcSegment2D) * needed);
    if (segments == NULL) {
        return;                 /* Can't allocate memory for grid. */
    }

    segPtr = segments;
    for (i = 0; i < t1Ptr->nTicks; i++) {
        value = t1Ptr->values[i];
        if (graphPtr->gridPtr->minorGrid) {
            register int    j;
            double          subValue;

            for (j = 0; j < t2Ptr->nTicks; j++) {
                subValue = value +
                    (axisPtr->majorSweep.step * t2Ptr->values[j]);
                if (InRange(subValue, &axisPtr->axisRange)) {
                    MakeGridLine(graphPtr, axisPtr, subValue, segPtr);
                    segPtr++;
                }
            }
        }
        if (InRange(value, &axisPtr->axisRange)) {
            MakeGridLine(graphPtr, axisPtr, value, segPtr);
            segPtr++;
        }
    }

    if (t1Ptr != axisPtr->t1Ptr) {
        ckfree((char *) t1Ptr); /* Free generated ticks. */
    }
    if (t2Ptr != axisPtr->t2Ptr) {
        ckfree((char *) t2Ptr); /* Free generated ticks. */
    }
    *nSegmentsPtr = segPtr - segments;
    assert(*nSegmentsPtr <= needed);
    *segPtrPtr = segments;
}

/*
 *----------------------------------------------------------------------
 *
 * GetAxisGeometry --
 *
 *      TODO: Description
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
GetAxisGeometry(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr)
{
    int             height;

    FreeLabels(axisPtr->tickLabels);
    height = 0;
    if (axisPtr->lineWidth > 0) {
        /* Leave room for axis baseline (and pad) */
        height += axisPtr->lineWidth + 2;
    }
    if (axisPtr->showTicks) {
        int             pad;
        register int    i, nLabels;
        int             lw, lh;
        double          x, x2;
        int             maxWidth, maxHeight;
        TickLabel      *labelPtr;

        SweepTicks(axisPtr);

        if (axisPtr->t1Ptr->nTicks < 0) {
            fprintf(stderr, "%s major ticks can't be %d\n",
                axisPtr->name, axisPtr->t1Ptr->nTicks);
            abort();
        }
        if (axisPtr->t1Ptr->nTicks > MAXTICKS) {
            fprintf(stderr, "too big, %s major ticks can't be %d\n",
                axisPtr->name, axisPtr->t1Ptr->nTicks);
            abort();
        }

        maxHeight = maxWidth = 0;
        nLabels = 0;
        for (i = 0; i < axisPtr->t1Ptr->nTicks; i++) {
            x2 = x = axisPtr->t1Ptr->values[i];
            if (axisPtr->labelOffset) {
                x2 += axisPtr->majorSweep.step * 0.5;
            }
            if (!InRange(x2, &axisPtr->axisRange)) {
                continue;
            }
            labelPtr = MakeLabel(graphPtr, axisPtr, x);
            RbcChainAppend(axisPtr->tickLabels, labelPtr);
            nLabels++;
            /*
             * Get the dimensions of each tick label.
             * Remember tick labels can be multi-lined and/or rotated.
             */
            RbcGetTextExtents(&axisPtr->tickTextStyle, labelPtr->string,
                &lw, &lh);
            labelPtr->width = lw;
            labelPtr->height = lh;

            if (axisPtr->tickTextStyle.theta > 0.0) {
                double          rotWidth, rotHeight;

                RbcGetBoundingBox(lw, lh, axisPtr->tickTextStyle.theta,
                    &rotWidth, &rotHeight, (RbcPoint2D *) NULL);
                lw = ROUND(rotWidth);
                lh = ROUND(rotHeight);
            }
            if (maxWidth < lw) {
                maxWidth = lw;
            }
            if (maxHeight < lh) {
                maxHeight = lh;
            }
        }
        assert(nLabels <= axisPtr->t1Ptr->nTicks);

        /* Because the axis cap style is "CapProjecting", we need to
         * account for an extra 1.5 linewidth at the end of each
         * line.  */

        pad = ((axisPtr->lineWidth * 15) / 10);

        if (AxisIsHorizontal(graphPtr, axisPtr)) {
            height += maxHeight + pad;
        } else {
            height += maxWidth + pad;
        }
        if (axisPtr->lineWidth > 0) {
            /* Distance from axis line to tick label. */
            height += AXIS_TITLE_PAD;
            height += ABS(axisPtr->tickLength);
        }
    }

    if (axisPtr->title != NULL) {
        if (axisPtr->titleAlternate) {
            if (height < axisPtr->titleHeight) {
                height = axisPtr->titleHeight;
            }
        } else {
            height += axisPtr->titleHeight + AXIS_TITLE_PAD;
        }
    }

    /* Correct for orientation of the axis. */
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
        axisPtr->height = height;
    } else {
        axisPtr->width = height;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GetMarginGeometry --
 *
 *      Examines all the axes in the given margin and determines the
 *      area required to display them.
 *
 *      Note: For multiple axes, the titles are displayed in another
 *            margin. So we must keep track of the widest title.
 *
 * Results:
 *      Returns the width or height of the margin, depending if it
 *      runs horizontally along the graph or vertically.
 *
 * Side Effects:
 *      The area width and height set in the margin.  Note again that
 *      this may be corrected later (mulitple axes) to adjust for
 *      the longest title in another margin.
 *
 *----------------------------------------------------------------------
 */
static int
GetMarginGeometry(
    RbcGraph * graphPtr,
    RbcMargin * marginPtr)
{
    RbcChainLink   *linkPtr;
    RbcAxis        *axisPtr;
    int             width, height;
    int             isHoriz;
    int             length, count;

    isHoriz = HORIZMARGIN(marginPtr);
    /* Count the number of visible axes. */
    count = 0;
    length = width = height = 0;
    for (linkPtr = RbcChainFirstLink(marginPtr->axes); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        axisPtr = RbcChainGetValue(linkPtr);
        if ((!axisPtr->hidden) && (axisPtr->flags & AXIS_ONSCREEN)) {
            count++;
            if (graphPtr->flags & RBC_GET_AXIS_GEOMETRY) {
                GetAxisGeometry(graphPtr, axisPtr);
            }
            if ((axisPtr->titleAlternate) && (length < axisPtr->titleWidth)) {
                length = axisPtr->titleWidth;
            }
            if (isHoriz) {
                height += axisPtr->height;
            } else {
                width += axisPtr->width;
            }
        }
    }
    /* Enforce a minimum size for margins. */
    if (width < 3) {
        width = 3;
    }
    if (height < 3) {
        height = 3;
    }
    marginPtr->nAxes = count;
    marginPtr->axesTitleLength = length;
    marginPtr->width = width;
    marginPtr->height = height;
    marginPtr->axesOffset = (HORIZMARGIN(marginPtr)) ? height : width;
    return marginPtr->axesOffset;
}

/*
 *----------------------------------------------------------------------
 *
 * ComputeMargins --
 *
 *      Computes the size of the margins and the plotting area.  We
 *      first compute the space needed for the axes in each margin.
 *      Then how much space the legend will occupy.  Finally, if the
 *      user has requested a margin size, we override the computed
 *      value.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *---------------------------------------------------------------------- */
static void
ComputeMargins(
    RbcGraph * graphPtr)
{
    int             left, right, top, bottom;
    int             width, height;
    int             insets;

    /*
     * Step 1:  Compute the amount of space needed to display the
     *          axes (there many be 0 or more) associated with the
     *          margin.
     */
    top = GetMarginGeometry(graphPtr, &graphPtr->margins[RBC_MARGIN_TOP]);
    bottom = GetMarginGeometry(graphPtr, &graphPtr->margins[RBC_MARGIN_BOTTOM]);
    left = GetMarginGeometry(graphPtr, &graphPtr->margins[RBC_MARGIN_LEFT]);
    right = GetMarginGeometry(graphPtr, &graphPtr->margins[RBC_MARGIN_RIGHT]);

    /*
     * Step 2:  Add the graph title height to the top margin.
     */
    if (graphPtr->title != NULL) {
        top += graphPtr->titleTextStyle.height;
    }
    insets = 2 * (graphPtr->inset + graphPtr->plotBorderWidth);

    /*
     * Step 3:  Use the current estimate of the plot area to compute
     *          the legend size.  Add it to the proper margin.
     */
    width = graphPtr->width - (insets + left + right);
    height = graphPtr->height - (insets + top + bottom);
    RbcMapLegend(graphPtr->legend, width, height);
    if (!RbcLegendIsHidden(graphPtr->legend)) {
        switch (RbcLegendSite(graphPtr->legend)) {
        case RBC_LEGEND_RIGHT:
            right += RbcLegendWidth(graphPtr->legend) + 2;
            break;
        case RBC_LEGEND_LEFT:
            left += RbcLegendWidth(graphPtr->legend) + 2;
            break;
        case RBC_LEGEND_TOP:
            top += RbcLegendHeight(graphPtr->legend) + 2;
            break;
        case RBC_LEGEND_BOTTOM:
            bottom += RbcLegendHeight(graphPtr->legend) + 2;
            break;
        case RBC_LEGEND_XY:
        case RBC_LEGEND_PLOT:
        case RBC_LEGEND_WINDOW:
            /* Do nothing. */
            break;
        }
    }

    /*
     * Recompute the plotarea, now accounting for the legend.
     */
    width = graphPtr->width - (insets + left + right);
    height = graphPtr->height - (insets + top + bottom);

    /*
     * Step 5:  If necessary, correct for the requested plot area
     *          aspect ratio.
     */
    if (graphPtr->aspect > 0.0) {
        double          ratio;

        /*
         * Shrink one dimension of the plotarea to fit the requested
         * width/height aspect ratio.
         */
        ratio = (double) width / (double) height;
        if (ratio > graphPtr->aspect) {
            int             scaledWidth;

            /* Shrink the width. */
            scaledWidth = (int) (height * graphPtr->aspect);
            if (scaledWidth < 1) {
                scaledWidth = 1;
            }
            right += (width - scaledWidth);     /* Add the difference to
                                                 * the right margin. */
            /* CHECK THIS: width = scaledWidth; */
        } else {
            int             scaledHeight;

            /* Shrink the height. */
            scaledHeight = (int) (width / graphPtr->aspect);
            if (scaledHeight < 1) {
                scaledHeight = 1;
            }
            top += (height - scaledHeight);     /* Add the difference to
                                                 * the top margin. */
            /* CHECK THIS: height = scaledHeight; */
        }
    }

    /*
     * Step 6:  If there's multiple axes in a margin, the axis
     *          titles will be displayed in the adjoining marging.
     *          Make sure there's room for the longest axis titles.
     */

    if (top < graphPtr->margins[RBC_MARGIN_LEFT].axesTitleLength) {
        top = graphPtr->margins[RBC_MARGIN_LEFT].axesTitleLength;
    }
    if (right < graphPtr->margins[RBC_MARGIN_BOTTOM].axesTitleLength) {
        right = graphPtr->margins[RBC_MARGIN_BOTTOM].axesTitleLength;
    }
    if (top < graphPtr->margins[RBC_MARGIN_RIGHT].axesTitleLength) {
        top = graphPtr->margins[RBC_MARGIN_RIGHT].axesTitleLength;
    }
    if (right < graphPtr->margins[RBC_MARGIN_TOP].axesTitleLength) {
        right = graphPtr->margins[RBC_MARGIN_TOP].axesTitleLength;
    }

    /*
     * Step 7:  Override calculated values with requested margin
     *          sizes.
     */

    graphPtr->margins[RBC_MARGIN_LEFT].width = left;
    graphPtr->margins[RBC_MARGIN_RIGHT].width = right;
    graphPtr->margins[RBC_MARGIN_TOP].height = top;
    graphPtr->margins[RBC_MARGIN_BOTTOM].height = bottom;

    if (graphPtr->margins[RBC_MARGIN_LEFT].reqSize > 0) {
        graphPtr->margins[RBC_MARGIN_LEFT].width = graphPtr->margins[RBC_MARGIN_LEFT].reqSize;
    }
    if (graphPtr->margins[RBC_MARGIN_RIGHT].reqSize > 0) {
        graphPtr->margins[RBC_MARGIN_RIGHT].width = graphPtr->margins[RBC_MARGIN_RIGHT].reqSize;
    }
    if (graphPtr->margins[RBC_MARGIN_TOP].reqSize > 0) {
        graphPtr->margins[RBC_MARGIN_TOP].height = graphPtr->margins[RBC_MARGIN_TOP].reqSize;
    }
    if (graphPtr->margins[RBC_MARGIN_BOTTOM].reqSize > 0) {
        graphPtr->margins[RBC_MARGIN_BOTTOM].height = graphPtr->margins[RBC_MARGIN_BOTTOM].reqSize;
    }
}

/*
 * -----------------------------------------------------------------
 *
 * RbcLayoutMargins --
 *
 *      Calculate the layout of the graph.  Based upon the data,
 *      axis limits, X and Y titles, and title height, determine
 *      the cavity left which is the plotting surface.  The first
 *      step get the data and axis limits for calculating the space
 *      needed for the top, bottom, left, and right margins.
 *
 *      1) The LEFT margin is the area from the left border to the
 *         Y axis (not including ticks). It composes the border
 *         width, the width an optional Y axis label and its padding,
 *         and the tick numeric labels. The Y axis label is rotated
 *         90 degrees so that the width is the font height.
 *
 *      2) The RIGHT margin is the area from the end of the graph
 *         to the right window border. It composes the border width,
 *         some padding, the font height (this may be dubious. It
 *         appears to provide a more even border), the max of the
 *         legend width and 1/2 max X tick number. This last part is
 *         so that the last tick label is not clipped.
 *
 *               Window Width
 *          ___________________________________________________________
 *          |          |                               |               |
 *          |          |   TOP  height of title        |               |
 *          |          |                               |               |
 *          |          |           x2 title            |               |
 *          |          |                               |               |
 *          |          |        height of x2-axis      |               |
 *          |__________|_______________________________|_______________|  W
 *          |          | -plotpady                     |               |  i
 *          |__________|_______________________________|_______________|  n
 *          |          | top                   right   |               |  d
 *          |          |                               |               |  o
 *          |   LEFT   |                               |     RIGHT     |  w
 *          |          |                               |               |
 *          | y        |     Free area = 104%          |      y2       |  H
 *          |          |     Plotting surface = 100%   |               |  e
 *          | t        |     Tick length = 2 + 2%      |      t        |  i
 *          | i        |                               |      i        |  g
 *          | t        |                               |      t  legend|  h
 *          | l        |                               |      l   width|  t
 *          | e        |                               |      e        |
 *          |    height|                               |height         |
 *          |       of |                               | of            |
 *          |    y-axis|                               |y2-axis        |
 *          |          |                               |               |
 *          |          |origin 0,0                     |               |
 *          |__________|_left___________________bottom___|_______________|
 *          |          |-plotpady                      |               |
 *          |__________|_______________________________|_______________|
 *          |          | (xoffset, yoffset)            |               |
 *          |          |                               |               |
 *          |          |       height of x-axis        |               |
 *          |          |                               |               |
 *          |          |   BOTTOM   x title            |               |
 *          |__________|_______________________________|_______________|
 *
 *      3) The TOP margin is the area from the top window border to the top
 *         of the graph. It composes the border width, twice the height of
 *         the title font (if one is given) and some padding between the
 *         title.
 *
 *      4) The BOTTOM margin is area from the bottom window border to the
 *         X axis (not including ticks). It composes the border width, the height
 *         an optional X axis label and its padding, the height of the font
 *         of the tick labels.
 *
 *      The plotting area is between the margins which includes the X and Y axes
 *      including the ticks but not the tick numeric labels. The length of
 *      the ticks and its padding is 5% of the entire plotting area.  Hence the
 *      entire plotting area is scaled as 105% of the width and height of the
 *      area.
 *
 *      The axis labels, ticks labels, title, and legend may or may not be
 *      displayed which must be taken into account.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
void
RbcLayoutMargins(
    RbcGraph * graphPtr)
{
    int             width, height;
    int             titleY;
    int             left, right, top, bottom;

    ComputeMargins(graphPtr);
    left = graphPtr->margins[RBC_MARGIN_LEFT].width + graphPtr->inset +
        graphPtr->plotBorderWidth;
    right = graphPtr->margins[RBC_MARGIN_RIGHT].width + graphPtr->inset +
        graphPtr->plotBorderWidth;
    top = graphPtr->margins[RBC_MARGIN_TOP].height + graphPtr->inset +
        graphPtr->plotBorderWidth;
    bottom = graphPtr->margins[RBC_MARGIN_BOTTOM].height + graphPtr->inset +
        graphPtr->plotBorderWidth;

    /* Based upon the margins, calculate the space left for the graph. */
    width = graphPtr->width - (left + right);
    height = graphPtr->height - (top + bottom);
    if (width < 1) {
        width = 1;
    }
    if (height < 1) {
        height = 1;
    }
    graphPtr->left = left;
    graphPtr->right = left + width;
    graphPtr->bottom = top + height;
    graphPtr->top = top;

    graphPtr->vOffset = top + graphPtr->padY.side1;     /*top */
    graphPtr->vRange = height - RbcPadding(graphPtr->padY);
    graphPtr->hOffset = left + graphPtr->padX.side1 /*left */ ;
    graphPtr->hRange = width - RbcPadding(graphPtr->padX);

    if (graphPtr->vRange < 1) {
        graphPtr->vRange = 1;
    }
    if (graphPtr->hRange < 1) {
        graphPtr->hRange = 1;
    }
    graphPtr->hScale = 1.0 / (double) graphPtr->hRange;
    graphPtr->vScale = 1.0 / (double) graphPtr->vRange;

    /*
     * Calculate the placement of the graph title so it is centered within the
     * space provided for it in the top margin
     */
    titleY = graphPtr->titleTextStyle.height;
    graphPtr->titleY = (titleY / 2) + graphPtr->inset;
    graphPtr->titleX = (graphPtr->right + graphPtr->left) / 2;

}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureAxis --
 *
 *      Configures axis attributes (font, line width, label, etc).
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      Axis layout is deferred until the height and width of the
 *      window are known.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureAxis(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr)
{
    char            errMsg[200];

    /* Check the requested axis limits. Can't allow -min to be greater
     * than -max, or have undefined log scale limits.  */
    if (((!TclIsNaN(axisPtr->reqMin)) && (!TclIsNaN(axisPtr->reqMax))) &&
        (axisPtr->reqMin >= axisPtr->reqMax)) {
        sprintf(errMsg, "impossible limits (min %g >= max %g) for axis \"%s\"",
            axisPtr->reqMin, axisPtr->reqMax, axisPtr->name);
        Tcl_AppendResult(graphPtr->interp, errMsg, (char *) NULL);
        /* Bad values, turn on axis auto-scaling */
        axisPtr->reqMin = axisPtr->reqMax = rbcNaN;
        return TCL_ERROR;
    }
    if ((axisPtr->logScale) && (!TclIsNaN(axisPtr->reqMin)) &&
        (axisPtr->reqMin <= 0.0)) {
        sprintf(errMsg, "bad logscale limits (min=%g,max=%g) for axis \"%s\"",
            axisPtr->reqMin, axisPtr->reqMax, axisPtr->name);
        Tcl_AppendResult(graphPtr->interp, errMsg, (char *) NULL);
        /* Bad minimum value, turn on auto-scaling */
        axisPtr->reqMin = rbcNaN;
        return TCL_ERROR;
    }
    axisPtr->tickTextStyle.theta = FMOD(axisPtr->tickTextStyle.theta, 360.0);
    if (axisPtr->tickTextStyle.theta < 0.0) {
        axisPtr->tickTextStyle.theta += 360.0;
    }
    ResetTextStyles(graphPtr, axisPtr);

    axisPtr->titleWidth = axisPtr->titleHeight = 0;
    if (axisPtr->title != NULL) {
        int             w, h;

        RbcGetTextExtents(&axisPtr->titleTextStyle, axisPtr->title, &w, &h);
        axisPtr->titleWidth = (short int) w;
        axisPtr->titleHeight = (short int) h;
    }

    /*
     * Don't bother to check what configuration options have changed.
     * Almost every option changes the size of the plotting area
     * (except for -color and -titlecolor), requiring the graph and
     * its contents to be completely redrawn.
     *
     * Recompute the scale and offset of the axis in case -min, -max
     * options have changed.
     */
    graphPtr->flags |= RBC_REDRAW_WORLD;
    if (!RbcConfigModified(configSpecs, "-*color", "-background", "-bg",
            (char *) NULL)) {
        graphPtr->flags |= (RBC_MAP_WORLD | RBC_RESET_AXES);
        axisPtr->flags |= AXIS_DIRTY;
    }
    RbcEventuallyRedrawGraph(graphPtr);

    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * CreateAxis --
 *
 *      Create and initialize a structure containing information to
 *      display a graph axis.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static RbcAxis *
CreateAxis(
    RbcGraph * graphPtr,
    const char *name,           /* Identifier for axis. */
    int margin)
{
    RbcAxis        *axisPtr;
    Tcl_HashEntry  *hPtr;
    int             isNew;

    if (name[0] == '-') {
        Tcl_AppendResult(graphPtr->interp, "name of axis \"", name,
            "\" can't start with a '-'", (char *) NULL);
        return NULL;
    }
    hPtr = Tcl_CreateHashEntry(&graphPtr->axes.table, name, &isNew);
    if (!isNew) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);
        if (!axisPtr->deletePending) {
            Tcl_AppendResult(graphPtr->interp, "axis \"", name,
                "\" already exists in \"", Tk_PathName(graphPtr->tkwin), "\"",
                (char *) NULL);
            return NULL;
        }
        axisPtr->deletePending = FALSE;
    } else {
        axisPtr = RbcCalloc(1, sizeof(RbcAxis));
        assert(axisPtr);

        axisPtr->name = RbcStrdup(name);
        axisPtr->hashPtr = hPtr;
        axisPtr->classUid = NULL;
        axisPtr->looseMin = axisPtr->looseMax = TICK_RANGE_TIGHT;
        axisPtr->reqNumMinorTicks = 2;
        axisPtr->scrollUnits = 10;
        axisPtr->showTicks = TRUE;
        axisPtr->reqMin = axisPtr->reqMax = rbcNaN;
        axisPtr->scrollMin = axisPtr->scrollMax = rbcNaN;

        if ((graphPtr->classUid == rbcBarElementUid) &&
            ((margin == RBC_MARGIN_TOP) || (margin == RBC_MARGIN_BOTTOM))) {
            axisPtr->reqStep = 1.0;
            axisPtr->reqNumMinorTicks = 0;
        }
        if ((margin == RBC_MARGIN_RIGHT) || (margin == RBC_MARGIN_TOP)) {
            axisPtr->hidden = TRUE;
        }
        RbcInitTextStyle(&axisPtr->titleTextStyle);
        RbcInitTextStyle(&axisPtr->limitsTextStyle);
        RbcInitTextStyle(&axisPtr->tickTextStyle);
        axisPtr->tickLabels = RbcChainCreate();
        axisPtr->lineWidth = 1;
        axisPtr->tickTextStyle.padX.side1 = 2;
        axisPtr->tickTextStyle.padX.side2 = 2;
        Tcl_SetHashValue(hPtr, axisPtr);
    }
    return axisPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * NameToAxis --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
NameToAxis(
    RbcGraph * graphPtr,        /* Graph widget record. */
    const char *name,           /* Name of the axis to be searched for. */
    RbcAxis ** axisPtrPtr)
{                               /* (out) Pointer to found axis structure. */
    Tcl_HashEntry  *hPtr;

    hPtr = Tcl_FindHashEntry(&graphPtr->axes.table, name);
    if (hPtr != NULL) {
        RbcAxis        *axisPtr;

        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);
        if (!axisPtr->deletePending) {
            *axisPtrPtr = axisPtr;
            return TCL_OK;
        }
    }
    Tcl_AppendResult(graphPtr->interp, "can't find axis \"", name,
        "\" in \"", Tk_PathName(graphPtr->tkwin), "\"", (char *) NULL);
    *axisPtrPtr = NULL;
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * GetAxis --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetAxis(
    RbcGraph * graphPtr,
    const char *axisName,
    Tk_Uid classUid,
    RbcAxis ** axisPtrPtr)
{
    RbcAxis        *axisPtr;

    if (NameToAxis(graphPtr, axisName, &axisPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    if (classUid != NULL) {
        if ((axisPtr->refCount == 0) || (axisPtr->classUid == NULL)) {
            /* Set the axis type on the first use of it. */
            axisPtr->classUid = classUid;
        } else if (axisPtr->classUid != classUid) {
            Tcl_AppendResult(graphPtr->interp, "axis \"", axisName,
                "\" is already in use on an opposite ", axisPtr->classUid,
                "-axis", (char *) NULL);
            return TCL_ERROR;
        }
        axisPtr->refCount++;
    }
    *axisPtrPtr = axisPtr;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * FreeAxis --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
FreeAxis(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr)
{
    axisPtr->refCount--;
    if ((axisPtr->deletePending) && (axisPtr->refCount == 0)) {
        DestroyAxis(graphPtr, axisPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDestroyAxes --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcDestroyAxes(
    RbcGraph * graphPtr)
{
    Tcl_HashEntry  *hPtr;
    Tcl_HashSearch  cursor;
    RbcAxis        *axisPtr;
    int             i;

    for (hPtr = Tcl_FirstHashEntry(&graphPtr->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);
        axisPtr->hashPtr = NULL;
        DestroyAxis(graphPtr, axisPtr);
    }
    Tcl_DeleteHashTable(&graphPtr->axes.table);
    for (i = 0; i < 4; i++) {
        RbcChainDestroy(graphPtr->axisChain[i]);
    }
    Tcl_DeleteHashTable(&graphPtr->axes.tagTable);
    RbcChainDestroy(graphPtr->axes.displayList);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDefaultAxes --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcDefaultAxes(
    RbcGraph * graphPtr)
{
    register int    i;
    RbcAxis        *axisPtr;
    RbcChain       *chainPtr;
    static const char *axisNames[4] = { "x", "y", "x2", "y2" };
    int             flags;

    flags = RbcGraphType(graphPtr);
    for (i = 0; i < 4; i++) {
        chainPtr = RbcChainCreate();
        graphPtr->axisChain[i] = chainPtr;

        /* Create a default axis for each chain. */
        axisPtr = CreateAxis(graphPtr, axisNames[i], i);
        if (axisPtr == NULL) {
            return TCL_ERROR;
        }
        axisPtr->refCount = 1;  /* Default axes are assumed in use. */
        axisPtr->classUid = (i & 1) ? rbcYAxisUid : rbcXAxisUid;
        axisPtr->flags |= AXIS_ONSCREEN;

        /*
         * RbcConfigureWidgetComponent creates a temporary child window
         * by the name of the axis.  It's used so that the Tk routines
         * that access the X resource database can describe a single
         * component and not the entire graph.
         */
        if (RbcConfigureWidgetComponent(graphPtr->interp, graphPtr->tkwin,
                axisPtr->name, "Axis", configSpecs, 0, (const char **) NULL,
                (char *) axisPtr, flags) != TCL_OK) {
            return TCL_ERROR;
        }
        if (ConfigureAxis(graphPtr, axisPtr) != TCL_OK) {
            return TCL_ERROR;
        }
        axisPtr->linkPtr = RbcChainAppend(chainPtr, axisPtr);
        axisPtr->chainPtr = chainPtr;
    }
    return TCL_OK;
}

/*----------------------------------------------------------------------
 *
 * BindOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
BindOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int argc,
    const char **argv)
{
    Tcl_Interp     *interp = graphPtr->interp;

    return RbcConfigureBindings(interp, graphPtr->bindTable,
        RbcMakeAxisTag(graphPtr, axisPtr->name), argc, argv);
}

/*
 * ----------------------------------------------------------------------
 *
 * CgetOp --
 *
 *      Queries axis attributes (font, line width, label, etc).
 *
 * Results:
 *      Return value is a standard Tcl result.  If querying configuration
 *      values, interp->result will contain the results.
 *
 * Side Effects:
 *      TODO: SIde Effects
 *
 * ----------------------------------------------------------------------
 */
static int
CgetOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int argc,                   /* Not used. */
    const char *argv[])
{
    return Tk_ConfigureValue(graphPtr->interp, graphPtr->tkwin, configSpecs,
        (char *) axisPtr, argv[0], RbcGraphType(graphPtr));
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureOp --
 *
 *      Queries or resets axis attributes (font, line width, label, etc).
 *
 * Results:
 *      Return value is a standard Tcl result.  If querying configuration
 *      values, interp->result will contain the results.
 *
 * Side Effects:
 *      Axis resources are possibly allocated (GC, font). Axis layout is
 *      deferred until the height and width of the window are known.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int argc,
    const char *argv[])
{
    int             flags;

    flags = TK_CONFIG_ARGV_ONLY | RbcGraphType(graphPtr);
    if (argc == 0) {
        return Tk_ConfigureInfo(graphPtr->interp, graphPtr->tkwin, configSpecs,
            (char *) axisPtr, (char *) NULL, flags);
    } else if (argc == 1) {
        return Tk_ConfigureInfo(graphPtr->interp, graphPtr->tkwin, configSpecs,
            (char *) axisPtr, argv[0], flags);
    }
    if (Tk_ConfigureWidget(graphPtr->interp, graphPtr->tkwin, configSpecs,
            argc, argv, (char *) axisPtr, flags) != TCL_OK) {
        return TCL_ERROR;
    }
    if (ConfigureAxis(graphPtr, axisPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    if (axisPtr->flags & AXIS_ONSCREEN) {
        if (!RbcConfigModified(configSpecs, "-*color", "-background", "-bg",
                (char *) NULL)) {
            graphPtr->flags |= RBC_REDRAW_BACKING_STORE;
        }
        graphPtr->flags |= RBC_DRAW_MARGINS;
        RbcEventuallyRedrawGraph(graphPtr);
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * GetOp --
 *
 *      Returns the name of the picked axis (using the axis
 *      bind operation).  Right now, the only name accepted is
 *      "current".
 *
 * Results:
 *      A standard Tcl result.  The interpreter result will contain
 *      the name of the axis.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
GetOp(
    RbcGraph * graphPtr,
    int argc,                   /* Not used. */
    const char *argv[])
{
    Tcl_Interp     *interp = graphPtr->interp;
    register RbcAxis *axisPtr;

    axisPtr = (RbcAxis *) RbcGetCurrentItem(graphPtr->bindTable);
    /* Report only on axes. */
    if ((axisPtr != NULL) &&
        ((axisPtr->classUid == rbcXAxisUid) ||
            (axisPtr->classUid == rbcYAxisUid) ||
            (axisPtr->classUid == NULL))) {
        char            c;

        c = argv[3][0];
        if ((c == 'c') && (strcmp(argv[3], "current") == 0)) {
            Tcl_SetObjResult(interp, Tcl_NewStringObj(axisPtr->name, -1));
        } else if ((c == 'd') && (strcmp(argv[3], "detail") == 0)) {
            Tcl_SetObjResult(interp, Tcl_NewStringObj(axisPtr->detail, -1));
        }
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * LimitsOp --
 *
 *      This procedure returns a string representing the axis limits
 *      of the graph.  The format of the string is { left top right bottom}.
 *
 * Results:
 *      Always returns TCL_OK.  The interp->result field is
 *      a list of the graph axis limits.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
LimitsOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int argc,                   /* Not used. */
    const char **argv)
{                               /* Not used. */
    Tcl_Interp     *interp = graphPtr->interp;
    double          min, max;
    char stringDouble[TCL_DOUBLE_SPACE];

    if (graphPtr->flags & RBC_RESET_AXES) {
        RbcResetAxes(graphPtr);
    }
    if (axisPtr->logScale) {
        min = EXP10(axisPtr->axisRange.min);
        max = EXP10(axisPtr->axisRange.max);
    } else {
        min = axisPtr->axisRange.min;
        max = axisPtr->axisRange.max;
    }
    Tcl_PrintDouble(NULL, min, stringDouble);
    Tcl_AppendElement(interp, stringDouble);
    Tcl_PrintDouble(NULL, max, stringDouble);
    Tcl_AppendElement(interp, stringDouble);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * InvTransformOp --
 *
 *      Maps the given window coordinate into an axis-value.
 *
 * Results:
 *      Returns a standard Tcl result.  interp->result contains
 *      the axis value. If an error occurred, TCL_ERROR is returned
 *      and interp->result will contain an error message.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
InvTransformOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int argc,                   /* Not used. */
    const char **argv)
{
    int             x;          /* Integer window coordinate */
    double          y;          /* Real graph coordinate */
    char stringDouble[TCL_DOUBLE_SPACE];

    if (graphPtr->flags & RBC_RESET_AXES) {
        RbcResetAxes(graphPtr);
    }
    if (Tcl_GetInt(graphPtr->interp, argv[0], &x) != TCL_OK) {
        return TCL_ERROR;
    }
    /*
     * Is the axis vertical or horizontal?
     *
     * Check the site where the axis was positioned.  If the axis is
     * virtual, all we have to go on is how it was mapped to an
     * element (using either -mapx or -mapy options).
     */
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
        y = RbcInvHMap(graphPtr, axisPtr, (double) x);
    } else {
        y = RbcInvVMap(graphPtr, axisPtr, (double) x);
    }
    Tcl_PrintDouble(NULL, y, stringDouble);
    Tcl_AppendElement(graphPtr->interp, stringDouble);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * TransformOp --
 *
 *      Maps the given axis-value to a window coordinate.
 *
 * Results:
 *      Returns a standard Tcl result.  interp->result contains
 *      the window coordinate. If an error occurred, TCL_ERROR
 *      is returned and interp->result will contain an error
 *      message.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
TransformOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,
    int argc,                   /* Not used. */
    const char **argv)
{
    double          x;

    if (graphPtr->flags & RBC_RESET_AXES) {
        RbcResetAxes(graphPtr);
    }
    if (Tcl_ExprDouble(graphPtr->interp, argv[0], &x) != TCL_OK) {
        return TCL_ERROR;
    }
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
        x = RbcHMap(graphPtr, axisPtr, x);
    } else {
        x = RbcVMap(graphPtr, axisPtr, x);
    }
    Tcl_SetObjResult(graphPtr->interp, Tcl_NewIntObj((int) x));
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * UseOp --
 *
 *      Changes the virtual axis used by the logical axis.
 *
 * Results:
 *      A standard Tcl result.  If the named axis doesn't exist
 *      an error message is put in interp->result.
 *
 *      .g xaxis use "abc def gah"
 *      .g xaxis use [lappend abc [.g axis use]]
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
UseOp(
    RbcGraph * graphPtr,
    RbcAxis * axisPtr,          /* Not used. */
    int argc,
    const char **argv)
{
    RbcChain       *chainPtr;
    int             nNames;
    const char    **names;
    RbcChainLink   *linkPtr;
    int             i;
    Tk_Uid          classUid;
    int             margin;

    margin = (int) argv[-1];
    chainPtr = graphPtr->margins[margin].axes;
    if (argc == 0) {
        for (linkPtr = RbcChainFirstLink(chainPtr); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            axisPtr = RbcChainGetValue(linkPtr);
            Tcl_AppendElement(graphPtr->interp, axisPtr->name);
        }
        return TCL_OK;
    }
    if ((margin == RBC_MARGIN_BOTTOM) || (margin == RBC_MARGIN_TOP)) {
        classUid = (graphPtr->inverted) ? rbcYAxisUid : rbcXAxisUid;
    } else {
        classUid = (graphPtr->inverted) ? rbcXAxisUid : rbcYAxisUid;
    }
    if (Tcl_SplitList(graphPtr->interp, argv[0], &nNames, &names) != TCL_OK) {
        return TCL_ERROR;
    }
    for (linkPtr = RbcChainFirstLink(chainPtr); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        axisPtr = RbcChainGetValue(linkPtr);
        axisPtr->linkPtr = NULL;
        axisPtr->flags &= ~AXIS_ONSCREEN;
        /* Clear the axis type if it's not currently used. */
        if (axisPtr->refCount == 0) {
            axisPtr->classUid = NULL;
        }
    }
    RbcChainReset(chainPtr);
    for (i = 0; i < nNames; i++) {
        if (NameToAxis(graphPtr, names[i], &axisPtr) != TCL_OK) {
            ckfree((char *) names);
            return TCL_ERROR;
        }
        if (axisPtr->classUid == NULL) {
            axisPtr->classUid = classUid;
        } else if (axisPtr->classUid != classUid) {
            Tcl_AppendResult(graphPtr->interp, "wrong type axis \"",
                axisPtr->name, "\": can't use ", classUid, " type axis.",
                (char *) NULL);
            ckfree((char *) names);
            return TCL_ERROR;
        }
        if (axisPtr->linkPtr != NULL) {
            /* Move the axis from the old margin's "use" list to the new. */
            RbcChainUnlinkLink(axisPtr->chainPtr, axisPtr->linkPtr);
            RbcChainLinkBefore(chainPtr, axisPtr->linkPtr, (RbcChainLink *)NULL);/* append on end */
        } else {
            axisPtr->linkPtr = RbcChainAppend(chainPtr, axisPtr);
        }
        axisPtr->chainPtr = chainPtr;
        axisPtr->flags |= AXIS_ONSCREEN;
    }
    graphPtr->flags |=
        (RBC_GET_AXIS_GEOMETRY | RBC_LAYOUT_NEEDED | RBC_RESET_AXES);
    /* When any axis changes, we need to layout the entire graph.  */
    graphPtr->flags |= (RBC_MAP_WORLD | RBC_REDRAW_WORLD);
    RbcEventuallyRedrawGraph(graphPtr);

    ckfree((char *) names);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * CreateVirtualOp --
 *
 *      Creates a new axis.
 *
 * Results:
 *      Returns a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
CreateVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv)
{
    RbcAxis        *axisPtr;
    int             flags;

    axisPtr = CreateAxis(graphPtr, argv[3], RBC_MARGIN_NONE);
    if (axisPtr == NULL) {
        return TCL_ERROR;
    }
    flags = RbcGraphType(graphPtr);
    if (RbcConfigureWidgetComponent(graphPtr->interp, graphPtr->tkwin,
            axisPtr->name, "Axis", configSpecs, argc - 4, argv + 4,
            (char *) axisPtr, flags) != TCL_OK) {
        goto error;
    }
    if (ConfigureAxis(graphPtr, axisPtr) != TCL_OK) {
        goto error;
    }
    Tcl_SetResult(graphPtr->interp, axisPtr->name, TCL_VOLATILE);
    return TCL_OK;
  error:
    DestroyAxis(graphPtr, axisPtr);
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * BindVirtualOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
BindVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv)
{
    Tcl_Interp     *interp = graphPtr->interp;

    if (argc == 3) {
        Tcl_HashEntry  *hPtr;
        Tcl_HashSearch  cursor;
        char           *tagName;

        for (hPtr = Tcl_FirstHashEntry(&graphPtr->axes.tagTable, &cursor);
            hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
            tagName = Tcl_GetHashKey(&graphPtr->axes.tagTable, hPtr);
            Tcl_AppendElement(interp, tagName);
        }
        return TCL_OK;
    }
    return RbcConfigureBindings(interp, graphPtr->bindTable,
        RbcMakeAxisTag(graphPtr, argv[3]), argc - 4, argv + 4);
}

/*
 * ----------------------------------------------------------------------
 *
 * CgetVirtualOp --
 *
 *      Queries axis attributes (font, line width, label, etc).
 *
 * Results:
 *      Return value is a standard Tcl result.  If querying configuration
 *      values, interp->result will contain the results.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
CgetVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char *argv[])
{
    RbcAxis        *axisPtr;

    if (NameToAxis(graphPtr, argv[3], &axisPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    return CgetOp(graphPtr, axisPtr, argc - 4, argv + 4);
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureVirtualOp --
 *
 *      Queries or resets axis attributes (font, line width, label, etc).
 *
 * Results:
 *      Return value is a standard Tcl result.  If querying configuration
 *      values, interp->result will contain the results.
 *
 * Side Effects:
 *      Axis resources are possibly allocated (GC, font). Axis layout is
 *      deferred until the height and width of the window are known.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char *argv[])
{
    RbcAxis        *axisPtr;
    int             nNames, nOpts;
    const char    **options;
    register int    i;

    /* Figure out where the option value pairs begin */
    argc -= 3;
    argv += 3;
    for (i = 0; i < argc; i++) {
        if (argv[i][0] == '-') {
            break;
        }
        if (NameToAxis(graphPtr, argv[i], &axisPtr) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    nNames = i;                 /* Number of pen names specified */
    nOpts = argc - i;           /* Number of options specified */
    options = argv + i;         /* Start of options in argv  */

    for (i = 0; i < nNames; i++) {
        if (NameToAxis(graphPtr, argv[i], &axisPtr) != TCL_OK) {
            return TCL_ERROR;
        }
        if (ConfigureOp(graphPtr, axisPtr, nOpts, options) != TCL_OK) {
            break;
        }
    }
    if (i < nNames) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * DeleteVirtualOp --
 *
 *      Deletes one or more axes.  The actual removal may be deferred
 *      until the axis is no longer used by any element. The axis
 *      can't be referenced by its name any longer and it may be
 *      recreated.
 *
 * Results:
 *      Returns a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
DeleteVirtualOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv)
{
    register int    i;
    RbcAxis        *axisPtr;

    for (i = 3; i < argc; i++) {
        if (NameToAxis(graphPtr, argv[i], &axisPtr) != TCL_OK) {
            return TCL_ERROR;
        }
        axisPtr->deletePending = TRUE;
        if (axisPtr->refCount == 0) {
            DestroyAxis(graphPtr, axisPtr);
        }
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * InvTransformVirtualOp --
 *
 *      Maps the given window coordinate into an axis-value.
 *
 * Results:
 *      Returns a standard Tcl result.  interp->result contains
 *      the axis value. If an error occurred, TCL_ERROR is returned
 *      and interp->result will contain an error message.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
InvTransformVirtualOp(
    RbcGraph * graphPtr,
    int argc,                   /* Not used. */
    const char **argv)
{
    RbcAxis        *axisPtr;

    if (NameToAxis(graphPtr, argv[3], &axisPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    return InvTransformOp(graphPtr, axisPtr, argc - 4, argv + 4);
}

/*
 *--------------------------------------------------------------
 *
 * LimitsVirtualOp --
 *
 *      This procedure returns a string representing the axis limits
 *      of the graph.  The format of the string is { left top right bottom}.
 *
 * Results:
 *      Always returns TCL_OK.  The interp->result field is
 *      a list of the graph axis limits.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
LimitsVirtualOp(
    RbcGraph * graphPtr,
    int argc,                   /* Not used. */
    const char **argv)
{                               /* Not used. */
    RbcAxis        *axisPtr;

    if (NameToAxis(graphPtr, argv[3], &axisPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    return LimitsOp(graphPtr, axisPtr, argc - 4, argv + 4);
}

/*
 * ----------------------------------------------------------------------
 *
 * NamesVirtualOp --
 *
 *      Return a list of the names of all the axes.
 *
 * Results:
 *      Returns a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
NamesVirtualOp(
    RbcGraph * graphPtr,
    int argc,                   /* Not used. */
    const char **argv)
{                               /* Not used. */
    Tcl_HashEntry  *hPtr;
    Tcl_HashSearch  cursor;
    RbcAxis        *axisPtr;
    register int    i;

    for (hPtr = Tcl_FirstHashEntry(&graphPtr->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);
        if (axisPtr->deletePending) {
            continue;
        }
        if (argc == 3) {
            Tcl_AppendElement(graphPtr->interp, axisPtr->name);
            continue;
        }
        for (i = 3; i < argc; i++) {
            if (Tcl_StringMatch(axisPtr->name, argv[i])) {
                Tcl_AppendElement(graphPtr->interp, axisPtr->name);
                break;
            }
        }
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * TransformVirtualOp --
 *
 *	Maps the given axis-value to a window coordinate.
 *
 * Results:
 *      Returns a standard Tcl result.  interp->result contains
 *      the window coordinate. If an error occurred, TCL_ERROR
 *      is returned and interp->result will contain an error
 *      message.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
TransformVirtualOp(
    RbcGraph * graphPtr,
    int argc,                   /* Not used. */
    const char **argv)
{
    RbcAxis        *axisPtr;

    if (NameToAxis(graphPtr, argv[3], &axisPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    return TransformOp(graphPtr, axisPtr, argc - 4, argv + 4);
}

/*
 *----------------------------------------------------------------------
 *
 * ViewOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ViewOp(
    RbcGraph * graphPtr,
    int argc,
    const char **argv)
{
    RbcAxis        *axisPtr;
    Tcl_Interp     *interp = graphPtr->interp;
    double          axisOffset, scrollUnits;
    double          fract;
    double          viewMin, viewMax, worldMin, worldMax;
    double          viewWidth, worldWidth;
    char stringDouble[TCL_DOUBLE_SPACE];

    if (NameToAxis(graphPtr, argv[3], &axisPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    worldMin = axisPtr->valueRange.min;
    worldMax = axisPtr->valueRange.max;
    /* Override data dimensions with user-selected limits. */
    if (!TclIsNaN(axisPtr->scrollMin)) {
        worldMin = axisPtr->scrollMin;
    }
    if (!TclIsNaN(axisPtr->scrollMax)) {
        worldMax = axisPtr->scrollMax;
    }
    viewMin = axisPtr->min;
    viewMax = axisPtr->max;
    /* Bound the view within scroll region. */
    if (viewMin < worldMin) {
        viewMin = worldMin;
    }
    if (viewMax > worldMax) {
        viewMax = worldMax;
    }
    if (axisPtr->logScale) {
        worldMin = log10(worldMin);
        worldMax = log10(worldMax);
        viewMin = log10(viewMin);
        viewMax = log10(viewMax);
    }
    worldWidth = worldMax - worldMin;
    viewWidth = viewMax - viewMin;

    /* Unlike horizontal axes, vertical axis values run opposite of
     * the scrollbar first/last values.  So instead of pushing the
     * axis minimum around, we move the maximum instead. */

    if (AxisIsHorizontal(graphPtr, axisPtr) != axisPtr->descending) {
        axisOffset = viewMin - worldMin;
        scrollUnits = (double) axisPtr->scrollUnits * graphPtr->hScale;
    } else {
        axisOffset = worldMax - viewMax;
        scrollUnits = (double) axisPtr->scrollUnits * graphPtr->vScale;
    }
    if (argc == 4) {
        /* Note: Bound the fractions between 0.0 and 1.0 to support
         * "canvas"-style scrolling. */
        fract = axisOffset / worldWidth;
        Tcl_PrintDouble(interp, CLAMP(fract, 0.0, 1.0), stringDouble);
        Tcl_AppendElement(interp, stringDouble);
        fract = (axisOffset + viewWidth) / worldWidth;
        Tcl_PrintDouble(interp, CLAMP(fract, 0.0, 1.0), stringDouble);
        Tcl_AppendElement(interp, stringDouble);
        return TCL_OK;
    }
    fract = axisOffset / worldWidth;
    if (GetAxisScrollInfo(interp, argc - 4, argv + 4, &fract,
            viewWidth / worldWidth, scrollUnits) != TCL_OK) {
        return TCL_ERROR;
    }
    if (AxisIsHorizontal(graphPtr, axisPtr) != axisPtr->descending) {
        axisPtr->reqMin = (fract * worldWidth) + worldMin;
        axisPtr->reqMax = axisPtr->reqMin + viewWidth;
    } else {
        axisPtr->reqMax = worldMax - (fract * worldWidth);
        axisPtr->reqMin = axisPtr->reqMax - viewWidth;
    }
    if (axisPtr->logScale) {
        axisPtr->reqMin = EXP10(axisPtr->reqMin);
        axisPtr->reqMax = EXP10(axisPtr->reqMax);
    }
    graphPtr->flags |=
        (RBC_GET_AXIS_GEOMETRY | RBC_LAYOUT_NEEDED | RBC_RESET_AXES);
    RbcEventuallyRedrawGraph(graphPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcVirtualAxisOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcVirtualAxisOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcOp           proc;
    int             result;
    static RbcOpSpec axisOps[] = {
        {"bind", 1, (RbcOp) BindVirtualOp, 3, 6, "axisName sequence command",},
        {"cget", 2, (RbcOp) CgetVirtualOp, 5, 5, "axisName option",},
        {"configure", 2, (RbcOp) ConfigureVirtualOp, 4, 0,
            "axisName ?axisName?... ?option value?...",},
        {"create", 2, (RbcOp) CreateVirtualOp, 4, 0,
            "axisName ?option value?...",},
        {"delete", 1, (RbcOp) DeleteVirtualOp, 3, 0, "?axisName?...",},
        {"get", 1, (RbcOp) GetOp, 4, 4, "name",},
        {"invtransform", 1, (RbcOp) InvTransformVirtualOp, 5, 5,
            "axisName value",},
        {"limits", 1, (RbcOp) LimitsVirtualOp, 4, 4, "axisName",},
        {"names", 1, (RbcOp) NamesVirtualOp, 3, 0, "?pattern?...",},
        {"transform", 1, (RbcOp) TransformVirtualOp, 5, 5, "axisName value",},
        {"view", 1, (RbcOp) ViewOp, 4, 7,
            "axisName ?moveto fract? ?scroll number what?",},
    };
    static int      nAxisOps = sizeof(axisOps) / sizeof(RbcOpSpec);

    proc = RbcGetOp(interp, nAxisOps, axisOps, RBC_OP_ARG2, argc, argv, 0);
    if (proc == NULL) {
        return TCL_ERROR;
    }
    result = (*proc) (graphPtr, argc, argv);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcAxisOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcAxisOp(
    RbcGraph * graphPtr,
    int margin,
    int argc,
    const char **argv)
{
    int             result;
    RbcOp           proc;
    RbcAxis        *axisPtr;
    static RbcOpSpec axisOps[] = {
        {"bind", 1, (RbcOp) BindOp, 2, 5, "sequence command",},
        {"cget", 2, (RbcOp) CgetOp, 4, 4, "option",},
        {"configure", 2, (RbcOp) ConfigureOp, 3, 0, "?option value?...",},
        {"invtransform", 1, (RbcOp) InvTransformOp, 4, 4, "value",},
        {"limits", 1, (RbcOp) LimitsOp, 3, 3, "",},
        {"transform", 1, (RbcOp) TransformOp, 4, 4, "value",},
        {"use", 1, (RbcOp) UseOp, 3, 4, "?axisName?",},
    };
    static int      nAxisOps = sizeof(axisOps) / sizeof(RbcOpSpec);

    proc = RbcGetOp(graphPtr->interp, nAxisOps, axisOps, RBC_OP_ARG2,
        argc, argv, 0);
    if (proc == NULL) {
        return TCL_ERROR;
    }
    argv[2] = (char *) margin;  /* Hack. Slide a reference to the margin in
                                 * the argument list. Needed only for UseOp.
                                 */
    axisPtr = RbcGetFirstAxis(graphPtr->margins[margin].axes);
    result = (*proc) (graphPtr, axisPtr, argc - 3, argv + 3);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMapAxes --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcMapAxes(
    RbcGraph * graphPtr)
{
    RbcAxis        *axisPtr;
    RbcChain       *chainPtr;
    RbcChainLink   *linkPtr;
    register int    margin;
    int             offset;

    for (margin = 0; margin < 4; margin++) {
        chainPtr = graphPtr->margins[margin].axes;
        offset = 0;
        for (linkPtr = RbcChainFirstLink(chainPtr); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            axisPtr = RbcChainGetValue(linkPtr);
            if ((!axisPtr->hidden) && (axisPtr->flags & AXIS_ONSCREEN)) {
                MapAxis(graphPtr, axisPtr, offset, margin);
                if (AxisIsHorizontal(graphPtr, axisPtr)) {
                    offset += axisPtr->height;
                } else {
                    offset += axisPtr->width;
                }
            }
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDrawAxes --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcDrawAxes(
    RbcGraph * graphPtr,
    Drawable drawable)
{
    RbcAxis        *axisPtr;
    RbcChainLink   *linkPtr;
    register int    i;

    for (i = 0; i < 4; i++) {
        for (linkPtr = RbcChainFirstLink(graphPtr->margins[i].axes);
            linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
            axisPtr = RbcChainGetValue(linkPtr);
            if ((!axisPtr->hidden) && (axisPtr->flags & AXIS_ONSCREEN)) {
                DrawAxis(graphPtr, drawable, axisPtr);
            }
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcAxesToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcAxesToPostScript(
    RbcGraph * graphPtr,
    RbcPsToken * psToken)
{
    RbcAxis        *axisPtr;
    RbcChainLink   *linkPtr;
    register int    i;

    for (i = 0; i < 4; i++) {
        for (linkPtr = RbcChainFirstLink(graphPtr->margins[i].axes);
            linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
            axisPtr = RbcChainGetValue(linkPtr);
            if ((!axisPtr->hidden) && (axisPtr->flags & AXIS_ONSCREEN)) {
                AxisToPostScript(psToken, axisPtr);
            }
        }
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcDrawAxisLimits --
 *
 *      Draws the min/max values of the axis in the plotting area.
 *      The text strings are formatted according to the "sprintf"
 *      format descriptors in the limitsFormats array.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Draws the numeric values of the axis limits into the outer
 *      regions of the plotting area.
 *
 * ----------------------------------------------------------------------
 */
void
RbcDrawAxisLimits(
    RbcGraph * graphPtr,
    Drawable drawable)
{
    RbcAxis        *axisPtr;
    Tcl_HashEntry  *hPtr;
    Tcl_HashSearch  cursor;
    RbcDim2D        textDim;
    int             isHoriz;
    char           *minPtr, *maxPtr;
    const char     *minFormat, *maxFormat;
    char            minString[200], maxString[200];
    int             vMin, hMin, vMax, hMax;

#define SPACING 8
    vMin = vMax = graphPtr->left + graphPtr->padX.side1 + 2;
    hMin = hMax = graphPtr->bottom - graphPtr->padY.side2 - 2;  /* Offsets */

    for (hPtr = Tcl_FirstHashEntry(&graphPtr->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);

        if (axisPtr->nFormats == 0) {
            continue;
        }
        isHoriz = AxisIsHorizontal(graphPtr, axisPtr);
        minPtr = maxPtr = NULL;
        minFormat = maxFormat = axisPtr->limitsFormats[0];
        if (axisPtr->nFormats > 1) {
            maxFormat = axisPtr->limitsFormats[1];
        }
        if (minFormat[0] != '\0') {
            minPtr = minString;
            sprintf(minString, minFormat, axisPtr->axisRange.min);
        }
        if (maxFormat[0] != '\0') {
            maxPtr = maxString;
            sprintf(maxString, maxFormat, axisPtr->axisRange.max);
        }
        if (axisPtr->descending) {
            char           *tmp;

            tmp = minPtr, minPtr = maxPtr, maxPtr = tmp;
        }
        if (maxPtr != NULL) {
            if (isHoriz) {
                axisPtr->limitsTextStyle.theta = 90.0;
                axisPtr->limitsTextStyle.anchor = TK_ANCHOR_SE;
                RbcDrawText2(graphPtr->tkwin, drawable, maxPtr,
                    &axisPtr->limitsTextStyle, graphPtr->right, hMax, &textDim);
                hMax -= (textDim.height + SPACING);
            } else {
                axisPtr->limitsTextStyle.theta = 0.0;
                axisPtr->limitsTextStyle.anchor = TK_ANCHOR_NW;
                RbcDrawText2(graphPtr->tkwin, drawable, maxPtr,
                    &axisPtr->limitsTextStyle, vMax, graphPtr->top, &textDim);
                vMax += (textDim.width + SPACING);
            }
        }
        if (minPtr != NULL) {
            axisPtr->limitsTextStyle.anchor = TK_ANCHOR_SW;
            if (isHoriz) {
                axisPtr->limitsTextStyle.theta = 90.0;
                RbcDrawText2(graphPtr->tkwin, drawable, minPtr,
                    &axisPtr->limitsTextStyle, graphPtr->left, hMin, &textDim);
                hMin -= (textDim.height + SPACING);
            } else {
                axisPtr->limitsTextStyle.theta = 0.0;
                RbcDrawText2(graphPtr->tkwin, drawable, minPtr,
                    &axisPtr->limitsTextStyle, vMin, graphPtr->bottom,
                    &textDim);
                vMin += (textDim.width + SPACING);
            }
        }
    }                           /* Loop on axes */
}

/*
 *----------------------------------------------------------------------
 *
 * RbcAxisLimitsToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcAxisLimitsToPostScript(
    RbcGraph * graphPtr,
    RbcPsToken * psToken)
{
    RbcAxis        *axisPtr;
    Tcl_HashEntry  *hPtr;
    Tcl_HashSearch  cursor;
    double          vMin, hMin, vMax, hMax;
    char            string[200];
    int             textWidth, textHeight;
    const char     *minFmt, *maxFmt;

#define SPACING 8
    vMin = vMax = graphPtr->left + graphPtr->padX.side1 + 2;
    hMin = hMax = graphPtr->bottom - graphPtr->padY.side2 - 2;  /* Offsets */
    for (hPtr = Tcl_FirstHashEntry(&graphPtr->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);

        if (axisPtr->nFormats == 0) {
            continue;
        }
        minFmt = maxFmt = axisPtr->limitsFormats[0];
        if (axisPtr->nFormats > 1) {
            maxFmt = axisPtr->limitsFormats[1];
        }
        if (*maxFmt != '\0') {
            sprintf(string, maxFmt, axisPtr->axisRange.max);
            RbcGetTextExtents(&axisPtr->tickTextStyle, string, &textWidth,
                &textHeight);
            if ((textWidth > 0) && (textHeight > 0)) {
                if (axisPtr->classUid == rbcXAxisUid) {
                    axisPtr->limitsTextStyle.theta = 90.0;
                    axisPtr->limitsTextStyle.anchor = TK_ANCHOR_SE;
                    RbcTextToPostScript(psToken, string,
                        &axisPtr->limitsTextStyle,
                        (double) graphPtr->right, hMax);
                    hMax -= (textWidth + SPACING);
                } else {
                    axisPtr->limitsTextStyle.theta = 0.0;
                    axisPtr->limitsTextStyle.anchor = TK_ANCHOR_NW;
                    RbcTextToPostScript(psToken, string,
                        &axisPtr->limitsTextStyle, vMax,
                        (double) graphPtr->top);
                    vMax += (textWidth + SPACING);
                }
            }
        }
        if (*minFmt != '\0') {
            sprintf(string, minFmt, axisPtr->axisRange.min);
            RbcGetTextExtents(&axisPtr->tickTextStyle, string, &textWidth,
                &textHeight);
            if ((textWidth > 0) && (textHeight > 0)) {
                axisPtr->limitsTextStyle.anchor = TK_ANCHOR_SW;
                if (axisPtr->classUid == rbcXAxisUid) {
                    axisPtr->limitsTextStyle.theta = 90.0;
                    RbcTextToPostScript(psToken, string,
                        &axisPtr->limitsTextStyle,
                        (double) graphPtr->left, hMin);
                    hMin -= (textWidth + SPACING);
                } else {
                    axisPtr->limitsTextStyle.theta = 0.0;
                    RbcTextToPostScript(psToken, string,
                        &axisPtr->limitsTextStyle,
                        vMin, (double) graphPtr->bottom);
                    vMin += (textWidth + SPACING);
                }
            }
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGetFirstAxis --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcAxis        *
RbcGetFirstAxis(
    RbcChain * chainPtr)
{
    RbcChainLink   *linkPtr;

    linkPtr = RbcChainFirstLink(chainPtr);
    if (linkPtr == NULL) {
        return NULL;
    }
    return RbcChainGetValue(linkPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcNearestAxis --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcAxis        *
RbcNearestAxis(
    RbcGraph * graphPtr,
    int x,                      /* Point to be tested */
    int y)
{                               /* Point to be tested */
    register Tcl_HashEntry *hPtr;
    Tcl_HashSearch  cursor;
    RbcAxis        *axisPtr;
    int             width, height;
    double          rotWidth, rotHeight;
    RbcPoint2D      bbox[5];

    for (hPtr = Tcl_FirstHashEntry(&graphPtr->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);
        if ((axisPtr->hidden) || (!(axisPtr->flags & AXIS_ONSCREEN))) {
            continue;           /* Don't check hidden axes or axes
                                 * that are virtual. */
        }
        if (axisPtr->showTicks) {
            register RbcChainLink *linkPtr;
            TickLabel      *labelPtr;
            RbcPoint2D      t;

            for (linkPtr = RbcChainFirstLink(axisPtr->tickLabels);
                linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
                labelPtr = RbcChainGetValue(linkPtr);
                RbcGetBoundingBox(labelPtr->width, labelPtr->height,
                    axisPtr->tickTextStyle.theta, &rotWidth, &rotHeight, bbox);
                width = ROUND(rotWidth);
                height = ROUND(rotHeight);
                t = RbcTranslatePoint(&labelPtr->anchorPos, width, height,
                    axisPtr->tickTextStyle.anchor);
                t.x = x - t.x - (width * 0.5);
                t.y = y - t.y - (height * 0.5);

                bbox[4] = bbox[0];
                if (RbcPointInPolygon(&t, bbox, 5)) {
                    axisPtr->detail = "label";
                    return axisPtr;
                }
            }
        }
        if (axisPtr->title != NULL) {   /* and then the title string. */
            RbcPoint2D      t;

            RbcGetTextExtents(&axisPtr->titleTextStyle, axisPtr->title, &width,
                &height);
            RbcGetBoundingBox(width, height, axisPtr->titleTextStyle.theta,
                &rotWidth, &rotHeight, bbox);
            width = ROUND(rotWidth);
            height = ROUND(rotHeight);
            t = RbcTranslatePoint(&axisPtr->titlePos, width, height,
                axisPtr->titleTextStyle.anchor);
            /* Translate the point so that the 0,0 is the upper left
             * corner of the bounding box.  */
            t.x = x - t.x - (width / 2);
            t.y = y - t.y - (height / 2);

            bbox[4] = bbox[0];
            if (RbcPointInPolygon(&t, bbox, 5)) {
                axisPtr->detail = "title";
                return axisPtr;
            }
        }
        if (axisPtr->lineWidth > 0) {   /* Check for the axis region */
            if (RbcPointInRegion(&axisPtr->region, x, y)) {
                axisPtr->detail = "line";
                return axisPtr;
            }
        }
    }
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMakeAxisTag --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
ClientData
RbcMakeAxisTag(
    RbcGraph * graphPtr,
    const char *tagName)
{
    Tcl_HashEntry  *hPtr;
    int             isNew;

    hPtr = Tcl_CreateHashEntry(&graphPtr->axes.tagTable, tagName, &isNew);
    assert(hPtr);
    return Tcl_GetHashKey(&graphPtr->axes.tagTable, hPtr);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted generic/rbc/rbcGrBar.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
/*
 * rbcGrBar.c --
 *
 *      This module implements barchart elements for the rbc graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "rbcInt.h"

/*
 * -------------------------------------------------------------------
 *
 * FreqKey --
 *
 *
 * -------------------------------------------------------------------
 */
typedef struct {
    double          value;      /* Duplicated abscissa */
    RbcAxis2D       axes;       /* Axis mapping of element */
} FreqKey;

typedef struct {
    char           *name;       /* Pen style identifier.  If NULL pen
                                 * was statically allocated. */
    Tk_Uid          classUid;   /* Type of pen */
    char           *typeId;     /* String token identifying the type of pen */
    unsigned int    flags;      /* Indicates if the pen element is active or
                                 * normal */
    int             refCount;   /* Reference count for elements using
                                 * this pen. */
    Tcl_HashEntry  *hashPtr;
    Tk_ConfigSpec  *specsPtr;   /* Configuration specifications */

    PenConfigureProc *configProc;
    PenDestroyProc *destroyProc;

    XColor         *fgColor;    /* Foreground color of bar */
    Tk_3DBorder     border;     /* 3D border and background color */
    int             borderWidth;        /* 3D border width of bar */
    int             relief;     /* Relief of the bar */
    Pixmap          stipple;    /* Stipple */
    GC              gc;         /* Graphics context */

    /* Error bar attributes. */
    int             errorBarShow;       /* Describes which error bars to
                                         * display: none, x, y, or * both. */

    int             errorBarLineWidth;  /* Width of the error bar segments. */

    int             errorBarCapWidth;
    XColor         *errorBarColor;      /* Color of the error bar. */

    GC              errorBarGC; /* Error bar graphics context. */

    /* Show value attributes. */
    int             valueShow;  /* Indicates whether to display data value.
                                 * Values are x, y, or none. */

    char           *valueFormat;        /* A printf format string. */
    RbcTextStyle    valueStyle; /* Text attributes (color, font,
                                 * rotation, etc.) of the value. */

} BarPen;

typedef struct {
    RbcElemWeight   weight;     /* Weight range where this pen is valid. */

    BarPen         *penPtr;     /* Pen to draw */

    RbcSegment2D   *xErrorBars; /* Point to start of this pen's X-error bar
                                 * segments in the element's array. */

    RbcSegment2D   *yErrorBars; /* Point to start of this pen's Y-error bar
                                 * segments in the element's array. */
    int             xErrorBarCnt;       /* # of error bars for this pen. */

    int             yErrorBarCnt;       /* # of error bars for this pen. */

    int             errorBarCapWidth;   /* Length of the cap ends on each
                                         * error bar. */

    int             symbolSize; /* Size of the pen's symbol scaled to the
                                 * current graph size. */

    /* Bar chart specific data. */
    XRectangle     *rectangles; /* Indicates starting location in bar
                                 * array for this pen. */
    int             nRects;     /* Number of bar segments for this pen. */

} BarPenStyle;

typedef struct {
    char           *name;       /* Identifier to refer the
                                 * element. Used in the "insert",
                                 * "delete", or "show", commands. */

    Tk_Uid          classUid;   /* Type of element; either
                                 * rbcBarElementUid, rbcLineElementUid, or
                                 * rbcStripElementUid. */

    RbcGraph       *graphPtr;   /* Graph widget of element */
    unsigned int    flags;      /* Indicates if the entire element is
                                 * active, or if coordinates need to
                                 * be calculated */
    char          **tags;
    int             hidden;     /* If non-zero, don't display the element. */

    Tcl_HashEntry  *hashPtr;
    char           *label;      /* Label displayed in legend */
    int             labelRelief;        /* Relief of label in legend. */

    RbcAxis2D       axes;
    RbcElemVector   x, y, w;    /* Contains array of numeric values */

    RbcElemVector   xError;     /* Relative/symmetric X error values. */
    RbcElemVector   yError;     /* Relative/symmetric Y error values. */
    RbcElemVector   xHigh, xLow;        /* Absolute/asymmetric X-coordinate high/low
                                           error values. */
    RbcElemVector   yHigh, yLow;        /* Absolute/asymmetric Y-coordinate high/low
                                           error values. */

    int            *activeIndices;      /* Array of indices (malloc-ed) that
                                         * indicate the data points have been
                                         * selected as active (drawn with
                                         * "active" colors). */

    int             nActiveIndices;     /* Number of active data points. Special
                                         * case: if nActiveIndices < 0 and the
                                         * active bit is set in "flags", then all
                                         * data points are drawn active. */

    RbcElementProcs *procsPtr;  /* Class information for bar elements */
    Tk_ConfigSpec  *specsPtr;   /* Configuration specifications */

    RbcSegment2D   *xErrorBars; /* Point to start of this pen's X-error bar
                                 * segments in the element's array. */
    RbcSegment2D   *yErrorBars; /* Point to start of this pen's Y-error bar
                                 * segments in the element's array. */
    int             xErrorBarCnt;       /* # of error bars for this pen. */
    int             yErrorBarCnt;       /* # of error bars for this pen. */

    int            *xErrorToData;       /* Maps individual error bar segments back
                                         * to the data point associated with it. */
    int            *yErrorToData;       /* Maps individual error bar segments back
                                         * to the data point associated with it. */

    int             errorBarCapWidth;   /* Length of cap on error bars */

    BarPen         *activePenPtr;       /* Standard Pens */
    BarPen         *normalPenPtr;

    RbcChain       *palette;    /* Chain of pen style information. */

    /* Symbol scaling */
    int             scaleSymbols;       /* If non-zero, the symbols will scale
                                         * in size as the graph is zoomed
                                         * in/out.  */

    double          xRange, yRange;     /* Initial X-axis and Y-axis ranges:
                                         * used to scale the size of element's
                                         * symbol. */
    int             state;
    /*
     * Bar specific attributes
     */
    BarPen          builtinPen;

    int            *rectToData;
    XRectangle     *rectangles; /* Array of rectangles comprising the bar
                                 * segments of the element. */
    int             nRects;     /* # of visible bar segments for element */

    int             padX;       /* Spacing on either side of bar */
    double          barWidth;
    int             nActive;

    XRectangle     *activeRects;
    int            *activeToData;
} Bar;

extern Tk_CustomOption rbcBarPenOption;
extern Tk_CustomOption rbcDataOption;
extern Tk_CustomOption rbcDataPairsOption;
extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcListOption;
extern Tk_CustomOption rbcXAxisOption;
extern Tk_CustomOption rbcYAxisOption;
extern Tk_CustomOption rbcShadowOption;
extern Tk_CustomOption rbcFillOption;
extern Tk_CustomOption rbcColorOption;
extern Tk_CustomOption rbcStateOption;

static Tk_OptionParseProc StringToBarMode;
static Tk_OptionPrintProc BarModeToString;

static Tk_CustomOption stylesOption = {
    RbcStringToStyles, RbcStylesToString, (ClientData) sizeof(BarPenStyle)
};

Tk_CustomOption rbcBarModeOption = {
    StringToBarMode, BarModeToString, (ClientData) 0
};

#define DEF_BAR_ACTIVE_PEN          "activeBar"
#define DEF_BAR_AXIS_X              "x"
#define DEF_BAR_AXIS_Y              "y"
#define DEF_BAR_BACKGROUND          "navyblue"
#define DEF_BAR_BG_MONO             "black"
#define DEF_BAR_BORDERWIDTH         "2"
#define DEF_BAR_DATA                (char *)NULL
#define DEF_BAR_ERRORBAR_COLOR      "defcolor"
#define DEF_BAR_ERRORBAR_LINE_WIDTH "1"
#define DEF_BAR_ERRORBAR_CAP_WIDTH  "1"
#define DEF_BAR_FOREGROUND          "blue"
#define DEF_BAR_FG_MONO             "white"
#define DEF_BAR_HIDE                "no"
#define DEF_BAR_LABEL               (char *)NULL
#define DEF_BAR_LABEL_RELIEF        "flat"
#define DEF_BAR_NORMAL_STIPPLE      ""
#define DEF_BAR_RELIEF              "raised"
#define DEF_BAR_SHOW_ERRORBARS      "both"
#define DEF_BAR_STATE               "normal"
#define DEF_BAR_STYLES              ""
#define DEF_BAR_TAGS                "all"
#define DEF_BAR_WIDTH               "0.0"
#define DEF_BAR_DATA                (char *)NULL

#define DEF_PEN_ACTIVE_BACKGROUND   "red"
#define DEF_PEN_ACTIVE_BG_MONO      "white"
#define DEF_PEN_ACTIVE_FOREGROUND   "pink"
#define DEF_PEN_ACTIVE_FG_MONO      "black"
#define DEF_PEN_BORDERWIDTH         "2"
#define DEF_PEN_NORMAL_BACKGROUND   "navyblue"
#define DEF_PEN_NORMAL_BG_MONO      "black"
#define DEF_PEN_NORMAL_FOREGROUND   "blue"
#define DEF_PEN_NORMAL_FG_MONO      "white"
#define DEF_PEN_RELIEF              "raised"
#define DEF_PEN_STIPPLE             ""
#define DEF_PEN_TYPE                "bar"
#define	DEF_PEN_VALUE_ANCHOR        "s"
#define	DEF_PEN_VALUE_COLOR         "black"
#define	DEF_PEN_VALUE_FONT          RBC_FONT_SMALL
#define	DEF_PEN_VALUE_FORMAT        "%g"
#define	DEF_PEN_VALUE_ROTATE        (char *)NULL
#define	DEF_PEN_VALUE_SHADOW        (char *)NULL
#define DEF_PEN_SHOW_VALUES         "no"

#define FreeElemVector(v) \
    if ((v).clientId != NULL) { \
	Rbc_FreeVectorId((v).clientId); \
    } else if ((v).valueArr != NULL) { \
	ckfree((char *)(v).valueArr); \
    }

static Tk_ConfigSpec barPenConfigSpecs[] = {
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_PEN_ACTIVE_BACKGROUND, Tk_Offset(BarPen, border),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY | RBC_ACTIVE_PEN},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_PEN_ACTIVE_BACKGROUND, Tk_Offset(BarPen, border),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY | RBC_ACTIVE_PEN},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_PEN_NORMAL_BACKGROUND, Tk_Offset(BarPen, border),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY | RBC_NORMAL_PEN},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_PEN_NORMAL_BACKGROUND, Tk_Offset(BarPen, border),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY | RBC_NORMAL_PEN},
    {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, (char *) NULL, 0,
        RBC_ALL_PENS},
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, (char *) NULL, 0,
        RBC_ALL_PENS},
    {TK_CONFIG_CUSTOM, "-borderwidth", "borderWidth", "BorderWidth",
            DEF_PEN_BORDERWIDTH, Tk_Offset(BarPen, borderWidth), RBC_ALL_PENS,
        &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-errorbarcolor", "errorBarColor", "ErrorBarColor",
            DEF_BAR_ERRORBAR_COLOR, Tk_Offset(BarPen, errorBarColor),
        RBC_ALL_PENS, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-errorbarwidth", "errorBarWidth", "ErrorBarWidth",
            DEF_BAR_ERRORBAR_LINE_WIDTH, Tk_Offset(BarPen, errorBarLineWidth),
        RBC_ALL_PENS | TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-errorbarcap", "errorBarCap", "ErrorBarCap",
            DEF_BAR_ERRORBAR_CAP_WIDTH, Tk_Offset(BarPen, errorBarCapWidth),
        RBC_ALL_PENS | TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL, (char *) NULL, 0,
        RBC_ALL_PENS},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_PEN_ACTIVE_FOREGROUND, Tk_Offset(BarPen, fgColor),
        RBC_ACTIVE_PEN | TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_PEN_ACTIVE_FOREGROUND, Tk_Offset(BarPen, fgColor),
        RBC_ACTIVE_PEN | TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_PEN_NORMAL_FOREGROUND, Tk_Offset(BarPen, fgColor),
        RBC_NORMAL_PEN | TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_PEN_NORMAL_FOREGROUND, Tk_Offset(BarPen, fgColor),
        RBC_NORMAL_PEN | TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", DEF_PEN_RELIEF,
        Tk_Offset(BarPen, relief), RBC_ALL_PENS},
    {TK_CONFIG_CUSTOM, "-showerrorbars", "showErrorBars", "ShowErrorBars",
            DEF_BAR_SHOW_ERRORBARS, Tk_Offset(BarPen, errorBarShow),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_CUSTOM, "-showvalues", "showValues", "ShowValues",
            DEF_PEN_SHOW_VALUES, Tk_Offset(BarPen, valueShow),
        RBC_ALL_PENS | TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_BITMAP, "-stipple", "stipple", "Stipple", DEF_PEN_STIPPLE,
        Tk_Offset(BarPen, stipple), RBC_ALL_PENS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_STRING, "-type", (char *) NULL, (char *) NULL, DEF_PEN_TYPE,
        Tk_Offset(BarPen, typeId), RBC_ALL_PENS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_ANCHOR, "-valueanchor", "valueAnchor", "ValueAnchor",
            DEF_PEN_VALUE_ANCHOR, Tk_Offset(BarPen, valueStyle.anchor),
        RBC_ALL_PENS},
    {TK_CONFIG_COLOR, "-valuecolor", "valueColor", "ValueColor",
            DEF_PEN_VALUE_COLOR, Tk_Offset(BarPen, valueStyle.color),
        RBC_ALL_PENS},
    {TK_CONFIG_FONT, "-valuefont", "valueFont", "ValueFont", DEF_PEN_VALUE_FONT,
        Tk_Offset(BarPen, valueStyle.font), RBC_ALL_PENS},
    {TK_CONFIG_STRING, "-valueformat", "valueFormat", "ValueFormat",
            DEF_PEN_VALUE_FORMAT, Tk_Offset(BarPen, valueFormat),
        RBC_ALL_PENS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_DOUBLE, "-valuerotate", "valueRotate", "ValueRotate",
            DEF_PEN_VALUE_ROTATE, Tk_Offset(BarPen, valueStyle.theta),
        RBC_ALL_PENS},
    {TK_CONFIG_CUSTOM, "-valueshadow", "valueShadow", "ValueShadow",
            DEF_PEN_VALUE_SHADOW, Tk_Offset(BarPen, valueStyle.shadow),
        RBC_ALL_PENS, &rbcShadowOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

static Tk_ConfigSpec barElemConfigSpecs[] = {
    {TK_CONFIG_CUSTOM, "-activepen", "activePen", "ActivePen",
            DEF_BAR_ACTIVE_PEN, Tk_Offset(Bar, activePenPtr), TK_CONFIG_NULL_OK,
        &rbcBarPenOption},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_BAR_BACKGROUND, Tk_Offset(Bar, builtinPen.border),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_BAR_BACKGROUND, Tk_Offset(Bar, builtinPen.border),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_DOUBLE, "-barwidth", "barWidth", "BarWidth", DEF_BAR_WIDTH,
        Tk_Offset(Bar, barWidth), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL, (char *) NULL, 0,
        0},
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL, (char *) NULL, 0,
        0},
    {TK_CONFIG_CUSTOM, "-bindtags", "bindTags", "BindTags", DEF_BAR_TAGS,
        Tk_Offset(Bar, tags), TK_CONFIG_NULL_OK, &rbcListOption},
    {TK_CONFIG_CUSTOM, "-borderwidth", "borderWidth", "BorderWidth",
            DEF_BAR_BORDERWIDTH, Tk_Offset(Bar, builtinPen.borderWidth), 0,
        &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-errorbarcolor", "errorBarColor", "ErrorBarColor",
            DEF_BAR_ERRORBAR_COLOR, Tk_Offset(Bar, builtinPen.errorBarColor), 0,
        &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-errorbarwidth", "errorBarWidth", "ErrorBarWidth",
            DEF_BAR_ERRORBAR_LINE_WIDTH, Tk_Offset(Bar,
                builtinPen.errorBarLineWidth), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-errorbarcap", "errorBarCap", "ErrorBarCap",
            DEF_BAR_ERRORBAR_CAP_WIDTH, Tk_Offset(Bar,
                builtinPen.errorBarCapWidth),
        RBC_ALL_PENS | TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL, (char *) NULL, 0,
        0},
    {TK_CONFIG_CUSTOM, "-data", "data", "Data", (char *) NULL, 0, 0,
        &rbcDataPairsOption},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_BAR_FOREGROUND, Tk_Offset(Bar, builtinPen.fgColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_BAR_FOREGROUND, Tk_Offset(Bar, builtinPen.fgColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_STRING, "-label", "label", "Label", DEF_BAR_LABEL, Tk_Offset(Bar,
            label), TK_CONFIG_NULL_OK},
    {TK_CONFIG_RELIEF, "-labelrelief", "labelRelief", "LabelRelief",
            DEF_BAR_LABEL_RELIEF, Tk_Offset(Bar, labelRelief),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide", DEF_BAR_HIDE, Tk_Offset(Bar,
            hidden), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX", DEF_BAR_AXIS_X, Tk_Offset(Bar,
            axes.x), 0, &rbcXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapy", "mapY", "MapY", DEF_BAR_AXIS_Y, Tk_Offset(Bar,
            axes.y), 0, &rbcYAxisOption},
    {TK_CONFIG_CUSTOM, "-pen", "pen", "Pen", (char *) NULL, Tk_Offset(Bar,
            normalPenPtr), TK_CONFIG_NULL_OK, &rbcBarPenOption},
    {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", DEF_BAR_RELIEF,
        Tk_Offset(Bar, builtinPen.relief), 0},
    {TK_CONFIG_CUSTOM, "-showerrorbars", "showErrorBars", "ShowErrorBars",
            DEF_BAR_SHOW_ERRORBARS, Tk_Offset(Bar, builtinPen.errorBarShow),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_CUSTOM, "-showvalues", "showValues", "ShowValues",
            DEF_PEN_SHOW_VALUES, Tk_Offset(Bar, builtinPen.valueShow),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_CUSTOM, "-state", "state", "State", DEF_BAR_STATE, Tk_Offset(Bar,
            state), TK_CONFIG_DONT_SET_DEFAULT, &rbcStateOption},
    {TK_CONFIG_BITMAP, "-stipple", "stipple", "Stipple", DEF_BAR_NORMAL_STIPPLE,
        Tk_Offset(Bar, builtinPen.stipple), TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-styles", "styles", "Styles", DEF_BAR_STYLES,
        Tk_Offset(Bar, palette), TK_CONFIG_NULL_OK, &stylesOption},
    {TK_CONFIG_ANCHOR, "-valueanchor", "valueAnchor", "ValueAnchor",
            DEF_PEN_VALUE_ANCHOR, Tk_Offset(Bar, builtinPen.valueStyle.anchor),
        0},
    {TK_CONFIG_COLOR, "-valuecolor", "valueColor", "ValueColor",
            DEF_PEN_VALUE_COLOR, Tk_Offset(Bar, builtinPen.valueStyle.color),
        0},
    {TK_CONFIG_FONT, "-valuefont", "valueFont", "ValueFont", DEF_PEN_VALUE_FONT,
        Tk_Offset(Bar, builtinPen.valueStyle.font), 0},
    {TK_CONFIG_STRING, "-valueformat", "valueFormat", "ValueFormat",
            DEF_PEN_VALUE_FORMAT, Tk_Offset(Bar, builtinPen.valueFormat),
        TK_CONFIG_NULL_OK},
    {TK_CONFIG_DOUBLE, "-valuerotate", "valueRotate", "ValueRotate",
            DEF_PEN_VALUE_ROTATE, Tk_Offset(Bar, builtinPen.valueStyle.theta),
        0},
    {TK_CONFIG_CUSTOM, "-valueshadow", "valueShadow", "ValueShadow",
            DEF_PEN_VALUE_SHADOW, Tk_Offset(Bar, builtinPen.valueStyle.shadow),
        0, &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-weights", "weights", "Weights", (char *) NULL,
        Tk_Offset(Bar, w), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-x", "xdata", "Xdata", DEF_BAR_DATA, Tk_Offset(Bar, x),
        0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-y", "ydata", "Ydata", DEF_BAR_DATA, Tk_Offset(Bar, y),
        0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xdata", "xdata", "Xdata", DEF_BAR_DATA, Tk_Offset(Bar,
            x), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-ydata", "ydata", "Ydata", DEF_BAR_DATA, Tk_Offset(Bar,
            y), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xerror", "xError", "XError", DEF_BAR_DATA,
        Tk_Offset(Bar, xError), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xhigh", "xHigh", "XHigh", DEF_BAR_DATA, Tk_Offset(Bar,
            xHigh), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xlow", "xLow", "XLow", DEF_BAR_DATA, Tk_Offset(Bar,
            xLow), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-yerror", "yError", "YError", DEF_BAR_DATA,
        Tk_Offset(Bar, yError), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-yhigh", "yHigh", "YHigh", DEF_BAR_DATA, Tk_Offset(Bar,
            yHigh), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-ylow", "yLow", "YLow", DEF_BAR_DATA, Tk_Offset(Bar,
            yLow), 0, &rbcDataOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

/* Forward declarations */
static PenConfigureProc ConfigurePen;
static PenDestroyProc DestroyPen;
static RbcElementClosestProc ClosestBar;
static RbcElementConfigProc ConfigureBar;
static RbcElementDestroyProc DestroyBar;
static RbcElementDrawProc DrawActiveBar;
static RbcElementDrawProc DrawNormalBar;
static RbcElementDrawSymbolProc DrawSymbol;
static RbcElementExtentsProc GetBarExtents;
static RbcElementToPostScriptProc ActiveBarToPostScript;
static RbcElementToPostScriptProc NormalBarToPostScript;
static RbcElementSymbolToPostScriptProc SymbolToPostScript;
static RbcElementMapProc MapBar;

static int      Round(
    register double x);
static const char *NameOfBarMode(
    RbcBarMode mode);
static void     ClearPalette(
    RbcChain * palette);
static void     InitPen(
    BarPen * penPtr);
static void     CheckStacks(
    RbcGraph * graphPtr,
    RbcAxis2D * pairPtr,
    double *minPtr,
    double *maxPtr);
static void     MergePens(
    Bar * barPtr,
    RbcPenStyle ** dataToStyle);
static void     MapActiveBars(
    Bar * barPtr);
static void     ResetBar(
    Bar * barPtr);
static void     DrawBarSegments(
    RbcGraph * graphPtr,
    Drawable drawable,
    BarPen * penPtr,
    XRectangle * rectangles,
    int nRects);
static void     DrawBarValues(
    RbcGraph * graphPtr,
    Drawable drawable,
    Bar * barPtr,
    BarPen * penPtr,
    XRectangle * rectangles,
    int nRects,
    int *rectToData);
static void     SegmentsToPostScript(
    RbcGraph * graphPtr,
    RbcPsToken * psToken,
    BarPen * penPtr,
    register XRectangle * rectPtr,
    int nRects);
static void     BarValuesToPostScript(
    RbcGraph * graphPtr,
    RbcPsToken * psToken,
    Bar * barPtr,
    BarPen * penPtr,
    XRectangle * rectangles,
    int nRects,
    int *rectToData);

/*
 *----------------------------------------------------------------------
 *
 * Round --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
Round(
    register double x)
{
    return (int) (x + ((x < 0.0) ? -0.5 : 0.5));
}

/*
 * ----------------------------------------------------------------------
 * Custom option parse and print procedures
 * ----------------------------------------------------------------------
 */

/*
 * ----------------------------------------------------------------------
 *
 * NameOfBarMode --
 *
 *      Converts the integer representing the mode style into a string.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static const char *
NameOfBarMode(
    RbcBarMode mode)
{
    switch (mode) {
    case MODE_INFRONT:
        return "infront";
    case MODE_OVERLAP:
        return "overlap";
    case MODE_STACKED:
        return "stacked";
    case MODE_ALIGNED:
        return "aligned";
    default:
        return "unknown mode value";
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * StringToMode --
 *
 *      Converts the mode string into its numeric representation.
 *
 *      Valid mode strings are:
 *
 *          "infront"   Draw a full bar at each point in the element.
 *
 *      "stacked"   Stack bar segments vertically. Each stack is defined
 *              by each ordinate at a particular abscissa. The height
 *              of each segment is represented by the sum the previous
 *              ordinates.
 *
 *      "aligned"   Align bar segments as smaller slices one next to
 *              the other.  Like "stacks", aligned segments are
 *              defined by each ordinate at a particular abscissa.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
StringToBarMode(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* Mode style string */
    char *widgRec,              /* Cubicle structure record */
    int offset)
{                               /* Offset of style in record */
    RbcBarMode     *modePtr = (RbcBarMode *) (widgRec + offset);
    unsigned int    length;
    char            c;

    c = string[0];
    length = strlen(string);
    if ((c == 'n') && (strncmp(string, "normal", length) == 0)) {
        *modePtr = MODE_INFRONT;
    } else if ((c == 'i') && (strncmp(string, "infront", length) == 0)) {
        *modePtr = MODE_INFRONT;
    } else if ((c == 's') && (strncmp(string, "stacked", length) == 0)) {
        *modePtr = MODE_STACKED;
    } else if ((c == 'a') && (strncmp(string, "aligned", length) == 0)) {
        *modePtr = MODE_ALIGNED;
    } else if ((c == 'o') && (strncmp(string, "overlap", length) == 0)) {
        *modePtr = MODE_OVERLAP;
    } else {
        Tcl_AppendResult(interp, "bad mode argument \"", string,
            "\": should be \"infront\", \"stacked\", \"overlap\", or \"aligned\"",
            (char *) NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * BarModeToString --
 *
 *      Returns the mode style string based upon the mode flags.
 *
 * Results:
 *      The mode style string is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static const char *
BarModeToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Row/column structure record */
    int offset,                 /* Offset of mode in Partition record */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Not used. */
    RbcBarMode      mode = *(RbcBarMode *) (widgRec + offset);

    return NameOfBarMode(mode);
}

/*
 *----------------------------------------------------------------------
 *
 * ClearPalette --
 *
 *      Zero out the style's number of rectangles and errorbars.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
ClearPalette(
    RbcChain * palette)
{
    register BarPenStyle *stylePtr;
    RbcChainLink   *linkPtr;

    for (linkPtr = RbcChainFirstLink(palette); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        stylePtr = RbcChainGetValue(linkPtr);
        stylePtr->xErrorBarCnt = stylePtr->yErrorBarCnt = stylePtr->nRects = 0;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigurePen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ConfigurePen(
    RbcGraph * graphPtr,
    RbcPen * penPtr)
{
    BarPen         *bpPtr = (BarPen *) penPtr;
    XGCValues       gcValues;
    unsigned long   gcMask;
    int             fillStyle;
    GC              newGC;
    long            defColor;

    RbcResetTextStyle(graphPtr->tkwin, &(bpPtr->valueStyle));
    gcMask = GCForeground;
    if (bpPtr->fgColor != NULL) {
        defColor = bpPtr->fgColor->pixel;
        gcValues.foreground = bpPtr->fgColor->pixel;
    } else if (bpPtr->border != NULL) {
        defColor = Tk_3DBorderColor(bpPtr->border)->pixel;
        gcValues.foreground = Tk_3DBorderColor(bpPtr->border)->pixel;
    } else {
        defColor = BlackPixel(graphPtr->display,
            Tk_ScreenNumber(graphPtr->tkwin));
    }
    if ((bpPtr->fgColor != NULL) && (bpPtr->border != NULL)) {
        gcMask |= GCBackground;
        gcValues.background = Tk_3DBorderColor(bpPtr->border)->pixel;
        fillStyle = FillOpaqueStippled;
    } else {
        fillStyle = FillStippled;
    }
    if (bpPtr->stipple != None) {
        gcValues.stipple = bpPtr->stipple;
        gcValues.fill_style = fillStyle;
        gcMask |= (GCStipple | GCFillStyle);
    }
    newGC = Tk_GetGC(graphPtr->tkwin, gcMask, &gcValues);
    if (bpPtr->gc != NULL) {
        Tk_FreeGC(graphPtr->display, bpPtr->gc);
    }
    bpPtr->gc = newGC;

    gcMask = GCForeground | GCLineWidth;
    if (bpPtr->errorBarColor == RBC_COLOR_DEFAULT) {
        gcValues.foreground = defColor;
    } else {
        gcValues.foreground = bpPtr->errorBarColor->pixel;
    }
    gcValues.line_width = RbcLineWidth(bpPtr->errorBarLineWidth);
    newGC = Tk_GetGC(graphPtr->tkwin, gcMask, &gcValues);
    if (bpPtr->errorBarGC != NULL) {
        Tk_FreeGC(graphPtr->display, bpPtr->errorBarGC);
    }
    bpPtr->errorBarGC = newGC;

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DestroyPen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DestroyPen(
    RbcGraph * graphPtr,
    RbcPen * penPtr)
{
    BarPen         *bpPtr = (BarPen *) penPtr;

    RbcFreeTextStyle(graphPtr->display, &(bpPtr->valueStyle));
    if (bpPtr->gc != NULL) {
        Tk_FreeGC(graphPtr->display, bpPtr->gc);
    }
    if (bpPtr->errorBarGC != NULL) {
        Tk_FreeGC(graphPtr->display, bpPtr->errorBarGC);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * InitPen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
InitPen(
    BarPen * penPtr)
{
    RbcInitTextStyle(&(penPtr->valueStyle));
    penPtr->specsPtr = barPenConfigSpecs;
    penPtr->configProc = ConfigurePen;
    penPtr->destroyProc = DestroyPen;
    penPtr->relief = TK_RELIEF_RAISED;
    penPtr->flags = RBC_NORMAL_PEN;
    penPtr->errorBarShow = RBC_SHOW_BOTH;
    penPtr->valueShow = RBC_SHOW_NONE;
    penPtr->borderWidth = 2;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcBarPen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcPen         *
RbcBarPen(
    const char *penName)
{
    BarPen         *penPtr;

    penPtr = RbcCalloc(1, sizeof(BarPen));
    assert(penPtr);
    InitPen(penPtr);
    penPtr->name = RbcStrdup(penName);
    if (strcmp(penName, "activeBar") == 0) {
        penPtr->flags = RBC_ACTIVE_PEN;
    }
    return (RbcPen *) penPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * CheckStacks --
 *
 *      Check that the data limits are not superseded by the heights
 *      of stacked bar segments.  The heights are calculated by
 *      RbcComputeStacks.
 *
 * Results:
 *      If the y-axis limits need to be adjusted for stacked segments,
 *      *minPtr* or *maxPtr* are updated.
 *
 * Side effects:
 *      Autoscaling of the y-axis is affected.
 *
 * ----------------------------------------------------------------------
 */
static void
CheckStacks(
    RbcGraph * graphPtr,
    RbcAxis2D * pairPtr,
    double *minPtr,             /* Current minimum for y-axis */
    double *maxPtr)
{                               /* Current maximum for y-axis */
    RbcFreqInfo    *infoPtr;
    register int    i;

    if ((graphPtr->mode != MODE_STACKED) || (graphPtr->nStacks == 0)) {
        return;
    }
    infoPtr = graphPtr->freqArr;
    for (i = 0; i < graphPtr->nStacks; i++) {
        if ((infoPtr->axes.x == pairPtr->x) && (infoPtr->axes.y == pairPtr->y)) {
            /*

             * Check if any of the y-values (because of stacking) are
             * greater than the current limits of the graph.
             */
            if (infoPtr->sum < 0.0) {
                if (*minPtr > infoPtr->sum) {
                    *minPtr = infoPtr->sum;
                }
            } else {
                if (*maxPtr < infoPtr->sum) {
                    *maxPtr = infoPtr->sum;
                }
            }
        }
        infoPtr++;
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureBar --
 *
 *      Sets up the appropriate configuration parameters in the GC.
 *      It is assumed the parameters have been previously set by
 *      a call to Tk_ConfigureWidget.
 *
 * Results:
 *      The return value is a standard Tcl result.  If TCL_ERROR is
 *      returned, then interp->result contains an error message.
 *
 * Side effects:
 *      Configuration information such as bar foreground/background
 *      color and stipple etc. get set in a new GC.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureBar(
    RbcGraph * graphPtr,
    register RbcElement * elemPtr)
{
    Bar            *barPtr = (Bar *) elemPtr;
    RbcChainLink   *linkPtr;

    if (ConfigurePen(graphPtr, (RbcPen *) & (barPtr->builtinPen)) != TCL_OK) {
        return TCL_ERROR;
    }
    /*
     * Point to the static normal pen if no external pens have
     * been selected.
     */
    if (barPtr->normalPenPtr == NULL) {
        barPtr->normalPenPtr = &(barPtr->builtinPen);
    }
    linkPtr = RbcChainFirstLink(barPtr->palette);
    if (linkPtr != NULL) {
        BarPenStyle    *stylePtr;

        stylePtr = RbcChainGetValue(linkPtr);
        stylePtr->penPtr = barPtr->normalPenPtr;
    }
    if (RbcConfigModified(barPtr->specsPtr, "-barwidth", "-*data",
            "-map*", "-label", "-hide", "-x", "-y", (char *) NULL)) {
        barPtr->flags |= RBC_MAP_ITEM;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * GetBarExtents --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
GetBarExtents(
    RbcElement * elemPtr,
    RbcExtents2D * extsPtr)
{
    RbcGraph       *graphPtr = elemPtr->graphPtr;
    Bar            *barPtr = (Bar *) elemPtr;
    double          middle, barWidth;
    int             nPoints;

    extsPtr->top = extsPtr->left = DBL_MAX;
    extsPtr->bottom = extsPtr->right = -DBL_MAX;

    nPoints = RbcNumberOfPoints(barPtr);
    if (nPoints < 1) {
        return;                 /* No data points */
    }
    barWidth = graphPtr->barWidth;
    if (barPtr->barWidth > 0.0) {
        barWidth = barPtr->barWidth;
    }
    middle = barWidth * 0.5;
    extsPtr->left = barPtr->x.min - middle;
    extsPtr->right = barPtr->x.max + middle;

    extsPtr->top = barPtr->y.min;
    extsPtr->bottom = barPtr->y.max;
    if (extsPtr->bottom < graphPtr->baseline) {
        extsPtr->bottom = graphPtr->baseline;
    }
    /*
     * Handle "stacked" bar elements specially.
     *
     * If element is stacked, the sum of its ordinates may be outside
     * the minimum/maximum limits of the element's data points.
     */
    if ((graphPtr->mode == MODE_STACKED) && (graphPtr->nStacks > 0)) {
        CheckStacks(graphPtr, &(elemPtr->axes), &(extsPtr->top),
            &(extsPtr->bottom));
    }
    /* Warning: You get what you deserve if the x-axis is logScale */
    if (elemPtr->axes.x->logScale) {
        extsPtr->left = RbcFindElemVectorMinimum(&(barPtr->x), DBL_MIN) +
            middle;
    }
    /* Fix y-min limits for barchart */
    if (elemPtr->axes.y->logScale) {
        if ((extsPtr->top <= 0.0) || (extsPtr->top > 1.0)) {
            extsPtr->top = 1.0;
        }
    } else {
        if (extsPtr->top > 0.0) {
            extsPtr->top = 0.0;
        }
    }
    /* Correct the extents for error bars if they exist. */
    if (elemPtr->xError.nValues > 0) {
        register int    i;
        double          x;

        /* Correct the data limits for error bars */
        nPoints = MIN(elemPtr->xError.nValues, nPoints);
        for (i = 0; i < nPoints; i++) {
            x = elemPtr->x.valueArr[i] + elemPtr->xError.valueArr[i];
            if (x > extsPtr->right) {
                extsPtr->right = x;
            }
            x = elemPtr->x.valueArr[i] - elemPtr->xError.valueArr[i];
            if (elemPtr->axes.x->logScale) {
                if (x < 0.0) {
                    x = -x;     /* Mirror negative values, instead
                                 * of ignoring them. */
                }
                if ((x > DBL_MIN) && (x < extsPtr->left)) {
                    extsPtr->left = x;
                }
            } else if (x < extsPtr->left) {
                extsPtr->left = x;
            }
        }
    } else {
        if ((elemPtr->xHigh.nValues > 0) &&
            (elemPtr->xHigh.max > extsPtr->right)) {
            extsPtr->right = elemPtr->xHigh.max;
        }
        if (elemPtr->xLow.nValues > 0) {
            double          left;

            if ((elemPtr->xLow.min <= 0.0) && (elemPtr->axes.x->logScale)) {
                left = RbcFindElemVectorMinimum(&elemPtr->xLow, DBL_MIN);
            } else {
                left = elemPtr->xLow.min;
            }
            if (left < extsPtr->left) {
                extsPtr->left = left;
            }
        }
    }
    if (elemPtr->yError.nValues > 0) {
        register int    i;
        double          y;

        nPoints = MIN(elemPtr->yError.nValues, nPoints);
        for (i = 0; i < nPoints; i++) {
            y = elemPtr->y.valueArr[i] + elemPtr->yError.valueArr[i];
            if (y > extsPtr->bottom) {
                extsPtr->bottom = y;
            }
            y = elemPtr->y.valueArr[i] - elemPtr->yError.valueArr[i];
            if (elemPtr->axes.y->logScale) {
                if (y < 0.0) {
                    y = -y;     /* Mirror negative values, instead
                                 * of ignoring them. */
                }
                if ((y > DBL_MIN) && (y < extsPtr->left)) {
                    extsPtr->top = y;
                }
            } else if (y < extsPtr->top) {
                extsPtr->top = y;
            }
        }
    } else {
        if ((elemPtr->yHigh.nValues > 0) &&
            (elemPtr->yHigh.max > extsPtr->bottom)) {
            extsPtr->bottom = elemPtr->yHigh.max;
        }
        if (elemPtr->yLow.nValues > 0) {
            double          top;

            if ((elemPtr->yLow.min <= 0.0) && (elemPtr->axes.y->logScale)) {
                top = RbcFindElemVectorMinimum(&elemPtr->yLow, DBL_MIN);
            } else {
                top = elemPtr->yLow.min;
            }
            if (top < extsPtr->top) {
                extsPtr->top = top;
            }
        }
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ClosestBar --
 *
 *      Find the bar segment closest to the window coordinates	point
 *      specified.
 *
 *      Note:  This does not return the height of the stacked segment
 *             (in graph coordinates) properly.
 *
 * Results:
 *      Returns 1 if the point is width any bar segment, otherwise 0.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static void
ClosestBar(
    RbcGraph * graphPtr,        /* Graph widget record */
    RbcElement * elemPtr,       /* Bar element */
    RbcClosestSearch * searchPtr)
{                               /* Info of closest point in element */
    Bar            *barPtr = (Bar *) elemPtr;
    RbcPoint2D     *pointPtr, *endPtr;
    RbcPoint2D      t, outline[5];
    XRectangle     *rectPtr;
    double          left, right, top, bottom;
    double          minDist, dist;
    int             imin;
    register int    i;

    minDist = searchPtr->dist;
    imin = 0;

    rectPtr = barPtr->rectangles;
    for (i = 0; i < barPtr->nRects; i++) {
        /* Point in rectangle */
        if (    searchPtr->x <= (int)(rectPtr->x + rectPtr->width -1)
            &&  searchPtr->x >= (int)(rectPtr->x)
            &&  searchPtr->y <= (int)(rectPtr->y + rectPtr->height -1)
            &&  searchPtr->y >= (int)(rectPtr->y)) {
            imin = barPtr->rectToData[i];
            minDist = 0.0;
            break;
        }
        left = rectPtr->x, top = rectPtr->y;
        right = (double) (rectPtr->x + rectPtr->width);
        bottom = (double) (rectPtr->y + rectPtr->height);
        outline[4].x = outline[3].x = outline[0].x = left;
        outline[4].y = outline[1].y = outline[0].y = top;
        outline[2].x = outline[1].x = right;
        outline[3].y = outline[2].y = bottom;

        for (pointPtr = outline, endPtr = outline + 4; pointPtr < endPtr;
            pointPtr++) {
            t = RbcGetProjection(searchPtr->x, searchPtr->y,
                pointPtr, pointPtr + 1);
            if (t.x > right) {
                t.x = right;
            } else if (t.x < left) {
                t.x = left;
            }
            if (t.y > bottom) {
                t.y = bottom;
            } else if (t.y < top) {
                t.y = top;
            }
            dist = hypot((t.x - searchPtr->x), (t.y - searchPtr->y));
            if (dist < minDist) {
                minDist = dist;
                imin = barPtr->rectToData[i];
            }
        }
        rectPtr++;
    }
    if (minDist < searchPtr->dist) {
        searchPtr->elemPtr = (RbcElement *) elemPtr;
        searchPtr->dist = minDist;
        searchPtr->index = imin;
        searchPtr->point.x = (double) barPtr->x.valueArr[imin];
        searchPtr->point.y = (double) barPtr->y.valueArr[imin];
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MergePens --
 *
 *      Reorders the both arrays of points and errorbars to merge pens.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The old arrays are freed and new ones allocated containing
 *      the reordered points and errorbars.
 *
 *----------------------------------------------------------------------
 */
static void
MergePens(
    Bar * barPtr,
    RbcPenStyle ** dataToStyle)
{
    BarPenStyle    *stylePtr;
    RbcChainLink   *linkPtr;

    if (RbcChainGetLength(barPtr->palette) < 2) {
        linkPtr = RbcChainFirstLink(barPtr->palette);
        stylePtr = RbcChainGetValue(linkPtr);
        stylePtr->nRects = barPtr->nRects;
        stylePtr->rectangles = barPtr->rectangles;
        stylePtr->symbolSize = barPtr->rectangles->width / 2;
        stylePtr->xErrorBarCnt = barPtr->xErrorBarCnt;
        stylePtr->xErrorBars = barPtr->xErrorBars;
        stylePtr->yErrorBarCnt = barPtr->yErrorBarCnt;
        stylePtr->yErrorBars = barPtr->yErrorBars;
        return;
    }
    /* We have more than one style. Group bar segments of like pen
     * styles together.  */

    if (barPtr->nRects > 0) {
        XRectangle     *rectangles;
        int            *rectToData;
        int             dataIndex;
        register XRectangle *rectPtr;
        register int   *indexPtr;
        register int    i;

        rectangles =
            (XRectangle *) ckalloc(barPtr->nRects * sizeof(XRectangle));
        rectToData = (int *) ckalloc(barPtr->nRects * sizeof(int));
        assert(rectangles && rectToData);

        rectPtr = rectangles, indexPtr = rectToData;
        for (linkPtr = RbcChainFirstLink(barPtr->palette); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            stylePtr->symbolSize = rectPtr->width / 2;
            stylePtr->rectangles = rectPtr;
            for (i = 0; i < barPtr->nRects; i++) {
                dataIndex = barPtr->rectToData[i];
                if (dataToStyle[dataIndex] == (RbcPenStyle *) stylePtr) {
                    *rectPtr++ = barPtr->rectangles[i];
                    *indexPtr++ = dataIndex;
                }
            }
            stylePtr->nRects = rectPtr - stylePtr->rectangles;
        }
        ckfree((char *) barPtr->rectangles);
        barPtr->rectangles = rectangles;
        ckfree((char *) barPtr->rectToData);
        barPtr->rectToData = rectToData;
    }
    if (barPtr->xErrorBarCnt > 0) {
        RbcSegment2D   *errorBars, *segPtr;
        int            *errorToData, *indexPtr;
        int             dataIndex;
        register int    i;

        errorBars =
            (RbcSegment2D *) ckalloc(barPtr->xErrorBarCnt *
            sizeof(RbcSegment2D));
        errorToData = (int *) ckalloc(barPtr->xErrorBarCnt * sizeof(int));
        assert(errorBars);
        segPtr = errorBars, indexPtr = errorToData;
        for (linkPtr = RbcChainFirstLink(barPtr->palette);
            linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            stylePtr->xErrorBars = segPtr;
            for (i = 0; i < barPtr->xErrorBarCnt; i++) {
                dataIndex = barPtr->xErrorToData[i];
                if (dataToStyle[dataIndex] == (RbcPenStyle *) stylePtr) {
                    *segPtr++ = barPtr->xErrorBars[i];
                    *indexPtr++ = dataIndex;
                }
            }
            stylePtr->xErrorBarCnt = segPtr - stylePtr->xErrorBars;
        }
        ckfree((char *) barPtr->xErrorBars);
        barPtr->xErrorBars = errorBars;
        ckfree((char *) barPtr->xErrorToData);
        barPtr->xErrorToData = errorToData;
    }
    if (barPtr->yErrorBarCnt > 0) {
        RbcSegment2D   *errorBars, *segPtr;
        int            *errorToData, *indexPtr;
        int             dataIndex;
        register int    i;

        errorBars =
            (RbcSegment2D *) ckalloc(barPtr->yErrorBarCnt *
            sizeof(RbcSegment2D));
        errorToData = (int *) ckalloc(barPtr->yErrorBarCnt * sizeof(int));
        assert(errorBars);
        segPtr = errorBars, indexPtr = errorToData;
        for (linkPtr = RbcChainFirstLink(barPtr->palette);
            linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            stylePtr->yErrorBars = segPtr;
            for (i = 0; i < barPtr->yErrorBarCnt; i++) {
                dataIndex = barPtr->yErrorToData[i];
                if (dataToStyle[dataIndex] == (RbcPenStyle *) stylePtr) {
                    *segPtr++ = barPtr->yErrorBars[i];
                    *indexPtr++ = dataIndex;
                }
            }
            stylePtr->yErrorBarCnt = segPtr - stylePtr->yErrorBars;
        }
        ckfree((char *) barPtr->yErrorBars);
        barPtr->yErrorBars = errorBars;
        ckfree((char *) barPtr->yErrorToData);
        barPtr->yErrorToData = errorToData;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MapActiveBars --
 *
 *      Creates an array of points of the active graph coordinates.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is freed and allocated for the active point array.
 *
 *----------------------------------------------------------------------
 */
static void
MapActiveBars(
    Bar * barPtr)
{
    if (barPtr->activeRects != NULL) {
        ckfree((char *) barPtr->activeRects);
        barPtr->activeRects = NULL;
    }
    if (barPtr->activeToData != NULL) {
        ckfree((char *) barPtr->activeToData);
        barPtr->activeToData = NULL;
    }
    barPtr->nActive = 0;

    if (barPtr->nActiveIndices > 0) {
        XRectangle     *activeRects;
        int            *activeToData;
        register int    i, n;
        register int    count;

        activeRects =
            (XRectangle *) ckalloc(sizeof(XRectangle) * barPtr->nActiveIndices);
        assert(activeRects);
        activeToData = (int *) ckalloc(sizeof(int) * barPtr->nActiveIndices);
        assert(activeToData);
        count = 0;
        for (i = 0; i < barPtr->nRects; i++) {
            for (n = 0; n < barPtr->nActiveIndices; n++) {
                if (barPtr->rectToData[i] == barPtr->activeIndices[n]) {
                    activeRects[count] = barPtr->rectangles[i];
                    activeToData[count] = i;
                    count++;
                }
            }
        }
        barPtr->nActive = count;
        barPtr->activeRects = activeRects;
        barPtr->activeToData = activeToData;
    }
    barPtr->flags &= ~RBC_ACTIVE_PENDING;
}

/*
 *----------------------------------------------------------------------
 *
 * ResetBar --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
ResetBar(
    Bar * barPtr)
{
    /* Release any storage associated with the display of the bar */
    ClearPalette(barPtr->palette);
    if (barPtr->activeRects != NULL) {
        ckfree((char *) barPtr->activeRects);
    }
    if (barPtr->activeToData != NULL) {
        ckfree((char *) barPtr->activeToData);
    }
    if (barPtr->xErrorBars != NULL) {
        ckfree((char *) barPtr->xErrorBars);
    }
    if (barPtr->xErrorToData != NULL) {
        ckfree((char *) barPtr->xErrorToData);
    }
    if (barPtr->yErrorBars != NULL) {
        ckfree((char *) barPtr->yErrorBars);
    }
    if (barPtr->yErrorToData != NULL) {
        ckfree((char *) barPtr->yErrorToData);
    }
    if (barPtr->rectangles != NULL) {
        ckfree((char *) barPtr->rectangles);
    }
    if (barPtr->rectToData != NULL) {
        ckfree((char *) barPtr->rectToData);
    }
    barPtr->activeToData = barPtr->xErrorToData = barPtr->yErrorToData =
        barPtr->rectToData = NULL;
    barPtr->activeRects = barPtr->rectangles = NULL;
    barPtr->xErrorBars = barPtr->yErrorBars = NULL;
    barPtr->nActive = barPtr->xErrorBarCnt = barPtr->yErrorBarCnt =
        barPtr->nRects = 0;
}

/*
 * ----------------------------------------------------------------------
 *
 * MapBar --
 *
 *      Calculates the actual window coordinates of the bar element.
 *      The window coordinates are saved in the bar element structure.
 *
 *      A bar can have multiple segments (more than one x,y pairs).
 *      In this case, the bar can be represented as either a set of
 *      non-contiguous bars or a single multi-segmented (stacked) bar.
 *
 *      The x-axis layout for a barchart may be presented in one of
 *      two ways.  If abscissas are used, the bars are placed at those
 *      coordinates.  Otherwise, the range will represent the number
 *      of values.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static void
MapBar(
    RbcGraph * graphPtr,
    RbcElement * elemPtr)
{
    Bar            *barPtr = (Bar *) elemPtr;
    FreqKey         key;
    RbcPenStyle   **dataToStyle;
    RbcPoint2D      c1, c2;     /* Two opposite corners of the rectangle
                                 * in graph coordinates. */
    double         *x, *y;
    double          barWidth, barOffset;
    double          baseline;
    double          dx, dy;
    int            *rectToData; /* Maps rectangles to data point indices */
    int             height;
    int             invertBar;
    int             nPoints, count;
    register XRectangle *rectPtr, *rectangles;
    register int    i;
    int             size;
    RbcChainLink   *linkPtr;
    BarPenStyle    *stylePtr;

    ResetBar(barPtr);
    nPoints = RbcNumberOfPoints(barPtr);
    if (nPoints < 1) {
        return;                 /* No data points */
    }
    barWidth = graphPtr->barWidth;
    if (barPtr->barWidth > 0.0) {
        barWidth = barPtr->barWidth;
    }
    baseline = (barPtr->axes.y->logScale) ? 1.0 : graphPtr->baseline;
    barOffset = barWidth * 0.5;

    /*
     * Create an array of rectangles representing the screen coordinates
     * of all the segments in the bar.
     */
    rectPtr = rectangles = (XRectangle *) ckalloc(nPoints * sizeof(XRectangle));
    assert(rectangles);
    rectToData = RbcCalloc(nPoints, sizeof(int));
    assert(rectToData);

    x = barPtr->x.valueArr, y = barPtr->y.valueArr;
    count = 0;
    for (i = 0; i < nPoints; i++) {
        if (((x[i] - barWidth) > barPtr->axes.x->axisRange.max) ||
            ((x[i] + barWidth) < barPtr->axes.x->axisRange.min)) {
            continue;           /* Abscissa is out of range of the x-axis */
        }
        c1.x = x[i] - barOffset;
        c1.y = y[i];
        c2.x = c1.x + barWidth;
        c2.y = baseline;

        /*
         * If the mode is "aligned" or "stacked" we need to adjust the
         * x or y coordinates of the two corners.
         */

        if ((graphPtr->nStacks > 0) && (graphPtr->mode != MODE_INFRONT)) {
            Tcl_HashEntry  *hPtr;

            key.value = x[i];
            key.axes = barPtr->axes;
            hPtr = Tcl_FindHashEntry(&(graphPtr->freqTable), (char *) &key);
            if (hPtr != NULL) {
                RbcFreqInfo    *infoPtr;
                double          slice, width;

                infoPtr = (RbcFreqInfo *) Tcl_GetHashValue(hPtr);
                switch (graphPtr->mode) {
                case MODE_STACKED:
                    c2.y = infoPtr->lastY;
                    c1.y += c2.y;
                    infoPtr->lastY = c1.y;
                    break;

                case MODE_ALIGNED:
                    infoPtr->count++;
                    slice = barWidth / (double) infoPtr->freq;
                    c1.x += slice * (infoPtr->freq - infoPtr->count);
                    c2.x = c1.x + slice;
                    break;

                case MODE_OVERLAP:
                    infoPtr->count++;
                    slice = barWidth / (double) (infoPtr->freq * 2);
                    width = slice * (infoPtr->freq + 1);
                    c1.x += slice * (infoPtr->freq - infoPtr->count);
                    c2.x = c1.x + width;
                    break;
                case MODE_INFRONT:
                    break;
                }
            }
        }
        invertBar = FALSE;
        if (c1.y < c2.y) {
            double          temp;

            /* Handle negative bar values by swapping ordinates */
            temp = c1.y, c1.y = c2.y, c2.y = temp;
            invertBar = TRUE;
        }
        /*
         * Get the two corners of the bar segment and compute the rectangle
         */
        c1 = RbcMap2D(graphPtr, c1.x, c1.y, &barPtr->axes);
        c2 = RbcMap2D(graphPtr, c2.x, c2.y, &barPtr->axes);

        /* Bound the bars vertically by the size of the graph window */
        if (c1.y < 0.0) {
            c1.y = 0.0;
        } else if (c1.y > (double) graphPtr->height) {
            c1.y = (double) graphPtr->height;
        }
        if (c2.y < 0.0) {
            c2.y = 0.0;
        } else if (c2.y > (double) graphPtr->height) {
            c2.y = (double) graphPtr->height;
        }
        dx = c1.x - c2.x;
        dy = c1.y - c2.y;
        height = (int) Round(FABS(dy));
        if (invertBar) {
            rectPtr->y = (short int) MIN(c1.y, c2.y);
        } else {
            rectPtr->y = (short int) (MAX(c1.y, c2.y)) - height;
        }
        rectPtr->x = (short int) MIN(c1.x, c2.x);
        rectPtr->width = (short int) Round(FABS(dx)) + 1;
        if (rectPtr->width < 1) {
            rectPtr->width = 1;
        }
        rectPtr->height = height + 1;
        if (rectPtr->height < 1) {
            rectPtr->height = 1;
        }
        rectToData[count] = i;  /* Save the data index corresponding to the
                                 * rectangle */
        rectPtr++;
        count++;
    }
    barPtr->nRects = count;
    barPtr->rectangles = rectangles;
    barPtr->rectToData = rectToData;
    if (barPtr->nActiveIndices > 0) {
        MapActiveBars(barPtr);
    }

    size = 20;
    if (count > 0) {
        size = rectangles->width;
    }
    /* Set the symbol size of all the pen styles. */
    for (linkPtr = RbcChainFirstLink(barPtr->palette); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        stylePtr = RbcChainGetValue(linkPtr);
        stylePtr->symbolSize = size;
        stylePtr->errorBarCapWidth = (stylePtr->penPtr->errorBarCapWidth > 0)
            ? stylePtr->penPtr->errorBarCapWidth : (int) (size * 0.6666666);
        stylePtr->errorBarCapWidth /= 2;
    }
    dataToStyle = RbcStyleMap((RbcElement *) barPtr);
    if (((barPtr->yHigh.nValues > 0) && (barPtr->yLow.nValues > 0)) ||
        ((barPtr->xHigh.nValues > 0) && (barPtr->xLow.nValues > 0)) ||
        (barPtr->xError.nValues > 0) || (barPtr->yError.nValues > 0)) {
        RbcMapErrorBars(graphPtr, (RbcElement *) barPtr, dataToStyle);
    }
    MergePens(barPtr, dataToStyle);
    ckfree((char *) dataToStyle);
}

/*
 * -----------------------------------------------------------------
 *
 * DrawSymbol --
 *
 *      Draw a symbol centered at the given x,y window coordinate
 *      based upon the element symbol type and size.
 *
 *      Most notable problem is the round-off errors generated when
 *      calculating the centered position of the symbol.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
static void
DrawSymbol(
    RbcGraph * graphPtr,
    Drawable drawable,          /* Pixmap or window to draw into */
    RbcElement * elemPtr,
    int x,
    int y,
    int size)
{
    BarPen         *penPtr = ((Bar *) elemPtr)->normalPenPtr;
    int             radius;

    if ((penPtr->border == NULL) && (penPtr->fgColor == NULL)) {
        return;
    }
    radius = (size / 2);
    size--;

    x -= radius;
    y -= radius;
    XSetTSOrigin(graphPtr->display, penPtr->gc, x, y);
    XFillRectangle(graphPtr->display, drawable, penPtr->gc, x, y, size, size);
    XSetTSOrigin(graphPtr->display, penPtr->gc, 0, 0);
}

/*
 * -----------------------------------------------------------------
 *
 * DrawBarSegments --
 *
 *      Draws each of the rectangular segments for the element.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
static void
DrawBarSegments(
    RbcGraph * graphPtr,
    Drawable drawable,          /* Pixmap or window to draw into */
    BarPen * penPtr,
    XRectangle * rectangles,
    int nRects)
{
    register XRectangle *rectPtr;

    if ((penPtr->border == NULL) && (penPtr->fgColor == NULL)) {
        return;
    }
    XFillRectangles(graphPtr->display, drawable, penPtr->gc, rectangles,
        nRects);
    if ((penPtr->border != NULL) && (penPtr->borderWidth > 0) &&
        (penPtr->relief != TK_RELIEF_FLAT)) {
        XRectangle     *endPtr;

        for (rectPtr = rectangles, endPtr = rectangles + nRects;
            rectPtr < endPtr; rectPtr++) {
            Tk_Draw3DRectangle(graphPtr->tkwin, drawable, penPtr->border,
                rectPtr->x, rectPtr->y, rectPtr->width, rectPtr->height,
                penPtr->borderWidth, penPtr->relief);
        }
    }
}

/*
 * -----------------------------------------------------------------
 *
 * DrawBarValues --
 *
 *      Draws the numeric value of the bar.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
static void
DrawBarValues(
    RbcGraph * graphPtr,
    Drawable drawable,
    Bar * barPtr,
    BarPen * penPtr,
    XRectangle * rectangles,
    int nRects,
    int *rectToData)
{
    XRectangle     *rectPtr, *endPtr;
    int             count;
    const char     *fmt;
    char            string[TCL_DOUBLE_SPACE * 2 + 2];
    double          x, y;
    RbcPoint2D      anchorPos;

    count = 0;
    fmt = penPtr->valueFormat;
    if (fmt == NULL) {
        fmt = "%g";
    }
    for (rectPtr = rectangles, endPtr = rectangles + nRects; rectPtr < endPtr;
        rectPtr++) {
        x = barPtr->x.valueArr[rectToData[count]];
        y = barPtr->y.valueArr[rectToData[count]];
        count++;
        if (penPtr->valueShow == RBC_SHOW_X) {
            sprintf(string, fmt, x);
        } else if (penPtr->valueShow == RBC_SHOW_Y) {
            sprintf(string, fmt, y);
        } else if (penPtr->valueShow == RBC_SHOW_BOTH) {
            sprintf(string, fmt, x);
            strcat(string, ",");
            sprintf(string + strlen(string), fmt, y);
        }
        if (graphPtr->inverted) {
            anchorPos.y = rectPtr->y + rectPtr->height * 0.5;
            anchorPos.x = rectPtr->x + rectPtr->width;
            if (y < graphPtr->baseline) {
                anchorPos.x -= rectPtr->width;
            }
        } else {
            anchorPos.x = rectPtr->x + rectPtr->width * 0.5;
            anchorPos.y = rectPtr->y;
            if (y < graphPtr->baseline) {
                anchorPos.y += rectPtr->height;
            }
        }
        RbcDrawText(graphPtr->tkwin, drawable, string, &(penPtr->valueStyle),
            (int) anchorPos.x, (int) anchorPos.y);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * DrawNormalBar --
 *
 *      Draws the rectangle representing the bar element.  If the
 *      relief option is set to "raised" or "sunken" and the bar
 *      borderwidth is set (borderwidth > 0), a 3D border is drawn
 *      around the bar.
 *
 *      Don't draw bars that aren't visible (i.e. within the limits
 *      of the axis).
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      X drawing commands are output.
 *
 * ----------------------------------------------------------------------
 */
static void
DrawNormalBar(
    RbcGraph * graphPtr,
    Drawable drawable,
    RbcElement * elemPtr)
{
    Bar            *barPtr = (Bar *) elemPtr;
    int             count;
    RbcChainLink   *linkPtr;
    register BarPenStyle *stylePtr;
    BarPen         *penPtr;

    count = 0;
    for (linkPtr = RbcChainFirstLink(barPtr->palette); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        stylePtr = RbcChainGetValue(linkPtr);
        penPtr = stylePtr->penPtr;
        if (stylePtr->nRects > 0) {
            DrawBarSegments(graphPtr, drawable, penPtr, stylePtr->rectangles,
                stylePtr->nRects);
        }
        if ((stylePtr->xErrorBarCnt > 0) && (penPtr->errorBarShow & RBC_SHOW_X)) {
            RbcDraw2DSegments(graphPtr->display, drawable, penPtr->errorBarGC,
                stylePtr->xErrorBars, stylePtr->xErrorBarCnt);
        }
        if ((stylePtr->yErrorBarCnt > 0) && (penPtr->errorBarShow & RBC_SHOW_Y)) {
            RbcDraw2DSegments(graphPtr->display, drawable, penPtr->errorBarGC,
                stylePtr->yErrorBars, stylePtr->yErrorBarCnt);
        }
        if (penPtr->valueShow != RBC_SHOW_NONE) {
            DrawBarValues(graphPtr, drawable, barPtr, penPtr,
                stylePtr->rectangles, stylePtr->nRects,
                barPtr->rectToData + count);
        }
        count += stylePtr->nRects;
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * DrawActiveBar --
 *
 *      Draws rectangles representing the active segments of the
 *      bar element.  If the -relief option is set (other than "flat")
 *      and the borderwidth is greater than 0, a 3D border is drawn
 *      around the each bar segment.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      X drawing commands are output.
 *
 * ----------------------------------------------------------------------
 */
static void
DrawActiveBar(
    RbcGraph * graphPtr,
    Drawable drawable,
    RbcElement * elemPtr)
{
    Bar            *barPtr = (Bar *) elemPtr;

    if (barPtr->activePenPtr != NULL) {
        BarPen         *penPtr = barPtr->activePenPtr;

        if (barPtr->nActiveIndices > 0) {
            if (barPtr->flags & RBC_ACTIVE_PENDING) {
                MapActiveBars(barPtr);
            }
            DrawBarSegments(graphPtr, drawable, penPtr, barPtr->activeRects,
                barPtr->nActive);
            if (penPtr->valueShow != RBC_SHOW_NONE) {
                DrawBarValues(graphPtr, drawable, barPtr, penPtr,
                    barPtr->activeRects, barPtr->nActive, barPtr->activeToData);
            }
        } else if (barPtr->nActiveIndices < 0) {
            DrawBarSegments(graphPtr, drawable, penPtr, barPtr->rectangles,
                barPtr->nRects);
            if (penPtr->valueShow != RBC_SHOW_NONE) {
                DrawBarValues(graphPtr, drawable, barPtr, penPtr,
                    barPtr->rectangles, barPtr->nRects, barPtr->rectToData);
            }
        }
    }
}

/*
 * -----------------------------------------------------------------
 *
 * SymbolToPostScript --
 *
 *      Draw a symbol centered at the given x,y window coordinate
 *      based upon the element symbol type and size.
 *
 *      Most notable problem is the round-off errors generated when
 *      calculating the centered position of the symbol.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
static void
SymbolToPostScript(
    RbcGraph * graphPtr,
    RbcPsToken * psToken,
    RbcElement * elemPtr,
    double x,
    double y,
    int size)
{
    Bar            *barPtr = (Bar *) elemPtr;
    BarPen         *bpPtr = barPtr->normalPenPtr;

    if ((bpPtr->border == NULL) && (bpPtr->fgColor == NULL)) {
        return;
    }
    /*
     * Build a PostScript procedure to draw the fill and outline of
     * the symbol after the path of the symbol shape has been formed
     */
    RbcAppendToPostScript(psToken, "\n",
        "/DrawSymbolProc {\n", "  gsave\n    ", (char *) NULL);
    if (bpPtr->stipple != None) {
        if (bpPtr->border != NULL) {
            RbcBackgroundToPostScript(psToken, Tk_3DBorderColor(bpPtr->border));
            RbcAppendToPostScript(psToken, "    Fill\n    ", (char *) NULL);
        }
        if (bpPtr->fgColor != NULL) {
            RbcForegroundToPostScript(psToken, bpPtr->fgColor);
        } else {
            RbcForegroundToPostScript(psToken, Tk_3DBorderColor(bpPtr->border));
        }
        RbcStippleToPostScript(psToken, graphPtr->display, bpPtr->stipple);
    } else if (bpPtr->fgColor != NULL) {
        RbcForegroundToPostScript(psToken, bpPtr->fgColor);
        RbcAppendToPostScript(psToken, "    fill\n", (char *) NULL);
    }
    RbcAppendToPostScript(psToken, "  grestore\n", (char *) NULL);
    RbcAppendToPostScript(psToken, "} def\n\n", (char *) NULL);
    RbcFormatToPostScript(psToken, "%g %g %d Sq\n", x, y, size);
}

/*
 *----------------------------------------------------------------------
 *
 * SegmentsToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
SegmentsToPostScript(
    RbcGraph * graphPtr,
    RbcPsToken * psToken,
    BarPen * penPtr,
    register XRectangle * rectPtr,
    int nRects)
{
    XRectangle     *endPtr;

    if ((penPtr->border == NULL) && (penPtr->fgColor == NULL)) {
        return;
    }
    for (endPtr = rectPtr + nRects; rectPtr < endPtr; rectPtr++) {
        if ((rectPtr->width < 1) || (rectPtr->height < 1)) {
            continue;
        }
        if (penPtr->stipple != None) {
            RbcRegionToPostScript(psToken,
                (double) rectPtr->x, (double) rectPtr->y,
                (int) rectPtr->width - 1, (int) rectPtr->height - 1);
            if (penPtr->border != NULL) {
                RbcBackgroundToPostScript(psToken,
                    Tk_3DBorderColor(penPtr->border));
                RbcAppendToPostScript(psToken, "Fill\n", (char *) NULL);
            }
            if (penPtr->fgColor != NULL) {
                RbcForegroundToPostScript(psToken, penPtr->fgColor);
            } else {
                RbcForegroundToPostScript(psToken,
                    Tk_3DBorderColor(penPtr->border));
            }
            RbcStippleToPostScript(psToken, graphPtr->display, penPtr->stipple);
        } else if (penPtr->fgColor != NULL) {
            RbcForegroundToPostScript(psToken, penPtr->fgColor);
            RbcRectangleToPostScript(psToken,
                (double) rectPtr->x, (double) rectPtr->y,
                (int) rectPtr->width - 1, (int) rectPtr->height - 1);
        }
        if ((penPtr->border != NULL) && (penPtr->borderWidth > 0) &&
            (penPtr->relief != TK_RELIEF_FLAT)) {
            RbcDraw3DRectangleToPostScript(psToken, penPtr->border,
                (double) rectPtr->x, (double) rectPtr->y,
                (int) rectPtr->width, (int) rectPtr->height,
                penPtr->borderWidth, penPtr->relief);
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * BarValuesToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
BarValuesToPostScript(
    RbcGraph * graphPtr,
    RbcPsToken * psToken,
    Bar * barPtr,
    BarPen * penPtr,
    XRectangle * rectangles,
    int nRects,
    int *rectToData)
{
    XRectangle     *rectPtr, *endPtr;
    int             count;
    const char     *fmt;
    char            string[TCL_DOUBLE_SPACE * 2 + 2];
    double          x, y;
    RbcPoint2D      anchorPos;

    count = 0;
    fmt = penPtr->valueFormat;
    if (fmt == NULL) {
        fmt = "%g";
    }
    for (rectPtr = rectangles, endPtr = rectangles + nRects; rectPtr < endPtr;
        rectPtr++) {
        x = barPtr->x.valueArr[rectToData[count]];
        y = barPtr->y.valueArr[rectToData[count]];
        count++;
        if (penPtr->valueShow == RBC_SHOW_X) {
            sprintf(string, fmt, x);
        } else if (penPtr->valueShow == RBC_SHOW_Y) {
            sprintf(string, fmt, y);
        } else if (penPtr->valueShow == RBC_SHOW_BOTH) {
            sprintf(string, fmt, x);
            strcat(string, ",");
            sprintf(string + strlen(string), fmt, y);
        }
        if (graphPtr->inverted) {
            anchorPos.y = rectPtr->y + rectPtr->height * 0.5;
            anchorPos.x = rectPtr->x + rectPtr->width;
            if (y < graphPtr->baseline) {
                anchorPos.x -= rectPtr->width;
            }
        } else {
            anchorPos.x = rectPtr->x + rectPtr->width * 0.5;
            anchorPos.y = rectPtr->y;
            if (y < graphPtr->baseline) {
                anchorPos.y += rectPtr->height;
            }
        }
        RbcTextToPostScript(psToken, string, &(penPtr->valueStyle),
            anchorPos.x, anchorPos.y);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ActiveBarToPostScript --
 *
 *      Similar to the NormalBarToPostScript procedure, generates
 *      PostScript commands to display the rectangles representing the
 *      active bar segments of the element.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      PostScript pen width, dashes, and color settings are changed.
 *
 * ----------------------------------------------------------------------
 */
static void
ActiveBarToPostScript(
    RbcGraph * graphPtr,
    RbcPsToken * psToken,
    RbcElement * elemPtr)
{
    Bar            *barPtr = (Bar *) elemPtr;

    if (barPtr->activePenPtr != NULL) {
        BarPen         *penPtr = barPtr->activePenPtr;

        if (barPtr->nActiveIndices > 0) {
            if (barPtr->flags & RBC_ACTIVE_PENDING) {
                MapActiveBars(barPtr);
            }
            SegmentsToPostScript(graphPtr, psToken, penPtr,
                barPtr->activeRects, barPtr->nActive);
            if (penPtr->valueShow != RBC_SHOW_NONE) {
                BarValuesToPostScript(graphPtr, psToken, barPtr, penPtr,
                    barPtr->activeRects, barPtr->nActive, barPtr->activeToData);
            }
        } else if (barPtr->nActiveIndices < 0) {
            SegmentsToPostScript(graphPtr, psToken, penPtr,
                barPtr->rectangles, barPtr->nRects);
            if (penPtr->valueShow != RBC_SHOW_NONE) {
                BarValuesToPostScript(graphPtr, psToken, barPtr, penPtr,
                    barPtr->rectangles, barPtr->nRects, barPtr->rectToData);
            }
        }
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * NormalBarToPostScript --
 *
 *      Generates PostScript commands to form the rectangles
 *      representing the segments of the bar element.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      PostScript pen width, dashes, and color settings are changed.
 *
 * ----------------------------------------------------------------------
 */
static void
NormalBarToPostScript(
    RbcGraph * graphPtr,
    RbcPsToken * psToken,
    RbcElement * elemPtr)
{
    Bar            *barPtr = (Bar *) elemPtr;
    RbcChainLink   *linkPtr;
    register BarPenStyle *stylePtr;
    int             count;
    BarPen         *penPtr;
    XColor         *colorPtr;

    count = 0;
    for (linkPtr = RbcChainFirstLink(barPtr->palette); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        stylePtr = RbcChainGetValue(linkPtr);
        penPtr = stylePtr->penPtr;
        if (stylePtr->nRects > 0) {
            SegmentsToPostScript(graphPtr, psToken, penPtr,
                stylePtr->rectangles, stylePtr->nRects);
        }
        colorPtr = penPtr->errorBarColor;
        if (colorPtr == RBC_COLOR_DEFAULT) {
            colorPtr = penPtr->fgColor;
        }
        if ((stylePtr->xErrorBarCnt > 0) && (penPtr->errorBarShow & RBC_SHOW_X)) {
            RbcLineAttributesToPostScript(psToken, colorPtr,
                penPtr->errorBarLineWidth, NULL, CapButt, JoinMiter);
            Rbc2DSegmentsToPostScript(psToken, stylePtr->xErrorBars,
                stylePtr->xErrorBarCnt);
        }
        if ((stylePtr->yErrorBarCnt > 0) && (penPtr->errorBarShow & RBC_SHOW_Y)) {
            RbcLineAttributesToPostScript(psToken, colorPtr,
                penPtr->errorBarLineWidth, NULL, CapButt, JoinMiter);
            Rbc2DSegmentsToPostScript(psToken, stylePtr->yErrorBars,
                stylePtr->yErrorBarCnt);
        }
        if (penPtr->valueShow != RBC_SHOW_NONE) {
            BarValuesToPostScript(graphPtr, psToken, barPtr, penPtr,
                stylePtr->rectangles, stylePtr->nRects,
                barPtr->rectToData + count);
        }
        count += stylePtr->nRects;
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * DestroyBar --
 *
 *      Release memory and resources allocated for the bar element.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Everything associated with the bar element is freed up.
 *
 * ----------------------------------------------------------------------
 */
static void
DestroyBar(
    RbcGraph * graphPtr,
    RbcElement * elemPtr)
{
    Bar            *barPtr = (Bar *) elemPtr;

    if (barPtr->normalPenPtr != &(barPtr->builtinPen)) {
        RbcFreePen(graphPtr, (RbcPen *) barPtr->normalPenPtr);
    }
    DestroyPen(graphPtr, (RbcPen *) & (barPtr->builtinPen));
    if (barPtr->activePenPtr != NULL) {
        RbcFreePen(graphPtr, (RbcPen *) barPtr->activePenPtr);
    }
    FreeElemVector(barPtr->x);
    FreeElemVector(barPtr->y);
    FreeElemVector(barPtr->w);
    FreeElemVector(barPtr->xHigh);
    FreeElemVector(barPtr->xLow);
    FreeElemVector(barPtr->xError);
    FreeElemVector(barPtr->yHigh);
    FreeElemVector(barPtr->yLow);
    FreeElemVector(barPtr->yError);

    ResetBar(barPtr);
    if (barPtr->activeIndices != NULL) {
        ckfree((char *) barPtr->activeIndices);
    }
    if (barPtr->palette != NULL) {
        RbcFreePalette(graphPtr, barPtr->palette);
        RbcChainDestroy(barPtr->palette);
    }
    if (barPtr->tags != NULL) {
        ckfree((char *) barPtr->tags);
    }
}

static RbcElementProcs barProcs = {
    ClosestBar,
    ConfigureBar,
    DestroyBar,
    DrawActiveBar,
    DrawNormalBar,
    DrawSymbol,
    GetBarExtents,
    ActiveBarToPostScript,
    NormalBarToPostScript,
    SymbolToPostScript,
    MapBar,
};

/*
 * ----------------------------------------------------------------------
 *
 * RbcBarElement --
 *
 *      Allocate memory and initialize methods for the new bar element.
 *
 * Results:
 *      The pointer to the newly allocated element structure is returned.
 *
 * Side effects:
 *      Memory is allocated for the bar element structure.
 *
 * ----------------------------------------------------------------------
 */
RbcElement     *
RbcBarElement(
    RbcGraph * graphPtr,
    const char *name,
    Tk_Uid type)
{
    register Bar   *barPtr;

    barPtr = RbcCalloc(1, sizeof(Bar));
    assert(barPtr);
    barPtr->normalPenPtr = &(barPtr->builtinPen);
    barPtr->procsPtr = &barProcs;
    barPtr->specsPtr = barElemConfigSpecs;
    barPtr->labelRelief = TK_RELIEF_FLAT;
    barPtr->classUid = type;
    /* By default, an element's name and label are the same. */
    barPtr->label = RbcStrdup(name);
    barPtr->name = RbcStrdup(name);

    barPtr->graphPtr = graphPtr;
    barPtr->hidden = FALSE;

    InitPen(barPtr->normalPenPtr);
    barPtr->palette = RbcChainCreate();
    return (RbcElement *) barPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcInitFreqTable --
 *
 *      Generate a table of abscissa frequencies.  Duplicate
 *      x-coordinates (depending upon the bar drawing mode) indicate
 *      that something special should be done with each bar segment
 *      mapped to the same abscissa (i.e. it should be stacked,
 *      aligned, or overlay-ed with other segments)
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is allocated for the bar element structure.
 *
 * ----------------------------------------------------------------------
 */
void
RbcInitFreqTable(
    RbcGraph * graphPtr)
{
    register RbcElement *elemPtr;
    RbcChainLink   *linkPtr;
    Tcl_HashEntry  *hPtr;
    Tcl_HashSearch  cursor;
    Bar            *barPtr;
    int             isNew, count;
    int             nStacks, nSegs;
    int             nPoints;
    FreqKey         key;
    Tcl_HashTable   freqTable;
    register int    i;
    double         *xArr;
    /*
     * Free resources associated with a previous frequency table. This
     * includes the array of frequency information and the table itself
     */
    if (graphPtr->freqArr != NULL) {
        ckfree((char *) graphPtr->freqArr);
        graphPtr->freqArr = NULL;
    }
    if (graphPtr->nStacks > 0) {
        Tcl_DeleteHashTable(&(graphPtr->freqTable));
        graphPtr->nStacks = 0;
    }
    if (graphPtr->mode == MODE_INFRONT) {
        return;                 /* No frequency table is needed for
                                 * "infront" mode */
    }
    Tcl_InitHashTable(&(graphPtr->freqTable), sizeof(FreqKey) / sizeof(int));

    /*
     * Initialize a hash table and fill it with unique abscissas.
     * Keep track of the frequency of each x-coordinate and how many
     * abscissas have duplicate mappings.
     */
    Tcl_InitHashTable(&freqTable, sizeof(FreqKey) / sizeof(int));
    nSegs = nStacks = 0;
    for (linkPtr = RbcChainFirstLink(graphPtr->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if ((elemPtr->hidden) || (elemPtr->classUid != rbcBarElementUid)) {
            continue;
        }
        nSegs++;
        barPtr = (Bar *) elemPtr;
        xArr = barPtr->x.valueArr;
        nPoints = RbcNumberOfPoints(barPtr);
        for (i = 0; i < nPoints; i++) {
            key.value = xArr[i];
            key.axes = barPtr->axes;
            hPtr = Tcl_CreateHashEntry(&freqTable, (char *) &key, &isNew);
            assert(hPtr != NULL);
            if (isNew) {
                count = 1;
            } else {
                count = (int) Tcl_GetHashValue(hPtr);
                if (count == 1) {
                    nStacks++;
                }
                count++;
            }
            Tcl_SetHashValue(hPtr, (ClientData) count);
        }
    }
    if (nSegs == 0) {
        return;                 /* No bar elements to be displayed */
    }
    if (nStacks > 0) {
        RbcFreqInfo    *infoPtr;
        FreqKey        *keyPtr;
        Tcl_HashEntry  *h2Ptr;

        graphPtr->freqArr = RbcCalloc(nStacks, sizeof(RbcFreqInfo));
        assert(graphPtr->freqArr);
        infoPtr = graphPtr->freqArr;
        for (hPtr = Tcl_FirstHashEntry(&freqTable, &cursor); hPtr != NULL;
            hPtr = Tcl_NextHashEntry(&cursor)) {
            count = (int) Tcl_GetHashValue(hPtr);
            keyPtr = (FreqKey *) Tcl_GetHashKey(&freqTable, hPtr);
            if (count > 1) {
                h2Ptr = Tcl_CreateHashEntry(&(graphPtr->freqTable),
                    (char *) keyPtr, &isNew);
                count = (int) Tcl_GetHashValue(hPtr);
                infoPtr->freq = count;
                infoPtr->axes = keyPtr->axes;
                Tcl_SetHashValue(h2Ptr, infoPtr);
                infoPtr++;
            }
        }
    }
    Tcl_DeleteHashTable(&freqTable);
    graphPtr->nStacks = nStacks;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcComputeStacks --
 *
 *      Determine the height of each stack of bar segments.  A stack
 *      is created by designating two or more points with the same
 *      abscissa.  Each ordinate defines the height of a segment in
 *      the stack.  This procedure simply looks at all the data points
 *      summing the heights of each stacked segment. The sum is saved
 *      in the frequency information table.  This value will be used
 *      to calculate the y-axis limits (data limits aren't sufficient).
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The heights of each stack is computed. CheckStacks will
 *      use this information to adjust the y-axis limits if necessary.
 *
 * ----------------------------------------------------------------------
 */
void
RbcComputeStacks(
    RbcGraph * graphPtr)
{
    RbcElement     *elemPtr;
    Bar            *barPtr;
    FreqKey         key;
    RbcChainLink   *linkPtr;
    Tcl_HashEntry  *hPtr;
    int             nPoints;
    register int    i;
    register RbcFreqInfo *infoPtr;
    double         *xArr, *yArr;

    if ((graphPtr->mode != MODE_STACKED) || (graphPtr->nStacks == 0)) {
        return;
    }
    /* Reset the sums for all duplicate values to zero. */

    infoPtr = graphPtr->freqArr;
    for (i = 0; i < graphPtr->nStacks; i++) {
        infoPtr->sum = 0.0;
        infoPtr++;
    }

    /* Look at each bar point, adding the ordinates of duplicate abscissas */

    for (linkPtr = RbcChainFirstLink(graphPtr->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if ((elemPtr->hidden) || (elemPtr->classUid != rbcBarElementUid)) {
            continue;
        }
        barPtr = (Bar *) elemPtr;
        xArr = barPtr->x.valueArr;
        yArr = barPtr->y.valueArr;
        nPoints = RbcNumberOfPoints(barPtr);
        for (i = 0; i < nPoints; i++) {
            key.value = xArr[i];
            key.axes = barPtr->axes;
            hPtr = Tcl_FindHashEntry(&(graphPtr->freqTable), (char *) &key);
            if (hPtr == NULL) {
                continue;
            }
            infoPtr = (RbcFreqInfo *) Tcl_GetHashValue(hPtr);
            infoPtr->sum += yArr[i];
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcResetStacks --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcResetStacks(
    RbcGraph * graphPtr)
{
    register RbcFreqInfo *infoPtr, *endPtr;

    for (infoPtr = graphPtr->freqArr,
        endPtr = graphPtr->freqArr + graphPtr->nStacks;
        infoPtr < endPtr; infoPtr++) {
        infoPtr->lastY = 0.0;
        infoPtr->count = 0;
    }
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted generic/rbc/rbcGrElem.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
/*
 * rbcGrElem.c --
 *
 *      This module implements generic elements for the rbc graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "rbcInt.h"

static Tk_OptionParseProc StringToData;
static Tk_OptionPrintProc DataToString;
static Tk_OptionParseProc StringToDataPairs;
static Tk_OptionPrintProc DataPairsToString;
static Tk_OptionParseProc StringToAlong;
static Tk_OptionPrintProc AlongToString;
static Tk_CustomOption alongOption = {
    StringToAlong, AlongToString, (ClientData) 0
};

Tk_CustomOption rbcDataOption = {
    StringToData, DataToString, (ClientData) 0
};

Tk_CustomOption rbcDataPairsOption = {
    StringToDataPairs, DataPairsToString, (ClientData) 0
};

extern Tk_CustomOption rbcDistanceOption;

static int      counter;

static RbcVectorChangedProc VectorChangedProc;

static int      GetPenStyle(
    RbcGraph * graphPtr,
    const char *string,
    Tk_Uid type,
    RbcPenStyle * stylePtr);
static void     SyncElemVector(
    RbcElemVector * vPtr);
static void     FindRange(
    RbcElemVector * vPtr);
static void     FreeDataVector(
    RbcElemVector * vPtr);
static int      EvalExprList(
    Tcl_Interp * interp,
    const char *list,
    int *nElemPtr,
    double **arrayPtr);
static int      GetIndex(
    Tcl_Interp * interp,
    RbcElement * elemPtr,
    const char *string,
    int *indexPtr);
static int      NameToElement(
    RbcGraph * graphPtr,
    const char *name,
    RbcElement ** elemPtrPtr);
static int      CreateElement(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv,
    Tk_Uid classUid);
static void     DestroyElement(
    RbcGraph * graphPtr,
    RbcElement * elemPtr);
static int      RebuildDisplayList(
    RbcGraph * graphPtr,
    const char *newList);

static int      ActivateOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      BindOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      CreateOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv,
    Tk_Uid type);
static int      ConfigureOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char *argv[]);
static int      DeactivateOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      DeleteOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      ExistsOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      GetOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char *argv[]);
static int      NamesOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      ShowOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      TypeOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);

/*
 * ----------------------------------------------------------------------
 * Custom option parse and print procedures
 * ----------------------------------------------------------------------
 */

/*
 *----------------------------------------------------------------------
 *
 * GetPenStyle --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetPenStyle(
    RbcGraph * graphPtr,
    const char *string,
    Tk_Uid type,
    RbcPenStyle * stylePtr)
{
    RbcPen         *penPtr;
    Tcl_Interp     *interp = graphPtr->interp;
    const char    **elemArr;
    int             nElem;

    elemArr = NULL;
    if (Tcl_SplitList(interp, string, &nElem, &elemArr) != TCL_OK) {
        return TCL_ERROR;
    }
    if ((nElem != 1) && (nElem != 3)) {
        Tcl_AppendResult(interp, "bad style \"", string, "\": should be ",
            "\"penName\" or \"penName min max\"", (char *) NULL);
        if (elemArr != NULL) {
            ckfree((char *) elemArr);
        }
        return TCL_ERROR;
    }
    if (RbcGetPen(graphPtr, elemArr[0], type, &penPtr) != TCL_OK) {
        ckfree((char *) elemArr);
        return TCL_ERROR;
    }
    if (nElem == 3) {
        double          min, max;

        if ((Tcl_GetDouble(interp, elemArr[1], &min) != TCL_OK) ||
            (Tcl_GetDouble(interp, elemArr[2], &max) != TCL_OK)) {
            ckfree((char *) elemArr);
            return TCL_ERROR;
        }
        stylePtr->weight.min = min;
        stylePtr->weight.max = max;
        stylePtr->weight.range = (max > min) ? (max - min) : DBL_EPSILON;
    }
    stylePtr->penPtr = penPtr;
    ckfree((char *) elemArr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * SyncElemVector --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
SyncElemVector(
    RbcElemVector * vPtr)
{
    vPtr->nValues = vPtr->vecPtr->numValues;
    vPtr->valueArr = vPtr->vecPtr->valueArr;
    vPtr->min = RbcVecMin(vPtr->vecPtr);
    vPtr->max = RbcVecMax(vPtr->vecPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * FindRange --
 *
 *      Find the minimum, positive minimum, and maximum values in a
 *      given vector and store the results in the vector structure.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Minimum, positive minimum, and maximum values are stored in
 *      the vector.
 *
 *----------------------------------------------------------------------
 */
static void
FindRange(
    RbcElemVector * vPtr)
{
    register int    i;
    register double *x;
    register double min, max;

    if ((vPtr->nValues < 1) || (vPtr->valueArr == NULL)) {
        return;                 /* This shouldn't ever happen. */
    }
    x = vPtr->valueArr;

    min = DBL_MAX, max = -DBL_MAX;
    for (i = 0; i < vPtr->nValues; i++) {
        if (!TclIsInfinite(x[i])) {
            min = max = x[i];
            break;
        }
    }
    /*  Initialize values to track the vector range */
    for ( /* empty */ ; i < vPtr->nValues; i++) {
        if (!TclIsInfinite(x[i])) {
            if (x[i] < min) {
                min = x[i];
            } else if (x[i] > max) {
                max = x[i];
            }
        }
    }
    vPtr->min = min, vPtr->max = max;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcFindElemVectorMinimum --
 *
 *      Find the minimum, positive minimum, and maximum values in a
 *      given vector and store the results in the vector structure.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Minimum, positive minimum, and maximum values are stored in
 *      the vector.
 *
 *----------------------------------------------------------------------
 */
double
RbcFindElemVectorMinimum(
    RbcElemVector * vPtr,
    double minLimit)
{
    register int    i;
    register double *arr;
    register double min, x;

    min = DBL_MAX;
    arr = vPtr->valueArr;
    for (i = 0; i < vPtr->nValues; i++) {
        x = arr[i];
        if (x < 0.0) {
            /* What do you do about negative values when using log
             * scale values seems like a grey area.  Mirror. */
            x = -x;
        }
        if ((x > minLimit) && (min > x)) {
            min = x;
        }
    }
    if (min == DBL_MAX) {
        min = minLimit;
    }
    return min;
}

/*
 *----------------------------------------------------------------------
 *
 * FreeDataVector --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
FreeDataVector(
    RbcElemVector * vPtr)
{
    if (vPtr->clientId != NULL) {
        Rbc_FreeVectorId(vPtr->clientId);        /* Free the old vector */
        vPtr->clientId = NULL;
    } else if (vPtr->valueArr != NULL) {
        ckfree((char *) vPtr->valueArr);
    }
    vPtr->valueArr = NULL;
    vPtr->nValues = 0;
}

/*
 *----------------------------------------------------------------------
 *
 * VectorChangedProc --
 *
 *      TODO: Description
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Graph is redrawn.
 *
 *----------------------------------------------------------------------
 */
static void
VectorChangedProc(
    Tcl_Interp * interp,
    ClientData clientData,
    RbcVectorNotify notify)
{
    RbcElemVector  *vPtr = clientData;
    RbcElement     *elemPtr = vPtr->elemPtr;
    RbcGraph       *graphPtr = elemPtr->graphPtr;

    switch (notify) {
    case RBC_VECTOR_NOTIFY_DESTROY:
        vPtr->clientId = NULL;
        vPtr->valueArr = NULL;
        vPtr->nValues = 0;
        break;

    case RBC_VECTOR_NOTIFY_UPDATE:
    default:
        Rbc_GetVectorById(interp, vPtr->clientId, &vPtr->vecPtr);
        SyncElemVector(vPtr);
        break;
    }
    graphPtr->flags |= RBC_RESET_AXES;
    elemPtr->flags |= RBC_MAP_ITEM;
    if (!elemPtr->hidden) {
        graphPtr->flags |= RBC_REDRAW_BACKING_STORE;
        RbcEventuallyRedrawGraph(graphPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * EvalExprList --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
EvalExprList(
    Tcl_Interp * interp,
    const char *list,
    int *nElemPtr,
    double **arrayPtr)
{
    int             nElem;
    const char    **elemArr;
    double         *array;
    int             result;

    result = TCL_ERROR;
    elemArr = NULL;
    if (Tcl_SplitList(interp, list, &nElem, &elemArr) != TCL_OK) {
        return TCL_ERROR;
    }
    array = NULL;
    if (nElem > 0) {
        register double *valuePtr;
        register int    i;

        counter++;
        array = (double *) ckalloc(sizeof(double) * nElem);
        if (array == NULL) {
            Tcl_AppendResult(interp, "can't allocate new vector",
                (char *) NULL);
            goto badList;
        }
        valuePtr = array;
        for (i = 0; i < nElem; i++) {
            if (Tcl_ExprDouble(interp, elemArr[i], valuePtr) != TCL_OK) {
                goto badList;
            }
            valuePtr++;
        }
    }
    result = TCL_OK;

  badList:
    ckfree((char *) elemArr);
    *arrayPtr = array;
    *nElemPtr = nElem;
    if (result != TCL_OK) {
        ckfree((char *) array);
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToData --
 *
 *      Given a Tcl list of numeric expression representing the element
 *      values, convert into an array of double precision values. In
 *      addition, the minimum and maximum values are saved.  Since
 *      elastic values are allow (values which translate to the
 *      min/max of the graph), we must try to get the non-elastic
 *      minimum and maximum.
 *
 * Results:
 *      The return value is a standard Tcl result.  The vector is passed
 *      back via the vPtr.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToData(
    ClientData clientData,      /* Type of axis vector to fill */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* Tcl list of expressions */
    char *widgRec,              /* Element record */
    int offset)
{                               /* Offset of vector in Element record */
    RbcElement     *elemPtr = (RbcElement *) (widgRec);
    RbcElemVector  *vPtr = (RbcElemVector *) (widgRec + offset);

    FreeDataVector(vPtr);
    if (Rbc_VectorExists(interp, string)) {
        RbcVectorId     clientId;

        clientId = RbcAllocVectorId(interp, string);
        if (Rbc_GetVectorById(interp, clientId, &vPtr->vecPtr) != TCL_OK) {
            return TCL_ERROR;
        }
        Rbc_SetVectorChangedProc(clientId, VectorChangedProc, vPtr);
        vPtr->elemPtr = elemPtr;
        vPtr->clientId = clientId;
        SyncElemVector(vPtr);
        elemPtr->flags |= RBC_MAP_ITEM;
    } else {
        double         *newArr;
        int             nValues;

        if (EvalExprList(interp, string, &nValues, &newArr) != TCL_OK) {
            return TCL_ERROR;
        }
        if (nValues > 0) {
            vPtr->valueArr = newArr;
        }
        vPtr->nValues = nValues;
        FindRange(vPtr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DataToString --
 *
 *      Convert the vector of floating point values into a Tcl list.
 *
 * Results:
 *      The string representation of the vector is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
DataToString(
    ClientData clientData,      /* Type of axis vector to print */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Element record */
    int offset,                 /* Offset of vector in Element record */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Memory deallocation scheme to use */
    RbcElemVector  *vPtr = (RbcElemVector *) (widgRec + offset);
    RbcElement     *elemPtr = (RbcElement *) (widgRec);
    Tcl_DString     dString;
    char           *result;
    char            string[TCL_DOUBLE_SPACE + 1];
    double         *p, *endPtr;

    if (vPtr->clientId != NULL) {
        return Rbc_NameOfVectorId(vPtr->clientId);
    }
    if (vPtr->nValues == 0) {
        return "";
    }
    Tcl_DStringInit(&dString);
    endPtr = vPtr->valueArr + vPtr->nValues;
    for (p = vPtr->valueArr; p < endPtr; p++) {
        Tcl_PrintDouble(elemPtr->graphPtr->interp, *p, string);
        Tcl_DStringAppendElement(&dString, string);
    }
    result = Tcl_DStringValue(&dString);

    /*
     * If memory wasn't allocated for the dynamic string, do it here (it's
     * currently on the stack), so that Tcl can free it normally.
     */
    if (result == dString.staticSpace) {
        result = RbcStrdup(result);
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToDataPairs --
 *
 *      This procedure is like StringToData except that it interprets
 *      the list of numeric expressions as X Y coordinate pairs.  The
 *      minimum and maximum for both the X and Y vectors are
 *      determined.
 *
 * Results:
 *      The return value is a standard Tcl result.  The vectors are
 *      passed back via the widget record (elemPtr).
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToDataPairs(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* Tcl list of numeric expressions */
    char *widgRec,              /* Element record */
    int offset)
{                               /* Not used. */
    RbcElement     *elemPtr = (RbcElement *) widgRec;
    int             nElem;
    unsigned int    newSize;
    double         *newArr;

    if (EvalExprList(interp, string, &nElem, &newArr) != TCL_OK) {
        return TCL_ERROR;
    }
    if (nElem & 1) {
        Tcl_AppendResult(interp, "odd number of data points", (char *) NULL);
        ckfree((char *) newArr);
        return TCL_ERROR;
    }
    nElem /= 2;
    newSize = nElem * sizeof(double);

    FreeDataVector(&elemPtr->x);
    FreeDataVector(&elemPtr->y);

    elemPtr->x.valueArr = (double *) ckalloc(newSize);
    elemPtr->y.valueArr = (double *) ckalloc(newSize);
    assert(elemPtr->x.valueArr && elemPtr->y.valueArr);
    elemPtr->x.nValues = elemPtr->y.nValues = nElem;

    if (newSize > 0) {
        register double *dataPtr;
        register int    i;

        for (dataPtr = newArr, i = 0; i < nElem; i++) {
            elemPtr->x.valueArr[i] = *dataPtr++;
            elemPtr->y.valueArr[i] = *dataPtr++;
        }
        ckfree((char *) newArr);
        FindRange(&elemPtr->x);
        FindRange(&elemPtr->y);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DataPairsToString --
 *
 *      Convert pairs of floating point values in the X and Y arrays
 *      into a Tcl list.
 *
 * Results:
 *      The return value is a string (Tcl list).
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
DataPairsToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Element information record */
    int offset,                 /* Not used. */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Memory deallocation scheme to use */
    RbcElement     *elemPtr = (RbcElement *) widgRec;
    Tcl_Interp     *interp = elemPtr->graphPtr->interp;
    int             i;
    int             length;
    char           *result;
    char            string[TCL_DOUBLE_SPACE + 1];
    Tcl_DString     dString;

    length = RbcNumberOfPoints(elemPtr);
    if (length < 1) {
        return "";
    }
    Tcl_DStringInit(&dString);
    for (i = 0; i < length; i++) {
        Tcl_PrintDouble(interp, elemPtr->x.valueArr[i], string);
        Tcl_DStringAppendElement(&dString, string);
        Tcl_PrintDouble(interp, elemPtr->y.valueArr[i], string);
        Tcl_DStringAppendElement(&dString, string);
    }
    result = Tcl_DStringValue(&dString);

    /*
     * If memory wasn't allocated for the dynamic string, do it here
     * (it's currently on the stack), so that Tcl can free it
     * normally.
     */
    if (result == dString.staticSpace) {
        result = RbcStrdup(result);
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToAlong --
 *
 *      Given a Tcl list of numeric expression representing the element
 *      values, convert into an array of double precision values. In
 *      addition, the minimum and maximum values are saved.  Since
 *      elastic values are allow (values which translate to the
 *      min/max of the graph), we must try to get the non-elastic
 *      minimum and maximum.
 *
 * Results:
 *      The return value is a standard Tcl result.  The vector is passed
 *      back via the vPtr.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToAlong(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* String representation of value. */
    char *widgRec,              /* Widget record. */
    int offset)
{                               /* Offset of field in widget record. */
    int            *intPtr = (int *) (widgRec + offset);

    if ((string[0] == 'x') && (string[1] == '\0')) {
        *intPtr = RBC_SEARCH_X;
    } else if ((string[0] == 'y') && (string[1] == '\0')) {
        *intPtr = RBC_SEARCH_Y;
    } else if ((string[0] == 'b') && (strcmp(string, "both") == 0)) {
        *intPtr = RBC_SEARCH_BOTH;
    } else {
        Tcl_AppendResult(interp, "bad along value \"", string, "\"",
            (char *) NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * AlongToString --
 *
 *      Convert the vector of floating point values into a Tcl list.
 *
 * Results:
 *      The string representation of the vector is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
AlongToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Widget record */
    int offset,                 /* Offset of field in widget record */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Memory deallocation scheme to use */
    int             along = *(int *) (widgRec + offset);

    switch (along) {
    case RBC_SEARCH_X:
        return "x";
    case RBC_SEARCH_Y:
        return "y";
    case RBC_SEARCH_BOTH:
        return "both";
    default:
        return "unknown along value";
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcFreePalette --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcFreePalette(
    RbcGraph * graphPtr,
    RbcChain * palette)
{
    RbcChainLink   *linkPtr;

    /* Skip the first slot. It contains the built-in "normal" pen of
     * the element.  */
    linkPtr = RbcChainFirstLink(palette);
    if (linkPtr != NULL) {
        register RbcPenStyle *stylePtr;
        RbcChainLink   *nextPtr;

        for (linkPtr = RbcChainNextLink(linkPtr); linkPtr != NULL;
            linkPtr = nextPtr) {
            nextPtr = RbcChainNextLink(linkPtr);
            stylePtr = RbcChainGetValue(linkPtr);
            RbcFreePen(graphPtr, stylePtr->penPtr);
            RbcChainDeleteLink(palette, linkPtr);
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcStringToStyles --
 *
 *      Parse the list of style names.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcStringToStyles(
    ClientData clientData,      /* Not used. */
    Tcl_Interp * interp,        /* Interpreter to send results back to */
    Tk_Window tkwin,            /* Not used. */
    const char *string,         /* String representing style list */
    char *widgRec,              /* Element information record */
    int offset)
{                               /* Offset of symbol type field in record */
    RbcChain       *palette = *(RbcChain **) (widgRec + offset);
    RbcChainLink   *linkPtr;
    RbcElement     *elemPtr = (RbcElement *) (widgRec);
    RbcPenStyle    *stylePtr;
    const char    **elemArr;
    int             nStyles;
    register int    i;
    size_t          size = (size_t) clientData;

    elemArr = NULL;
    RbcFreePalette(elemPtr->graphPtr, palette);
    if ((string == NULL) || (*string == '\0')) {
        nStyles = 0;
    } else if (Tcl_SplitList(interp, string, &nStyles, &elemArr) != TCL_OK) {
        return TCL_ERROR;
    }
    /* Reserve the first entry for the "normal" pen. We'll set the
     * style later */
    linkPtr = RbcChainFirstLink(palette);
    if (linkPtr == NULL) {
        linkPtr = RbcChainAllocLink(size);
        RbcChainLinkBefore(palette, linkPtr, NULL);
    }
    stylePtr = RbcChainGetValue(linkPtr);
    stylePtr->penPtr = elemPtr->normalPenPtr;

    for (i = 0; i < nStyles; i++) {
        linkPtr = RbcChainAllocLink(size);
        stylePtr = RbcChainGetValue(linkPtr);
        stylePtr->weight.min = (double) i;
        stylePtr->weight.max = (double) i + 1.0;
        stylePtr->weight.range = 1.0;
        if (GetPenStyle(elemPtr->graphPtr, elemArr[i], elemPtr->classUid,
                (RbcPenStyle *) stylePtr) != TCL_OK) {
            ckfree((char *) elemArr);
            RbcFreePalette(elemPtr->graphPtr, palette);
            return TCL_ERROR;
        }
        RbcChainLinkBefore(palette, linkPtr, NULL);
    }
    if (elemArr != NULL) {
        ckfree((char *) elemArr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcStylesToString --
 *
 *      Convert the style information into a string.
 *
 * Results:
 *      The string representing the style information is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
const char     *
RbcStylesToString(
    ClientData clientData,      /* Not used. */
    Tk_Window tkwin,            /* Not used. */
    char *widgRec,              /* Element information record */
    int offset,                 /* Not used. */
    Tcl_FreeProc ** freeProcPtr)
{                               /* Not used. */
    RbcChain       *palette = *(RbcChain **) (widgRec + offset);
    Tcl_DString     dString;
    char           *result;
    RbcChainLink   *linkPtr;

    Tcl_DStringInit(&dString);
    linkPtr = RbcChainFirstLink(palette);
    if (linkPtr != NULL) {
        RbcElement     *elemPtr = (RbcElement *) (widgRec);
        char            string[TCL_DOUBLE_SPACE];
        Tcl_Interp     *interp;
        RbcPenStyle    *stylePtr;

        interp = elemPtr->graphPtr->interp;
        for (linkPtr = RbcChainNextLink(linkPtr); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            Tcl_DStringStartSublist(&dString);
            Tcl_DStringAppendElement(&dString, stylePtr->penPtr->name);
            Tcl_PrintDouble(interp, stylePtr->weight.min, string);
            Tcl_DStringAppendElement(&dString, string);
            Tcl_PrintDouble(interp, stylePtr->weight.max, string);
            Tcl_DStringAppendElement(&dString, string);
            Tcl_DStringEndSublist(&dString);
        }
    }
    result = RbcStrdup(Tcl_DStringValue(&dString));
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcStyleMap --
 *
 *      Creates an array of style indices and fills it based on the weight
 *      of each data point.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is freed and allocated for the index array.
 *
 *----------------------------------------------------------------------
 */
RbcPenStyle   **
RbcStyleMap(
    RbcElement * elemPtr)
{
    register int    i;
    int             nWeights;   /* Number of weights to be examined.
                                 * If there are more data points than
                                 * weights, they will default to the
                                 * normal pen. */

    RbcPenStyle   **dataToStyle;        /* Directory of styles.  Each array
                                         * element represents the style for
                                         * the data point at that index */
    RbcChainLink   *linkPtr;
    RbcPenStyle    *stylePtr;
    double         *w;          /* Weight vector */
    int             nPoints;

    nPoints = RbcNumberOfPoints(elemPtr);
    nWeights = MIN(elemPtr->w.nValues, nPoints);
    w = elemPtr->w.valueArr;
    linkPtr = RbcChainFirstLink(elemPtr->palette);
    stylePtr = RbcChainGetValue(linkPtr);

    /*
     * Create a style mapping array (data point index to style),
     * initialized to the default style.
     */
    dataToStyle = (RbcPenStyle **) ckalloc(nPoints * sizeof(RbcPenStyle *));
    assert(dataToStyle);
    for (i = 0; i < nPoints; i++) {
        dataToStyle[i] = stylePtr;
    }

    for (i = 0; i < nWeights; i++) {
        for (linkPtr = RbcChainLastLink(elemPtr->palette); linkPtr != NULL;
            linkPtr = RbcChainPrevLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);

            if (stylePtr->weight.range > 0.0) {
                double          norm;

                norm = (w[i] - stylePtr->weight.min) / stylePtr->weight.range;
                if (((norm - 1.0) <= DBL_EPSILON) &&
                    (((1.0 - norm) - 1.0) <= DBL_EPSILON)) {
                    dataToStyle[i] = stylePtr;
                    break;      /* Done: found range that matches. */
                }
            }
        }
    }
    return dataToStyle;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMapErrorBars --
 *
 *      Creates two arrays of points and pen indices, filled with
 *      the screen coordinates of the visible
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is freed and allocated for the index array.
 *
 *----------------------------------------------------------------------
 */
void
RbcMapErrorBars(
    RbcGraph * graphPtr,
    RbcElement * elemPtr,
    RbcPenStyle ** dataToStyle)
{
    int             n, nPoints;
    RbcExtents2D    exts;
    RbcPenStyle    *stylePtr;

    RbcGraphExtents(graphPtr, &exts);
    nPoints = RbcNumberOfPoints(elemPtr);
    if (elemPtr->xError.nValues > 0) {
        n = MIN(elemPtr->xError.nValues, nPoints);
    } else {
        n = MIN3(elemPtr->xHigh.nValues, elemPtr->xLow.nValues, nPoints);
    }
    if (n > 0) {
        RbcSegment2D   *errorBars;
        RbcSegment2D   *segPtr;
        double          high, low;
        double          x, y;
        int            *errorToData;
        int            *indexPtr;
        register int    i;

        segPtr = errorBars =
            (RbcSegment2D *) ckalloc(n * 3 * sizeof(RbcSegment2D));
        indexPtr = errorToData = (int *) ckalloc(n * 3 * sizeof(int));
        for (i = 0; i < n; i++) {
            x = elemPtr->x.valueArr[i];
            y = elemPtr->y.valueArr[i];
            stylePtr = dataToStyle[i];
            if ((!TclIsInfinite(x)) && (!TclIsInfinite(y))) {
                if (elemPtr->xError.nValues > 0) {
                    high = x + elemPtr->xError.valueArr[i];
                    low = x - elemPtr->xError.valueArr[i];
                } else {
                    high = elemPtr->xHigh.valueArr[i];
                    low = elemPtr->xLow.valueArr[i];
                }
                if ((!TclIsInfinite(high)) && (!TclIsInfinite(low))) {
                    RbcPoint2D      p, q;

                    p = RbcMap2D(graphPtr, high, y, &elemPtr->axes);
                    q = RbcMap2D(graphPtr, low, y, &elemPtr->axes);
                    segPtr->p = p;
                    segPtr->q = q;
                    if (RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
                        segPtr++;
                        *indexPtr++ = i;
                    }
                    /* Left cap */
                    segPtr->p.x = segPtr->q.x = p.x;
                    segPtr->p.y = p.y - stylePtr->errorBarCapWidth;
                    segPtr->q.y = p.y + stylePtr->errorBarCapWidth;
                    if (RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
                        segPtr++;
                        *indexPtr++ = i;
                    }
                    /* Right cap */
                    segPtr->p.x = segPtr->q.x = q.x;
                    segPtr->p.y = q.y - stylePtr->errorBarCapWidth;
                    segPtr->q.y = q.y + stylePtr->errorBarCapWidth;
                    if (RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
                        segPtr++;
                        *indexPtr++ = i;
                    }
                }
            }
        }
        elemPtr->xErrorBars = errorBars;
        elemPtr->xErrorBarCnt = segPtr - errorBars;
        elemPtr->xErrorToData = errorToData;
    }
    if (elemPtr->yError.nValues > 0) {
        n = MIN(elemPtr->yError.nValues, nPoints);
    } else {
        n = MIN3(elemPtr->yHigh.nValues, elemPtr->yLow.nValues, nPoints);
    }
    if (n > 0) {
        RbcSegment2D   *errorBars;
        RbcSegment2D   *segPtr;
        double          high, low;
        double          x, y;
        int            *errorToData;
        int            *indexPtr;
        register int    i;

        segPtr = errorBars =
            (RbcSegment2D *) ckalloc(n * 3 * sizeof(RbcSegment2D));
        indexPtr = errorToData = (int *) ckalloc(n * 3 * sizeof(int));
        for (i = 0; i < n; i++) {
            x = elemPtr->x.valueArr[i];
            y = elemPtr->y.valueArr[i];
            stylePtr = dataToStyle[i];
            if ((!TclIsInfinite(x)) && (!TclIsInfinite(y))) {
                if (elemPtr->yError.nValues > 0) {
                    high = y + elemPtr->yError.valueArr[i];
                    low = y - elemPtr->yError.valueArr[i];
                } else {
                    high = elemPtr->yHigh.valueArr[i];
                    low = elemPtr->yLow.valueArr[i];
                }
                if ((!TclIsInfinite(high)) && (!TclIsInfinite(low))) {
                    RbcPoint2D      p, q;

                    p = RbcMap2D(graphPtr, x, high, &elemPtr->axes);
                    q = RbcMap2D(graphPtr, x, low, &elemPtr->axes);
                    segPtr->p = p;
                    segPtr->q = q;
                    if (RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
                        segPtr++;
                        *indexPtr++ = i;
                    }
                    /* Top cap. */
                    segPtr->p.y = segPtr->q.y = p.y;
                    segPtr->p.x = p.x - stylePtr->errorBarCapWidth;
                    segPtr->q.x = p.x + stylePtr->errorBarCapWidth;
                    if (RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
                        segPtr++;
                        *indexPtr++ = i;
                    }
                    /* Bottom cap. */
                    segPtr->p.y = segPtr->q.y = q.y;
                    segPtr->p.x = q.x - stylePtr->errorBarCapWidth;
                    segPtr->q.x = q.x + stylePtr->errorBarCapWidth;
                    if (RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
                        segPtr++;
                        *indexPtr++ = i;
                    }
                }
            }
        }
        elemPtr->yErrorBars = errorBars;
        elemPtr->yErrorBarCnt = segPtr - errorBars;
        elemPtr->yErrorToData = errorToData;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GetIndex --
 *
 *      Given a string representing the index of a pair of x,y
 *      coordinates, return the numeric index.
 *
 * Results:
 *      A standard TCL result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetIndex(
    Tcl_Interp * interp,
    RbcElement * elemPtr,
    const char *string,
    int *indexPtr)
{
    long            ielem;
    int             last;

    last = RbcNumberOfPoints(elemPtr) - 1;
    if ((*string == 'e') && (strcmp("end", string) == 0)) {
        ielem = last;
    } else if (Tcl_ExprLong(interp, string, &ielem) != TCL_OK) {
        return TCL_ERROR;
    }
    *indexPtr = (int) ielem;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * NameToElement --
 *
 *      Find the element represented the given name,  returning
 *      a pointer to its data structure via elemPtrPtr.
 *
 * Results:
 *      A standard TCL result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
NameToElement(
    RbcGraph * graphPtr,
    const char *name,
    RbcElement ** elemPtrPtr)
{
    Tcl_HashEntry  *hPtr;

    if (name == NULL) {
        return TCL_ERROR;
    }
    hPtr = Tcl_FindHashEntry(&graphPtr->elements.table, name);
    if (hPtr == NULL) {
        Tcl_AppendResult(graphPtr->interp, "can't find element \"", name,
            "\" in \"", Tk_PathName(graphPtr->tkwin), "\"", (char *) NULL);
        return TCL_ERROR;
    }
    *elemPtrPtr = (RbcElement *) Tcl_GetHashValue(hPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DestroyElement --
 *
 *      Add a new element to the graph.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DestroyElement(
    RbcGraph * graphPtr,
    RbcElement * elemPtr)
{
    RbcChainLink   *linkPtr;

    RbcDeleteBindings(graphPtr->bindTable, elemPtr);
    RbcLegendRemoveElement(graphPtr->legend, elemPtr);

    Tk_FreeOptions(elemPtr->specsPtr, (char *) elemPtr, graphPtr->display, 0);
    /*
     * Call the element's own destructor to release the memory and
     * resources allocated for it.
     */
    (*elemPtr->procsPtr->destroyProc) (graphPtr, elemPtr);

    /* Remove it also from the element display list */
    for (linkPtr = RbcChainFirstLink(graphPtr->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        if (elemPtr == RbcChainGetValue(linkPtr)) {
            RbcChainDeleteLink(graphPtr->elements.displayList, linkPtr);
            if (!elemPtr->hidden) {
                graphPtr->flags |= RBC_RESET_WORLD;
                RbcEventuallyRedrawGraph(graphPtr);
            }
            break;
        }
    }
    /* Remove the element for the graph's hash table of elements */
    if (elemPtr->hashPtr != NULL) {
        Tcl_DeleteHashEntry(elemPtr->hashPtr);
    }
    if (elemPtr->name != NULL) {
        ckfree((char *) elemPtr->name);
    }
    ckfree((char *) elemPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * CreateElement --
 *
 *      Add a new element to the graph.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
CreateElement(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv,
    Tk_Uid classUid)
{
    RbcElement     *elemPtr;
    Tcl_HashEntry  *hPtr;
    int             isNew;

    if (argv[3][0] == '-') {
        Tcl_AppendResult(graphPtr->interp, "name of element \"", argv[3],
            "\" can't start with a '-'", (char *) NULL);
        return TCL_ERROR;
    }
    hPtr = Tcl_CreateHashEntry(&graphPtr->elements.table, argv[3], &isNew);
    if (!isNew) {
        Tcl_AppendResult(interp, "element \"", argv[3],
            "\" already exists in \"", argv[0], "\"", (char *) NULL);
        return TCL_ERROR;
    }
    if (classUid == rbcBarElementUid) {
        elemPtr = RbcBarElement(graphPtr, argv[3], classUid);
    } else {
        /* Stripcharts are line graphs with some options enabled. */
        elemPtr = RbcLineElement(graphPtr, argv[3], classUid);
    }
    elemPtr->hashPtr = hPtr;
    Tcl_SetHashValue(hPtr, elemPtr);

    if (RbcConfigureWidgetComponent(interp, graphPtr->tkwin, elemPtr->name,
            "Element", elemPtr->specsPtr, argc - 4, argv + 4,
            (char *) elemPtr, 0) != TCL_OK) {
        DestroyElement(graphPtr, elemPtr);
        return TCL_ERROR;
    }
    (*elemPtr->procsPtr->configProc) (graphPtr, elemPtr);
    RbcChainPrepend(graphPtr->elements.displayList, elemPtr);

    if (!elemPtr->hidden) {
        /* If the new element isn't hidden then redraw the graph.  */
        graphPtr->flags |= RBC_REDRAW_BACKING_STORE;
        RbcEventuallyRedrawGraph(graphPtr);
    }
    elemPtr->flags |= RBC_MAP_ITEM;
    graphPtr->flags |= RBC_RESET_AXES;
    Tcl_SetObjResult(interp, Tcl_NewStringObj(elemPtr->name, -1));
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RebuildDisplayList --
 *
 *      Given a Tcl list of element names, this procedure rebuilds the
 *      display list, ignoring invalid element names. This list describes
 *      not only only which elements to draw, but in what order.  This is
 *      only important for bar and pie charts.
 *
 * Results:
 *      The return value is a standard Tcl result.  Only if the Tcl list
 *      can not be split, a TCL_ERROR is returned and interp->result contains
 *      an error message.
 *
 * Side effects:
 *      The graph is eventually redrawn using the new display list.
 *
 *----------------------------------------------------------------------
 */
static int
RebuildDisplayList(
    RbcGraph * graphPtr,        /* Graph widget record */
    const char *newList)
{                               /* Tcl list of element names */
    int             nNames;     /* Number of names found in Tcl name list */
    const char    **nameArr;    /* Broken out array of element names */
    Tcl_HashSearch  cursor;
    register int    i;
    register Tcl_HashEntry *hPtr;
    RbcElement     *elemPtr;    /* Element information record */

    if (Tcl_SplitList(graphPtr->interp, newList, &nNames, &nameArr) != TCL_OK) {
        Tcl_AppendResult(graphPtr->interp, "can't split name list \"", newList,
            "\"", (char *) NULL);
        return TCL_ERROR;
    }
    /* Clear the display list and mark all elements as hidden.  */
    RbcChainReset(graphPtr->elements.displayList);
    for (hPtr = Tcl_FirstHashEntry(&graphPtr->elements.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        elemPtr = (RbcElement *) Tcl_GetHashValue(hPtr);
        elemPtr->hidden = TRUE;
    }

    /* Rebuild the display list, checking that each name it exists
     * (currently ignoring invalid element names).  */
    for (i = 0; i < nNames; i++) {
        if (NameToElement(graphPtr, nameArr[i], &elemPtr) == TCL_OK) {
            elemPtr->hidden = FALSE;
            RbcChainAppend(graphPtr->elements.displayList, elemPtr);
        }
    }
    ckfree((char *) nameArr);
    graphPtr->flags |= RBC_RESET_WORLD;
    RbcEventuallyRedrawGraph(graphPtr);
    Tcl_ResetResult(graphPtr->interp);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDestroyElements --
 *
 *      Removes all the graph's elements. This routine is called when
 *      the graph is destroyed.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory allocated for the graph's elements is freed.
 *
 *----------------------------------------------------------------------
 */
void
RbcDestroyElements(
    RbcGraph * graphPtr)
{
    Tcl_HashEntry  *hPtr;
    Tcl_HashSearch  cursor;
    RbcElement     *elemPtr;

    for (hPtr = Tcl_FirstHashEntry(&graphPtr->elements.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        elemPtr = (RbcElement *) Tcl_GetHashValue(hPtr);
        elemPtr->hashPtr = NULL;
        DestroyElement(graphPtr, elemPtr);
    }
    Tcl_DeleteHashTable(&graphPtr->elements.table);
    Tcl_DeleteHashTable(&graphPtr->elements.tagTable);
    RbcChainDestroy(graphPtr->elements.displayList);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMapElements --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcMapElements(
    RbcGraph * graphPtr)
{
    RbcElement     *elemPtr;
    RbcChainLink   *linkPtr;

    if (graphPtr->mode != MODE_INFRONT) {
        RbcResetStacks(graphPtr);
    }
    for (linkPtr = RbcChainFirstLink(graphPtr->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if (elemPtr->hidden) {
            continue;
        }
        if ((graphPtr->flags & RBC_MAP_ALL) || (elemPtr->flags & RBC_MAP_ITEM)) {
            (*elemPtr->procsPtr->mapProc) (graphPtr, elemPtr);
            elemPtr->flags &= ~RBC_MAP_ITEM;
        }
    }
}

/*
 * -----------------------------------------------------------------
 *
 * RbcDrawElements --
 *
 *      Calls the individual element drawing routines for each
 *      element.
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Elements are drawn into the drawable (pixmap) which will
 *      eventually be displayed in the graph window.
 *
 * -----------------------------------------------------------------
 */
void
RbcDrawElements(
    RbcGraph * graphPtr,
    Drawable drawable)
{                               /* Pixmap or window to draw into */
    RbcChainLink   *linkPtr;
    RbcElement     *elemPtr;

    for (linkPtr = RbcChainFirstLink(graphPtr->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if (!elemPtr->hidden) {
            (*elemPtr->procsPtr->drawNormalProc) (graphPtr, drawable, elemPtr);
        }
    }
}

/*
 * -----------------------------------------------------------------
 *
 * RbcDrawActiveElements --
 *
 *      Calls the individual element drawing routines to display
 *      the active colors for each element.
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Elements are drawn into the drawable (pixmap) which will
 *      eventually be displayed in the graph window.
 *
 * -----------------------------------------------------------------
 */
void
RbcDrawActiveElements(
    RbcGraph * graphPtr,
    Drawable drawable)
{                               /* Pixmap or window to draw into */
    RbcChainLink   *linkPtr;
    RbcElement     *elemPtr;

    for (linkPtr = RbcChainFirstLink(graphPtr->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if ((!elemPtr->hidden) && (elemPtr->flags & RBC_ELEM_ACTIVE)) {
            (*elemPtr->procsPtr->drawActiveProc) (graphPtr, drawable, elemPtr);
        }
    }
}

/*
 * -----------------------------------------------------------------
 *
 * RbcElementsToPostScript --
 *
 *      Generates PostScript output for each graph element in the
 *      element display list.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
void
RbcElementsToPostScript(
    RbcGraph * graphPtr,
    RbcPsToken * psToken)
{
    RbcChainLink   *linkPtr;
    RbcElement     *elemPtr;

    for (linkPtr = RbcChainFirstLink(graphPtr->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if (!elemPtr->hidden) {
            /* Comment the PostScript to indicate the start of the element */
            RbcFormatToPostScript(psToken, "\n%% Element \"%s\"\n\n",
                elemPtr->name);
            (*elemPtr->procsPtr->printNormalProc) (graphPtr, psToken, elemPtr);
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcActiveElementsToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcActiveElementsToPostScript(
    RbcGraph * graphPtr,
    RbcPsToken * psToken)
{
    RbcChainLink   *linkPtr;
    RbcElement     *elemPtr;

    for (linkPtr = RbcChainFirstLink(graphPtr->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if ((!elemPtr->hidden) && (elemPtr->flags & RBC_ELEM_ACTIVE)) {
            RbcFormatToPostScript(psToken, "\n%% Active Element \"%s\"\n\n",
                elemPtr->name);
            (*elemPtr->procsPtr->printActiveProc) (graphPtr, psToken, elemPtr);
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGraphUpdateNeeded --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcGraphUpdateNeeded(
    RbcGraph * graphPtr)
{
    RbcChainLink   *linkPtr;
    RbcElement     *elemPtr;

    for (linkPtr = RbcChainFirstLink(graphPtr->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if (elemPtr->hidden) {
            continue;
        }
        /* Check if the x or y vectors have notifications pending */
        if ((RbcVectorNotifyPending(elemPtr->x.clientId)) ||
            (RbcVectorNotifyPending(elemPtr->y.clientId))) {
            return 1;
        }
    }
    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * ActivateOp --
 *
 *      Marks data points of elements (given by their index) as active.
 *
 * Results:
 *      Returns TCL_OK if no errors occurred.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ActivateOp(
    RbcGraph * graphPtr,        /* Graph widget */
    Tcl_Interp * interp,        /* Interpreter to report errors to */
    int argc,                   /* Number of element names */
    const char **argv)
{                               /* List of element names */
    RbcElement     *elemPtr;
    register int    i;
    int            *activeArr;
    int             nActiveIndices;

    if (argc == 3) {
        register Tcl_HashEntry *hPtr;
        Tcl_HashSearch  cursor;

        /* List all the currently active elements */
        for (hPtr = Tcl_FirstHashEntry(&graphPtr->elements.table, &cursor);
            hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
            elemPtr = (RbcElement *) Tcl_GetHashValue(hPtr);
            if (elemPtr->flags & RBC_ELEM_ACTIVE) {
                Tcl_AppendElement(graphPtr->interp, elemPtr->name);
            }
        }
        return TCL_OK;
    }
    if (NameToElement(graphPtr, argv[3], &elemPtr) != TCL_OK) {
        return TCL_ERROR;       /* Can't find named element */
    }
    elemPtr->flags |= RBC_ELEM_ACTIVE | RBC_ACTIVE_PENDING;

    activeArr = NULL;
    nActiveIndices = -1;
    if (argc > 4) {
        register int   *activePtr;

        nActiveIndices = argc - 4;
        activePtr = activeArr = (int *) ckalloc(sizeof(int) * nActiveIndices);
        assert(activeArr);
        for (i = 4; i < argc; i++) {
            if (GetIndex(interp, elemPtr, argv[i], activePtr) != TCL_OK) {
                return TCL_ERROR;
            }
            activePtr++;
        }
    }
    if (elemPtr->activeIndices != NULL) {
        ckfree((char *) elemPtr->activeIndices);
    }
    elemPtr->nActiveIndices = nActiveIndices;
    elemPtr->activeIndices = activeArr;
    RbcEventuallyRedrawGraph(graphPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMakeElementTag --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
ClientData
RbcMakeElementTag(
    RbcGraph * graphPtr,
    const char *tagName)
{
    Tcl_HashEntry  *hPtr;
    int             isNew;

    hPtr = Tcl_CreateHashEntry(&graphPtr->elements.tagTable, tagName, &isNew);
    assert(hPtr);
    return Tcl_GetHashKey(&graphPtr->elements.tagTable, hPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * BindOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
BindOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    if (argc == 3) {
        Tcl_HashEntry  *hPtr;
        Tcl_HashSearch  cursor;
        char           *tagName;

        for (hPtr = Tcl_FirstHashEntry(&graphPtr->elements.tagTable, &cursor);
            hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
            tagName = Tcl_GetHashKey(&graphPtr->elements.tagTable, hPtr);
            Tcl_AppendElement(interp, tagName);
        }
        return TCL_OK;
    }
    return RbcConfigureBindings(interp, graphPtr->bindTable,
        RbcMakeElementTag(graphPtr, argv[3]), argc - 4, argv + 4);
}

/*
 *----------------------------------------------------------------------
 *
 * CreateOp --
 *
 *      Add a new element to the graph (using the default type of the
 *      graph).
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
CreateOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv,
    Tk_Uid type)
{
    return CreateElement(graphPtr, interp, argc, argv, type);
}

/*
 *----------------------------------------------------------------------
 *
 * CgetOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
CgetOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    char *argv[])
{
    RbcElement     *elemPtr;

    if (NameToElement(graphPtr, argv[3], &elemPtr) != TCL_OK) {
        return TCL_ERROR;       /* Can't find named element */
    }
    if (Tk_ConfigureValue(interp, graphPtr->tkwin, elemPtr->specsPtr,
            (char *) elemPtr, argv[4], 0) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

static Tk_ConfigSpec closestSpecs[] = {
    {TK_CONFIG_CUSTOM, "-halo", (char *) NULL, (char *) NULL,
            (char *) NULL, Tk_Offset(RbcClosestSearch, halo), 0,
        &rbcDistanceOption},
    {TK_CONFIG_BOOLEAN, "-interpolate", (char *) NULL, (char *) NULL,
        (char *) NULL, Tk_Offset(RbcClosestSearch, mode), 0},
    {TK_CONFIG_CUSTOM, "-along", (char *) NULL, (char *) NULL,
        (char *) NULL, Tk_Offset(RbcClosestSearch, along), 0, &alongOption},
    {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL,
        (char *) NULL, 0, 0}
};

/*
 *----------------------------------------------------------------------
 *
 * ClosestOp --
 *
 *      Find the element closest to the specified screen coordinates.
 *      Options:
 *      -halo		Consider points only with this maximum distance
 *      		from the picked coordinate.
 *      -interpolate	Find closest point along element traces, not just
 *      		data points.
 *      -along
 *
 * Results:
 *      A standard Tcl result. If an element could be found within
 *      the halo distance, the interpreter result is "1", otherwise
 *      "0".  If a closest element exists, the designated Tcl array
 *      variable will be set with the following information:
 *
 *      1) the element name,
 *      2) the index of the closest point,
 *      3) the distance (in screen coordinates) from the picked X-Y
 *         coordinate and the closest point,
 *      4) the X coordinate (graph coordinate) of the closest point,
 *      5) and the Y-coordinate.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ClosestOp(
    RbcGraph * graphPtr,        /* Graph widget */
    Tcl_Interp * interp,        /* Interpreter to report results to */
    int argc,                   /* Number of element names */
    const char **argv)
{                               /* List of element names */
    RbcElement     *elemPtr;
    RbcClosestSearch search;
    int             i, x, y;
    int             flags = TCL_LEAVE_ERR_MSG;

    if (graphPtr->flags & RBC_RESET_AXES) {
        RbcResetAxes(graphPtr);
    }
    if (Tk_GetPixels(interp, graphPtr->tkwin, argv[3], &x) != TCL_OK) {
        Tcl_AppendResult(interp, ": bad window x-coordinate", (char *) NULL);
        return TCL_ERROR;
    }
    if (Tk_GetPixels(interp, graphPtr->tkwin, argv[4], &y) != TCL_OK) {
        Tcl_AppendResult(interp, ": bad window y-coordinate", (char *) NULL);
        return TCL_ERROR;
    }
    if (graphPtr->inverted) {
        int             temp;

        temp = x, x = y, y = temp;
    }
    for (i = 6; i < argc; i += 2) {     /* Count switches-value pairs */
        if ((argv[i][0] != '-') ||
            ((argv[i][1] == '-') && (argv[i][2] == '\0'))) {
            break;
        }
    }
    if (i > argc) {
        i = argc;
    }

    search.mode = RBC_SEARCH_POINTS;
    search.halo = graphPtr->halo;
    search.index = -1;
    search.along = RBC_SEARCH_BOTH;
    search.x = x;
    search.y = y;

    if (Tk_ConfigureWidget(interp, graphPtr->tkwin, closestSpecs, i - 6,
            argv + 6, (char *) &search, TK_CONFIG_ARGV_ONLY) != TCL_OK) {
        return TCL_ERROR;       /* Error occurred processing an option. */
    }
    if ((i < argc) && (argv[i][0] == '-')) {
        i++;                    /* Skip "--" */
    }
    search.dist = (double) (search.halo + 1);

    if (i < argc) {
        for ( /* empty */ ; i < argc; i++) {
            if (NameToElement(graphPtr, argv[i], &elemPtr) != TCL_OK) {
                return TCL_ERROR;       /* Can't find named element */
            }
            if (elemPtr->hidden) {
                Tcl_AppendResult(interp, "element \"", argv[i], "\" is hidden",
                    (char *) NULL);
                return TCL_ERROR;       /* Element isn't visible */
            }
            /* Check if the X or Y vectors have notifications pending */
            if ((elemPtr->flags & RBC_MAP_ITEM) ||
                (RbcVectorNotifyPending(elemPtr->x.clientId)) ||
                (RbcVectorNotifyPending(elemPtr->y.clientId))) {
                continue;
            }
            (*elemPtr->procsPtr->closestProc) (graphPtr, elemPtr, &search);
        }
    } else {
        RbcChainLink   *linkPtr;

        /*
         * Find the closest point from the set of displayed elements,
         * searching the display list from back to front.  That way if
         * the points from two different elements overlay each other
         * exactly, the last one picked will be the topmost.
         */
        for (linkPtr = RbcChainLastLink(graphPtr->elements.displayList);
            linkPtr != NULL; linkPtr = RbcChainPrevLink(linkPtr)) {
            elemPtr = RbcChainGetValue(linkPtr);

            /* Check if the X or Y vectors have notifications pending */
            if ((elemPtr->flags & RBC_MAP_ITEM) ||
                (RbcVectorNotifyPending(elemPtr->x.clientId)) ||
                (RbcVectorNotifyPending(elemPtr->y.clientId))) {
                continue;
            }
            if (!elemPtr->hidden) {
                (*elemPtr->procsPtr->closestProc) (graphPtr, elemPtr, &search);
            }
        }

    }
    if (search.dist < (double) search.halo) {
        char            string[200];
        /*
         *  Return an array of 5 elements
         */
        if (Tcl_SetVar2(interp, argv[5], "name",
                search.elemPtr->name, flags) == NULL) {
            return TCL_ERROR;
        }
        sprintf(string, "%d", search.index);
        if (Tcl_SetVar2(interp, argv[5], "index", string, flags) == NULL) {
            return TCL_ERROR;
        }
        Tcl_PrintDouble(interp, search.point.x, string);
        if (Tcl_SetVar2(interp, argv[5], "x", string, flags) == NULL) {
            return TCL_ERROR;
        }
        Tcl_PrintDouble(interp, search.point.y, string);
        if (Tcl_SetVar2(interp, argv[5], "y", string, flags) == NULL) {
            return TCL_ERROR;
        }
        Tcl_PrintDouble(interp, search.dist, string);
        if (Tcl_SetVar2(interp, argv[5], "dist", string, flags) == NULL) {
            return TCL_ERROR;
        }
        Tcl_SetObjResult(interp, Tcl_NewIntObj(1));
    } else {
        if (Tcl_SetVar2(interp, argv[5], "name", "", flags) == NULL) {
            return TCL_ERROR;
        }
        Tcl_SetObjResult(interp, Tcl_NewIntObj(0));
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigureOp --
 *
 *      Sets the element specifications by the given the command line
 *      arguments and calls the element specification configuration
 *      routine. If zero or one command line options are given, only
 *      information about the option(s) is returned in interp->result.
 *      If the element configuration has changed and the element is
 *      currently displayed, the axis limits are updated and
 *      recomputed.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      Graph will be redrawn to reflect the new display list.
 *
 *----------------------------------------------------------------------
 */
static int
ConfigureOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char *argv[])
{
    RbcElement     *elemPtr;
    int             flags;
    int             numNames, numOpts;
    const char    **options;
    register int    i;

    /* Figure out where the option value pairs begin */
    argc -= 3;
    argv += 3;
    for (i = 0; i < argc; i++) {
        if (argv[i][0] == '-') {
            break;
        }
        if (NameToElement(graphPtr, argv[i], &elemPtr) != TCL_OK) {
            return TCL_ERROR;   /* Can't find named element */
        }
    }
    numNames = i;               /* Number of element names specified */
    numOpts = argc - i;         /* Number of options specified */
    options = argv + numNames;  /* Start of options in argv  */

    for (i = 0; i < numNames; i++) {
        NameToElement(graphPtr, argv[i], &elemPtr);
        flags = TK_CONFIG_ARGV_ONLY;
        if (numOpts == 0) {
            return Tk_ConfigureInfo(interp, graphPtr->tkwin,
                elemPtr->specsPtr, (char *) elemPtr, (char *) NULL, flags);
        } else if (numOpts == 1) {
            return Tk_ConfigureInfo(interp, graphPtr->tkwin,
                elemPtr->specsPtr, (char *) elemPtr, options[0], flags);
        }
        if (Tk_ConfigureWidget(interp, graphPtr->tkwin, elemPtr->specsPtr,
                numOpts, options, (char *) elemPtr, flags) != TCL_OK) {
            return TCL_ERROR;
        }
        if ((*elemPtr->procsPtr->configProc) (graphPtr, elemPtr) != TCL_OK) {
            return TCL_ERROR;   /* Failed to configure element */
        }
        if (RbcConfigModified(elemPtr->specsPtr, "-hide", (char *) NULL)) {
            RbcChainLink   *linkPtr;

            for (linkPtr = RbcChainFirstLink(graphPtr->elements.displayList);
                linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
                if (elemPtr == RbcChainGetValue(linkPtr)) {
                    break;
                }
            }
            if ((elemPtr->hidden) != (linkPtr == NULL)) {

                /* The element's "hidden" variable is out of sync with
                 * the display list. [That's what you get for having
                 * two ways to do the same thing.]  This affects what
                 * elements are considered for axis ranges and
                 * displayed in the legend. Update the display list by
                 * either by adding or removing the element.  */

                if (linkPtr == NULL) {
                    RbcChainPrepend(graphPtr->elements.displayList, elemPtr);
                } else {
                    RbcChainDeleteLink(graphPtr->elements.displayList, linkPtr);
                }
            }
            graphPtr->flags |= RBC_RESET_AXES;
            elemPtr->flags |= RBC_MAP_ITEM;
        }
        /* If data points or axes have changed, reset the axes (may
         * affect autoscaling) and recalculate the screen points of
         * the element. */

        if (RbcConfigModified(elemPtr->specsPtr, "-*data", "-map*", "-x",
                "-y", (char *) NULL)) {
            graphPtr->flags |= RBC_RESET_WORLD;
            elemPtr->flags |= RBC_MAP_ITEM;
        }
        /* The new label may change the size of the legend */
        if (RbcConfigModified(elemPtr->specsPtr, "-label", (char *) NULL)) {
            graphPtr->flags |= (RBC_MAP_WORLD | RBC_REDRAW_WORLD);
        }
    }
    /* Update the pixmap if any configuration option changed */
    graphPtr->flags |= (RBC_REDRAW_BACKING_STORE | RBC_DRAW_MARGINS);
    RbcEventuallyRedrawGraph(graphPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DeactivateOp --
 *
 *      Clears the active bit for the named elements.
 *
 * Results:
 *      Returns TCL_OK if no errors occurred.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
DeactivateOp(
    RbcGraph * graphPtr,        /* Graph widget */
    Tcl_Interp * interp,        /* Not used. */
    int argc,                   /* Number of element names */
    const char **argv)
{                               /* List of element names */
    RbcElement     *elemPtr;
    register int    i;

    for (i = 3; i < argc; i++) {
        if (NameToElement(graphPtr, argv[i], &elemPtr) != TCL_OK) {
            return TCL_ERROR;   /* Can't find named element */
        }
        elemPtr->flags &= ~RBC_ELEM_ACTIVE;
        if (elemPtr->activeIndices != NULL) {
            ckfree((char *) elemPtr->activeIndices);
            elemPtr->activeIndices = NULL;
        }
        elemPtr->nActiveIndices = 0;
    }
    RbcEventuallyRedrawGraph(graphPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DeleteOp --
 *
 *      Delete the named elements from the graph.
 *
 * Results:
 *      TCL_ERROR is returned if any of the named elements can not be
 *      found.  Otherwise TCL_OK is returned;
 *
 * Side Effects:
 *      If the element is currently displayed, the plotting area of
 *      the graph is redrawn. Memory and resources allocated by the
 *      elements are released.
 *
 *----------------------------------------------------------------------
 */
static int
DeleteOp(
    RbcGraph * graphPtr,        /* Graph widget */
    Tcl_Interp * interp,        /* Not used. */
    int argc,                   /* Number of element names */
    const char **argv)
{                               /* List of element names */
    RbcElement     *elemPtr;
    register int    i;

    for (i = 3; i < argc; i++) {
        if (NameToElement(graphPtr, argv[i], &elemPtr) != TCL_OK) {
            return TCL_ERROR;   /* Can't find named element */
        }
        DestroyElement(graphPtr, elemPtr);
    }
    RbcEventuallyRedrawGraph(graphPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ExistsOp --
 *
 *      Indicates if the named element exists in the graph.
 *
 * Results:
 *      The return value is a standard Tcl result.  The interpreter
 *      result will contain "1" or "0".
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ExistsOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,                   /* Not used. */
    const char **argv)
{
    Tcl_HashEntry  *hPtr;

    hPtr = Tcl_FindHashEntry(&graphPtr->elements.table, argv[3]);
    Tcl_SetObjResult(interp, Tcl_NewBooleanObj((hPtr != NULL)));
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * GetOp --
 *
 *      Returns the name of the picked element (using the element
 *      bind operation).  Right now, the only name accepted is
 *      "current".
 *
 * Results:
 *      A standard Tcl result.  The interpreter result will contain
 *      the name of the element.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,                   /* Not used. */
    const char *argv[])
{
    register RbcElement *elemPtr;

    if ((argv[3][0] == 'c') && (strcmp(argv[3], "current") == 0)) {
        elemPtr = (RbcElement *) RbcGetCurrentItem(graphPtr->bindTable);
        /* Report only on elements. */
        if ((elemPtr != NULL) &&
            ((elemPtr->classUid == rbcBarElementUid) ||
                (elemPtr->classUid == rbcLineElementUid) ||
                (elemPtr->classUid == rbcStripElementUid))) {
            Tcl_SetObjResult(interp, Tcl_NewStringObj(elemPtr->name, -1));
        }
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * NamesOp --
 *
 *      Returns the names of the elements is the graph matching
 *      one of more patterns provided.  If no pattern arguments
 *      are given, then all element names will be returned.
 *
 * Results:
 *      The return value is a standard Tcl result. The interpreter
 *      result will contain a Tcl list of the element names.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
NamesOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcElement     *elemPtr;
    Tcl_HashSearch  cursor;
    register Tcl_HashEntry *hPtr;
    register int    i;

    for (hPtr = Tcl_FirstHashEntry(&graphPtr->elements.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        elemPtr = (RbcElement *) Tcl_GetHashValue(hPtr);
        if (argc == 3) {
            Tcl_AppendElement(graphPtr->interp, elemPtr->name);
            continue;
        }
        for (i = 3; i < argc; i++) {
            if (Tcl_StringMatch(elemPtr->name, argv[i])) {
                Tcl_AppendElement(interp, elemPtr->name);
                break;
            }
        }
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ShowOp --
 *
 *      Queries or resets the element display list.
 *
 * Results:
 *      The return value is a standard Tcl result. The interpreter
 *      result will contain the new display list of element names.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ShowOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcElement     *elemPtr;
    RbcChainLink   *linkPtr;

    if (argc == 4) {
        if (RebuildDisplayList(graphPtr, argv[3]) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    for (linkPtr = RbcChainFirstLink(graphPtr->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        Tcl_AppendElement(interp, elemPtr->name);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TypeOp --
 *
 *      Returns the name of the type of the element given by some
 *      element name.
 *
 * Results:
 *      A standard Tcl result. Returns the type of the element in
 *      interp->result. If the identifier given doesn't represent an
 *      element, then an error message is left in interp->result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
TypeOp(
    RbcGraph * graphPtr,        /* Graph widget */
    Tcl_Interp * interp,
    int argc,                   /* Not used. */
    const char **argv)
{                               /* Element name */
    RbcElement     *elemPtr;

    if (NameToElement(graphPtr, argv[3], &elemPtr) != TCL_OK) {
        return TCL_ERROR;       /* Can't find named element */
    }
    Tcl_SetObjResult(interp, Tcl_NewStringObj(elemPtr->classUid, -1));
    return TCL_OK;
}

/*
 * Global routines:
 */
static RbcOpSpec elemOps[] = {
    {"activate", 1, (RbcOp) ActivateOp, 3, 0, "?elemName? ?index...?",},
    {"bind", 1, (RbcOp) BindOp, 3, 6, "elemName sequence command",},
    {"cget", 2, (RbcOp) CgetOp, 5, 5, "elemName option",},
    {"closest", 2, (RbcOp) ClosestOp, 6, 0,
        "x y varName ?option value?... ?elemName?...",},
    {"configure", 2, (RbcOp) ConfigureOp, 4, 0,
        "elemName ?elemName?... ?option value?...",},
    {"create", 2, (RbcOp) CreateOp, 4, 0, "elemName ?option value?...",},
    {"deactivate", 3, (RbcOp) DeactivateOp, 3, 0, "?elemName?...",},
    {"delete", 3, (RbcOp) DeleteOp, 3, 0, "?elemName?...",},
    {"exists", 1, (RbcOp) ExistsOp, 4, 4, "elemName",},
    {"get", 1, (RbcOp) GetOp, 4, 4, "name",},
    {"names", 1, (RbcOp) NamesOp, 3, 0, "?pattern?...",},
    {"show", 1, (RbcOp) ShowOp, 3, 4, "?elemList?",},
    {"type", 1, (RbcOp) TypeOp, 4, 4, "elemName",},
};

static int      numElemOps = sizeof(elemOps) / sizeof(RbcOpSpec);

/*
 * ----------------------------------------------------------------
 *
 * RbcElementOp --
 *
 *      This procedure is invoked to process the Tcl command that
 *      corresponds to a widget managed by this module.  See the user
 *      documentation for details on what it does.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *      See the user documentation.
 *
 * ----------------------------------------------------------------
 */
int
RbcElementOp(
    RbcGraph * graphPtr,        /* Graph widget record */
    Tcl_Interp * interp,
    int argc,                   /* # arguments */
    const char **argv,          /* Argument list */
    Tk_Uid type)
{
    RbcOp           proc;
    int             result;

    proc = RbcGetOp(interp, numElemOps, elemOps, RBC_OP_ARG2, argc, argv, 0);
    if (proc == NULL) {
        return TCL_ERROR;
    }
    if (proc == CreateOp) {
        result = CreateOp(graphPtr, interp, argc, argv, type);
    } else {
        result = (*proc) (graphPtr, interp, argc, argv);
    }
    return result;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted generic/rbc/rbcGrGrid.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
/*
 * rbcGrGrid.c --
 *
 *      This module implements grid lines for the rbc graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "rbcInt.h"

extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcDashesOption;
extern Tk_CustomOption rbcAnyXAxisOption;
extern Tk_CustomOption rbcAnyYAxisOption;

#define DEF_GRID_DASHES             "dot"
#define DEF_GRID_FOREGROUND         "gray64"
#define DEF_GRID_FG_MONO            "black"
#define DEF_GRID_LINE_WIDTH         "0"
#define DEF_GRID_HIDE_BARCHART      "no"
#define DEF_GRID_HIDE_GRAPH         "yes"
#define DEF_GRID_MINOR              "yes"
#define DEF_GRID_MAP_X_GRAPH        "x"
#define DEF_GRID_MAP_X_BARCHART     (char *)NULL
#define DEF_GRID_MAP_Y              "y"
#define DEF_GRID_POSITION           (char *)NULL

static Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_COLOR, "-color", "color", "Color", DEF_GRID_FOREGROUND,
            Tk_Offset(RbcGrid, colorPtr),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-color", "color", "color", DEF_GRID_FG_MONO,
        Tk_Offset(RbcGrid, colorPtr), TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-dashes", "dashes", "Dashes", DEF_GRID_DASHES,
            Tk_Offset(RbcGrid, dashes), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS,
        &rbcDashesOption},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide", DEF_GRID_HIDE_BARCHART,
        Tk_Offset(RbcGrid, hidden), RBC_BARCHART},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide", DEF_GRID_HIDE_GRAPH,
        Tk_Offset(RbcGrid, hidden), RBC_GRAPH | RBC_STRIPCHART},
    {TK_CONFIG_CUSTOM, "-linewidth", "lineWidth", "Linewidth",
            DEF_GRID_LINE_WIDTH, Tk_Offset(RbcGrid, lineWidth),
        TK_CONFIG_DONT_SET_DEFAULT | RBC_ALL_GRAPHS, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX", DEF_GRID_MAP_X_GRAPH,
            Tk_Offset(RbcGrid, axes.x), RBC_GRAPH | RBC_STRIPCHART,
        &rbcAnyXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX", DEF_GRID_MAP_X_BARCHART,
        Tk_Offset(RbcGrid, axes.x), RBC_BARCHART, &rbcAnyXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapy", "mapY", "MapY", DEF_GRID_MAP_Y,
        Tk_Offset(RbcGrid, axes.y), RBC_ALL_GRAPHS, &rbcAnyYAxisOption},
    {TK_CONFIG_BOOLEAN, "-minor", "minor", "Minor", DEF_GRID_MINOR,
            Tk_Offset(RbcGrid, minorGrid),
        TK_CONFIG_DONT_SET_DEFAULT | RBC_ALL_GRAPHS},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

static void     ConfigureGrid(
    RbcGraph * graphPtr,
    RbcGrid * gridPtr);
static int      CgetOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      ConfigureOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      MapOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      UnmapOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      ToggleOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);

/*
 *----------------------------------------------------------------------
 *
 * ConfigureGrid --
 *
 *      Configures attributes of the grid such as line width,
 *      dashes, and position.  The grid are first turned off
 *      before any of the attributes changes.
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Crosshair GC is allocated.
 *
 *----------------------------------------------------------------------
 */
static void
ConfigureGrid(
    RbcGraph * graphPtr,
    RbcGrid * gridPtr)
{
    XGCValues       gcValues;
    unsigned long   gcMask;
    GC              newGC;

    gcValues.background = gcValues.foreground = gridPtr->colorPtr->pixel;
    gcValues.line_width = RbcLineWidth(gridPtr->lineWidth);
    gcMask = (GCForeground | GCBackground | GCLineWidth);
    if (RbcLineIsDashed(gridPtr->dashes)) {
        gcValues.line_style = LineOnOffDash;
        gcMask |= GCLineStyle;
    }
    newGC = RbcGetPrivateGC(graphPtr->tkwin, gcMask, &gcValues);
    if (RbcLineIsDashed(gridPtr->dashes)) {
        RbcSetDashes(graphPtr->display, newGC, &(gridPtr->dashes));
    }
    if (gridPtr->gc != NULL) {
        RbcFreePrivateGC(graphPtr->display, gridPtr->gc);
    }
    gridPtr->gc = newGC;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMapGrid --
 *
 *      Determines the coordinates of the line segments corresponding
 *      to the grid lines for each axis.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcMapGrid(
    RbcGraph * graphPtr)
{
    RbcGrid        *gridPtr = (RbcGrid *) graphPtr->gridPtr;
    int             nSegments;
    RbcSegment2D   *segments;

    if (gridPtr->x.segments != NULL) {
        ckfree((char *) gridPtr->x.segments);
        gridPtr->x.segments = NULL;
    }
    if (gridPtr->y.segments != NULL) {
        ckfree((char *) gridPtr->y.segments);
        gridPtr->y.segments = NULL;
    }
    gridPtr->x.nSegments = gridPtr->y.nSegments = 0;
    /*
     * Generate line segments to represent the grid.  Line segments
     * are calculated from the major tick intervals of each axis mapped.
     */
    RbcGetAxisSegments(graphPtr, gridPtr->axes.x, &segments, &nSegments);
    if (nSegments > 0) {
        gridPtr->x.nSegments = nSegments;
        gridPtr->x.segments = segments;
    }
    RbcGetAxisSegments(graphPtr, gridPtr->axes.y, &segments, &nSegments);
    if (nSegments > 0) {
        gridPtr->y.nSegments = nSegments;
        gridPtr->y.segments = segments;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDrawGrid --
 *
 *      Draws the grid lines associated with each axis.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcDrawGrid(
    RbcGraph * graphPtr,
    Drawable drawable)
{                               /* Pixmap or window to draw into */
    RbcGrid        *gridPtr = (RbcGrid *) graphPtr->gridPtr;

    if (gridPtr->hidden) {
        return;
    }
    if (gridPtr->x.nSegments > 0) {
        RbcDraw2DSegments(graphPtr->display, drawable, gridPtr->gc,
            gridPtr->x.segments, gridPtr->x.nSegments);
    }
    if (gridPtr->y.nSegments > 0) {
        RbcDraw2DSegments(graphPtr->display, drawable, gridPtr->gc,
            gridPtr->y.segments, gridPtr->y.nSegments);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGridToPostScript --
 *
 *      Prints the grid lines associated with each axis.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcGridToPostScript(
    RbcGraph * graphPtr,
    RbcPsToken * psToken)
{
    RbcGrid        *gridPtr = (RbcGrid *) graphPtr->gridPtr;

    if (gridPtr->hidden) {
        return;
    }
    RbcLineAttributesToPostScript(psToken, gridPtr->colorPtr,
        gridPtr->lineWidth, &(gridPtr->dashes), CapButt, JoinMiter);
    if (gridPtr->x.nSegments > 0) {
        Rbc2DSegmentsToPostScript(psToken, gridPtr->x.segments,
            gridPtr->x.nSegments);
    }
    if (gridPtr->y.nSegments > 0) {
        Rbc2DSegmentsToPostScript(psToken, gridPtr->y.segments,
            gridPtr->y.nSegments);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDestroyGrid --
 *
 *      TODO: Description
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Grid GC is released.
 *
 *----------------------------------------------------------------------
 */
void
RbcDestroyGrid(
    RbcGraph * graphPtr)
{
    RbcGrid        *gridPtr = (RbcGrid *) graphPtr->gridPtr;

    Tk_FreeOptions(configSpecs, (char *) gridPtr, graphPtr->display,
        RbcGraphType(graphPtr));
    if (gridPtr->gc != NULL) {
        RbcFreePrivateGC(graphPtr->display, gridPtr->gc);
    }
    if (gridPtr->x.segments != NULL) {
        ckfree((char *) gridPtr->x.segments);
    }
    if (gridPtr->y.segments != NULL) {
        ckfree((char *) gridPtr->y.segments);
    }
    ckfree((char *) gridPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcCreateGrid --
 *
 *      Creates and initializes a new grid structure.
 *
 * Results:
 *      Returns TCL_ERROR if the configuration failed, otherwise TCL_OK.
 *
 * Side Effects:
 *      Memory for grid structure is allocated.
 *
 *----------------------------------------------------------------------
 */
int
RbcCreateGrid(
    RbcGraph * graphPtr)
{
    RbcGrid        *gridPtr;

    gridPtr = RbcCalloc(1, sizeof(RbcGrid));
    assert(gridPtr);
    gridPtr->minorGrid = TRUE;
    graphPtr->gridPtr = gridPtr;

    if (RbcConfigureWidgetComponent(graphPtr->interp, graphPtr->tkwin, "grid",
            "Grid", configSpecs, 0, (const char **) NULL, (char *) gridPtr,
            RbcGraphType(graphPtr)) != TCL_OK) {
        return TCL_ERROR;
    }
    ConfigureGrid(graphPtr, gridPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * CgetOp --
 *
 *      Queries configuration attributes of the grid such as line
 *      width, dashes, and position.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
CgetOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcGrid        *gridPtr = (RbcGrid *) graphPtr->gridPtr;

    return Tk_ConfigureValue(interp, graphPtr->tkwin, configSpecs,
        (char *) gridPtr, argv[3], RbcGraphType(graphPtr));
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigureOp --
 *
 *      Queries or resets configuration attributes of the grid
 *      such as line width, dashes, and position.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Grid attributes are reset.  The graph is redrawn at the
 *      next idle point.
 *
 *----------------------------------------------------------------------
 */
static int
ConfigureOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcGrid        *gridPtr = (RbcGrid *) graphPtr->gridPtr;
    int             flags;

    flags = RbcGraphType(graphPtr) | TK_CONFIG_ARGV_ONLY;
    if (argc == 3) {
        return Tk_ConfigureInfo(interp, graphPtr->tkwin, configSpecs,
            (char *) gridPtr, (char *) NULL, flags);
    } else if (argc == 4) {
        return Tk_ConfigureInfo(interp, graphPtr->tkwin, configSpecs,
            (char *) gridPtr, argv[3], flags);
    }
    if (Tk_ConfigureWidget(graphPtr->interp, graphPtr->tkwin, configSpecs,
            argc - 3, argv + 3, (char *) gridPtr, flags) != TCL_OK) {
        return TCL_ERROR;
    }
    ConfigureGrid(graphPtr, gridPtr);
    graphPtr->flags |= RBC_REDRAW_BACKING_STORE;
    RbcEventuallyRedrawGraph(graphPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * MapOp --
 *
 *      Maps the grid.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Grid attributes are reset and the graph is redrawn if necessary.
 *
 *----------------------------------------------------------------------
 */
static int
MapOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcGrid        *gridPtr = (RbcGrid *) graphPtr->gridPtr;

    if (gridPtr->hidden) {
        gridPtr->hidden = FALSE;        /* Changes "-hide" configuration option */
        graphPtr->flags |= RBC_REDRAW_BACKING_STORE;
        RbcEventuallyRedrawGraph(graphPtr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * MapOp --
 *
 *      Maps or unmaps the grid (off or on).
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Grid attributes are reset and the graph is redrawn if necessary.
 *
 *----------------------------------------------------------------------
 */
static int
UnmapOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcGrid        *gridPtr = (RbcGrid *) graphPtr->gridPtr;

    if (!gridPtr->hidden) {
        gridPtr->hidden = TRUE; /* Changes "-hide" configuration option */
        graphPtr->flags |= RBC_REDRAW_BACKING_STORE;
        RbcEventuallyRedrawGraph(graphPtr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ToggleOp --
 *
 *      Toggles the state of the grid shown/hidden.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Grid is hidden/displayed. The graph is redrawn at the next
 *      idle time.
 *
 *----------------------------------------------------------------------
 */
static int
ToggleOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcGrid        *gridPtr = (RbcGrid *) graphPtr->gridPtr;

    gridPtr->hidden = (!gridPtr->hidden);
    graphPtr->flags |= RBC_REDRAW_BACKING_STORE;
    RbcEventuallyRedrawGraph(graphPtr);
    return TCL_OK;
}

static RbcOpSpec gridOps[] = {
    {"cget", 2, (RbcOp) CgetOp, 4, 4, "option",},
    {"configure", 2, (RbcOp) ConfigureOp, 3, 0, "?options...?",},
    {"off", 2, (RbcOp) UnmapOp, 3, 3, "",},
    {"on", 2, (RbcOp) MapOp, 3, 3, "",},
    {"toggle", 1, (RbcOp) ToggleOp, 3, 3, "",},
};

static int      nGridOps = sizeof(gridOps) / sizeof(RbcOpSpec);

/*
 *----------------------------------------------------------------------
 *
 * RbcGridOp --
 *
 *      User routine to configure grid lines.  Grids are drawn
 *      at major tick intervals across the graph.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      Grid may be drawn in the plotting area.
 *
 *----------------------------------------------------------------------
 */
int
RbcGridOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcOp           proc;

    proc = RbcGetOp(interp, nGridOps, gridOps, RBC_OP_ARG2, argc, argv, 0);
    if (proc == NULL) {
        return TCL_ERROR;
    }
    return (*proc) (graphPtr, interp, argc, argv);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted generic/rbc/rbcGrHairs.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
/*
 * rbcGrHairs.c --
 *
 *      This module implements crosshairs for the rbc graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/

#include "rbcInt.h"

extern Tk_CustomOption rbcPointOption;
extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcDashesOption;

/*
 * -------------------------------------------------------------------
 *
 * RbcCrosshairs --
 *
 *      Contains the line segments positions and graphics context used
 *      to simulate crosshairs (by XORing) on the graph.
 *
 * -------------------------------------------------------------------
 */

typedef struct RbcCrosshairs {

    XPoint          hotSpot;    /* Hot spot for crosshairs */
    int             visible;    /* Internal state of crosshairs. If non-zero,
                                 * crosshairs are displayed. */
    int             hidden;     /* If non-zero, crosshairs are not displayed.
                                 * This is not necessarily consistent with the
                                 * internal state variable.  This is true when
                                 * the hot spot is off the graph.  */
    RbcDashes       dashes;     /* Dashstyle of the crosshairs. This represents
                                 * an array of alternatingly drawn pixel
                                 * values. If NULL, the hairs are drawn as a
                                 * solid line */
    int             lineWidth;  /* Width of the simulated crosshair lines */
    XSegment        segArr[2];  /* Positions of line segments representing the
                                 * simulated crosshairs. */
    XColor         *colorPtr;   /* Foreground color of crosshairs */
    GC              gc;         /* Graphics context for crosshairs. Set to
                                 * GXxor to not require redraws of graph */
} RbcCrosshairs;

#define DEF_HAIRS_DASHES	(char *)NULL
#define DEF_HAIRS_FOREGROUND	"#000000"
#define DEF_HAIRS_FG_MONO	"#000000"
#define DEF_HAIRS_LINE_WIDTH	"0"
#define DEF_HAIRS_HIDE		"yes"
#define DEF_HAIRS_POSITION	(char *)NULL

static const Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_COLOR, "-color", "color", "Color", DEF_HAIRS_FOREGROUND,
        Tk_Offset(RbcCrosshairs, colorPtr), TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-color", "color", "Color", DEF_HAIRS_FG_MONO,
        Tk_Offset(RbcCrosshairs, colorPtr), TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_CUSTOM, "-dashes", "dashes", "Dashes", DEF_HAIRS_DASHES,
            Tk_Offset(RbcCrosshairs, dashes), TK_CONFIG_NULL_OK,
        &rbcDashesOption},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide", DEF_HAIRS_HIDE,
        Tk_Offset(RbcCrosshairs, hidden), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-linewidth", "lineWidth", "Linewidth",
            DEF_HAIRS_LINE_WIDTH, Tk_Offset(RbcCrosshairs, lineWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-position", "position", "Position", DEF_HAIRS_POSITION,
        Tk_Offset(RbcCrosshairs, hotSpot), 0, &rbcPointOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

/* TODO new object code
static const Tk_OptionSpec optionSpecs[] = {
    {TK_OPTION_COLOR, "-color", "color", "Color", DEF_HAIRS_FOREGROUND, -1, Tk_Offset(Crosshairs, colorPtr), TK_CONFIG_COLOR_ONLY, NULL, 0},
    {TK_OPTION_COLOR, "-color", "color", "Color", DEF_HAIRS_FG_MONO, -1, Tk_Offset(Crosshairs, colorPtr), TK_CONFIG_MONO_ONLY, NULL, 0},
    {TK_OPTION_CUSTOM, "-dashes", "dashes", "Dashes", DEF_HAIRS_DASHES, -1, Tk_Offset(Crosshairs, dashes), TK_CONFIG_NULL_OK, &rbcDashesOption, 0},
    {TK_OPTION_BOOLEAN, "-hide", "hide", "Hide", DEF_HAIRS_HIDE, -1, Tk_Offset(Crosshairs, hidden), TK_CONFIG_DONT_SET_DEFAULT, NULL, 0},
    {TK_OPTION_CUSTOM, "-linewidth", "lineWidth", "Linewidth", DEF_HAIRS_LINE_WIDTH, -1, Tk_Offset(Crosshairs, lineWidth), TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption, 0},
    {TK_OPTION_CUSTOM, "-position", "position", "Position", DEF_HAIRS_POSITION, -1, Tk_Offset(Crosshairs, hotSpot), 0, &rbcPointOption, 0},
    {TK_OPTION_END, NULL, NULL, NULL, NULL, 0, -1, 0, NULL, 0}
};
*/

static void     TurnOffHairs(
    Tk_Window tkwin,
    RbcCrosshairs * chPtr);
static void     TurnOnHairs(
    RbcGraph * graphPtr,
    RbcCrosshairs * chPtr);
static int      CgetOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      ConfigureOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      OnOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      OffOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int      ToggleOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv);

/*
 *----------------------------------------------------------------------
 *
 * TurnOffHairs --
 *
 *      XOR's the existing line segments (representing the crosshairs),
 *      thereby erasing them.  The internal state of the crosshairs is
 *      tracked.
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Crosshairs are erased.
 *
 *----------------------------------------------------------------------
 */
static void
TurnOffHairs(
    Tk_Window tkwin,
    RbcCrosshairs * chPtr)
{
    if (Tk_IsMapped(tkwin) && (chPtr->visible)) {
        XDrawSegments(Tk_Display(tkwin), Tk_WindowId(tkwin), chPtr->gc,
            chPtr->segArr, 2);
        chPtr->visible = FALSE;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TurnOnHairs --
 *
 *      Draws (by XORing) new line segments, creating the effect of
 *      crosshairs. The internal state of the crosshairs is tracked.
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Crosshairs are displayed.
 *
 *----------------------------------------------------------------------
 */
static void
TurnOnHairs(
    RbcGraph * graphPtr,
    RbcCrosshairs * chPtr)
{
    if (Tk_IsMapped(graphPtr->tkwin) && (!chPtr->visible)) {
        /* Coordinates are off the graph */
        if (chPtr->hotSpot.x > graphPtr->right
            || chPtr->hotSpot.x < graphPtr->left
            || chPtr->hotSpot.y > graphPtr->bottom
            || chPtr->hotSpot.y < graphPtr->top)
            return;
        XDrawSegments(graphPtr->display, Tk_WindowId(graphPtr->tkwin),
            chPtr->gc, chPtr->segArr, 2);
        chPtr->visible = TRUE;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcConfigureCrosshairs --
 *
 *      Configures attributes of the crosshairs such as line width,
 *      dashes, and position.  The crosshairs are first turned off
 *      before any of the attributes changes.
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Crosshair GC is allocated.
 *
 *----------------------------------------------------------------------
 */
void
RbcConfigureCrosshairs(
    RbcGraph * graphPtr)
{
    XGCValues       gcValues;
    unsigned long   gcMask;
    GC              newGC;
    long            colorValue;
    RbcCrosshairs  *chPtr = graphPtr->crosshairs;

    /*
     * Turn off the crosshairs temporarily. This is in case the new
     * configuration changes the size, style, or position of the lines.
     */
    TurnOffHairs(graphPtr->tkwin, chPtr);

    gcValues.function = GXxor;

    if (graphPtr->plotBg == NULL) {
        /* The graph's color option may not have been set yet */
        colorValue = WhitePixelOfScreen(Tk_Screen(graphPtr->tkwin));
    } else {
        colorValue = graphPtr->plotBg->pixel;
    }
    gcValues.background = colorValue;
    gcValues.foreground = (colorValue ^ chPtr->colorPtr->pixel);

    gcValues.line_width = RbcLineWidth(chPtr->lineWidth);
    gcMask = (GCForeground | GCBackground | GCFunction | GCLineWidth);
    if (RbcLineIsDashed(chPtr->dashes)) {
        gcValues.line_style = LineOnOffDash;
        gcMask |= GCLineStyle;
    }
    newGC = RbcGetPrivateGC(graphPtr->tkwin, gcMask, &gcValues);
    if (RbcLineIsDashed(chPtr->dashes)) {
        RbcSetDashes(graphPtr->display, newGC, &(chPtr->dashes));
    }
    if (chPtr->gc != NULL) {
        RbcFreePrivateGC(graphPtr->display, chPtr->gc);
    }
    chPtr->gc = newGC;

    /*
     * Are the new coordinates on the graph?
     */
    chPtr->segArr[0].x2 = chPtr->segArr[0].x1 = chPtr->hotSpot.x;
    chPtr->segArr[0].y1 = graphPtr->bottom;
    chPtr->segArr[0].y2 = graphPtr->top;
    chPtr->segArr[1].y2 = chPtr->segArr[1].y1 = chPtr->hotSpot.y;
    chPtr->segArr[1].x1 = graphPtr->left;
    chPtr->segArr[1].x2 = graphPtr->right;

    if (!chPtr->hidden) {
        TurnOnHairs(graphPtr, chPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcEnableCrosshairs --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcEnableCrosshairs(
    RbcGraph * graphPtr)
{
    if (!graphPtr->crosshairs->hidden) {
        TurnOnHairs(graphPtr, graphPtr->crosshairs);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDisableCrosshairs --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcDisableCrosshairs(
    RbcGraph * graphPtr)
{
    if (!graphPtr->crosshairs->hidden) {
        TurnOffHairs(graphPtr->tkwin, graphPtr->crosshairs);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcUpdateCrosshairs --
 *
 *      Update the length of the hairs (not the hot spot).
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcUpdateCrosshairs(
    RbcGraph * graphPtr)
{
    RbcCrosshairs  *chPtr = graphPtr->crosshairs;

    chPtr->segArr[0].y1 = graphPtr->bottom;
    chPtr->segArr[0].y2 = graphPtr->top;
    chPtr->segArr[1].x1 = graphPtr->left;
    chPtr->segArr[1].x2 = graphPtr->right;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDestroyCrosshairs --
 *
 *      TODO: Description
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Crosshair GC is allocated.
 *
 *----------------------------------------------------------------------
 */
void
RbcDestroyCrosshairs(
    RbcGraph * graphPtr)
{
    RbcCrosshairs  *chPtr = graphPtr->crosshairs;

    Tk_FreeOptions(configSpecs, (char *) chPtr, graphPtr->display, 0);
    if (chPtr->gc != NULL) {
        RbcFreePrivateGC(graphPtr->display, chPtr->gc);
    }
    ckfree((char *) chPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcCreateCrosshairs --
 *
 *      Creates and initializes a new crosshair structure.
 *
 * Results:
 *      Returns TCL_ERROR if the crosshair structure can't be created,
 *      otherwise TCL_OK.
 *
 * Side Effects:
 *      Crosshair GC is allocated.
 *
 *----------------------------------------------------------------------
 */
int
RbcCreateCrosshairs(
    RbcGraph * graphPtr)
{
    RbcCrosshairs  *chPtr;

    chPtr = RbcCalloc(1, sizeof(RbcCrosshairs));
    assert(chPtr);
    chPtr->hidden = TRUE;
    chPtr->hotSpot.x = chPtr->hotSpot.y = -1;
    graphPtr->crosshairs = chPtr;

    if (RbcConfigureWidgetComponent(graphPtr->interp, graphPtr->tkwin,
            "crosshairs", "Crosshairs", configSpecs, 0, (const char **) NULL,
            (char *) chPtr, 0) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * CgetOp --
 *
 *      Queries configuration attributes of the crosshairs such as
 *      line width, dashes, and position.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
CgetOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,                   /* Not used. */
    const char **argv)
{
    RbcCrosshairs  *chPtr = graphPtr->crosshairs;

    return Tk_ConfigureValue(interp, graphPtr->tkwin, configSpecs,
        (char *) chPtr, argv[3], 0);
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigureOp --
 *
 *      Queries or resets configuration attributes of the crosshairs
 *      such as line width, dashes, and position.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Crosshairs are reset.
 *
 *----------------------------------------------------------------------
 */
static int
ConfigureOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcCrosshairs  *chPtr = graphPtr->crosshairs;

    if (argc == 3) {
        return Tk_ConfigureInfo(interp, graphPtr->tkwin, configSpecs,
            (char *) chPtr, (char *) NULL, 0);
    } else if (argc == 4) {
        return Tk_ConfigureInfo(interp, graphPtr->tkwin, configSpecs,
            (char *) chPtr, argv[3], 0);
    }
    if (Tk_ConfigureWidget(interp, graphPtr->tkwin, configSpecs, argc - 3,
            argv + 3, (char *) chPtr, TK_CONFIG_ARGV_ONLY) != TCL_OK) {
        return TCL_ERROR;
    }
    RbcConfigureCrosshairs(graphPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * OnOp --
 *
 *      Maps the crosshairs.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Crosshairs are reset if necessary.
 *
 *----------------------------------------------------------------------
 */
static int
OnOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcCrosshairs  *chPtr = graphPtr->crosshairs;

    if (chPtr->hidden) {
        TurnOnHairs(graphPtr, chPtr);
        chPtr->hidden = FALSE;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * OffOp --
 *
 *      Unmaps the crosshairs.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Crosshairs are reset if necessary.
 *
 *----------------------------------------------------------------------
 */
static int
OffOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcCrosshairs  *chPtr = graphPtr->crosshairs;

    if (!chPtr->hidden) {
        TurnOffHairs(graphPtr->tkwin, chPtr);
        chPtr->hidden = TRUE;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ToggleOp --
 *
 *      Toggles the state of the crosshairs.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Crosshairs are reset.
 *
 *----------------------------------------------------------------------
 */
static int
ToggleOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcCrosshairs  *chPtr = graphPtr->crosshairs;

    chPtr->hidden = (chPtr->hidden == 0);
    if (chPtr->hidden) {
        TurnOffHairs(graphPtr->tkwin, chPtr);
    } else {
        TurnOnHairs(graphPtr, chPtr);
    }
    return TCL_OK;
}

static RbcOpSpec xhairOps[] = {
    {"cget", 2, (RbcOp) CgetOp, 4, 4, "option",},
    {"configure", 2, (RbcOp) ConfigureOp, 3, 0, "?options...?",},
    {"off", 2, (RbcOp) OffOp, 3, 3, "",},
    {"on", 2, (RbcOp) OnOp, 3, 3, "",},
    {"toggle", 1, (RbcOp) ToggleOp, 3, 3, "",},
};

static int      nXhairOps = sizeof(xhairOps) / sizeof(RbcOpSpec);

/*
 *----------------------------------------------------------------------
 *
 * RbcCrosshairsOp --
 *
 *      User routine to configure crosshair simulation.  Crosshairs
 *      are simulated by drawing line segments parallel to both axes
 *      using the XOR drawing function. The allows the lines to be
 *      erased (by drawing them again) without redrawing the entire
 *      graph.  Care must be taken to erase crosshairs before redrawing
 *      the graph and redraw them after the graph is redraw.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      Crosshairs may be drawn in the plotting area.
 *
 *----------------------------------------------------------------------
 */
int
RbcCrosshairsOp(
    RbcGraph * graphPtr,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcOp           proc;

    proc = RbcGetOp(interp, nXhairOps, xhairOps, RBC_OP_ARG2, argc, argv, 0);
    if (proc == NULL) {
        return TCL_ERROR;
    }
    return (*proc) (graphPtr, interp, argc, argv);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted generic/rbc/rbcGrLegd.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
/*
 * rbcGrLegd.c --
 *
 *      This module implements the legend for the rbc graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "rbcInt.h"

/*
 * -------------------------------------------------------------------
 *
 * Legend --
 *
 *      Contains information specific to how the legend will be
 *      displayed.
 *
 * -------------------------------------------------------------------
 */
typedef struct RbcLegend {
    unsigned int    flags;
    Tk_Uid          classUid;   /* Type: Element or Marker. */
    int             hidden;     /* If non-zero, don't display the legend. */
    int             raised;     /* If non-zero, draw the legend last, above
                                 * everything else. */
    int             nEntries;   /* Number of element entries in table. */
    short int       width, height;      /* Dimensions of the legend */
    short int       nColumns, nRows;    /* Number of columns and rows in legend */
    int             site;
    RbcPoint2D      anchorPos;  /* Says how to position the legend. Indicates
                                 * the site and/or x-y screen coordinates of
                                 * the legend.  Used in conjunction with the
                                 * anchor to determine its location. */
    Tk_Anchor       anchor;     /* Anchor of legend. Used to interpret the
                                 * positioning point of the legend in the
                                 * graph*/
    int             x, y;       /* Computed origin of legend. */
    RbcGraph       *graphPtr;
    Tcl_Command     cmdToken;   /* Token for graph's widget command. */
    int             reqColumns, reqRows;
    RbcPad          ipadX, ipadY;       /* # of pixels padding around legend entries */
    RbcPad          padX, padY; /* # of pixels padding to exterior of legend */
    Tk_Window       tkwin;      /* Optional external window to draw legend. */
    RbcTextStyle    style;
    int             maxSymSize; /* Size of largest symbol to be displayed.
                                 * Used to calculate size of legend */
    Tk_3DBorder     activeBorder;       /* Active legend entry background color. */
    int             activeRelief;       /* 3-D effect on active entry. */
    int             entryBorderWidth;   /* Border width around each entry in legend. */
    Tk_3DBorder     border;     /* 3-D effect of legend. */
    int             borderWidth;        /* Width of legend 3-D border */
    int             relief;     /* 3-d effect of border around the legend:
                                 * TK_RELIEF_RAISED etc. */
    RbcBindTable   *bindTable;
} RbcLegend;

#define DEF_LEGEND_ACTIVE_BACKGROUND    RBC_ACTIVE_BACKGROUND
#define DEF_LEGEND_ACTIVE_BG_MONO       RBC_ACTIVE_BG_MONO
#define DEF_LEGEND_ACTIVE_BORDERWIDTH   "2"
#define DEF_LEGEND_ACTIVE_FOREGROUND    RBC_ACTIVE_FOREGROUND
#define DEF_LEGEND_ACTIVE_FG_MONO       RBC_ACTIVE_FG_MONO
#define DEF_LEGEND_ACTIVE_RELIEF        "flat"
#define DEF_LEGEND_ANCHOR               "n"
#define DEF_LEGEND_BACKGROUND           (char *)NULL
#define DEF_LEGEND_BG_MONO              (char *)NULL
#define DEF_LEGEND_BORDERWIDTH          RBC_BORDERWIDTH
#define DEF_LEGEND_FOREGROUND           RBC_NORMAL_FOREGROUND
#define DEF_LEGEND_FG_MONO              RBC_NORMAL_FG_MONO
#define DEF_LEGEND_FONT                 RBC_FONT_SMALL
#define DEF_LEGEND_HIDE                 "no"
#define DEF_LEGEND_IPAD_X               "1"
#define DEF_LEGEND_IPAD_Y               "1"
#define DEF_LEGEND_PAD_X                "1"
#define DEF_LEGEND_PAD_Y                "1"
#define DEF_LEGEND_POSITION             "rightmargin"
#define DEF_LEGEND_RAISED               "no"
#define DEF_LEGEND_RELIEF               "sunken"
#define DEF_LEGEND_SHADOW_COLOR         (char *)NULL
#define DEF_LEGEND_SHADOW_MONO          (char *)NULL
#define DEF_LEGEND_ROWS                 "0"
#define DEF_LEGEND_COLUMNS              "0"

static Tk_OptionParseProc StringToPosition;
static Tk_OptionPrintProc PositionToString;
static Tk_CustomOption legendPositionOption = {
    StringToPosition, PositionToString, (ClientData) 0
};

extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcPadOption;
extern Tk_CustomOption rbcShadowOption;
extern Tk_CustomOption rbcCountOption;

static Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_BORDER, "-activebackground", "activeBackground",
            "ActiveBackground", DEF_LEGEND_ACTIVE_BACKGROUND,
        Tk_Offset(RbcLegend, activeBorder), TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_BORDER, "-activebackground", "activeBackground",
            "ActiveBackground", DEF_LEGEND_ACTIVE_BG_MONO, Tk_Offset(RbcLegend,
            activeBorder), TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_CUSTOM, "-activeborderwidth", "activeBorderWidth", "BorderWidth",
            DEF_LEGEND_BORDERWIDTH, Tk_Offset(RbcLegend, entryBorderWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_COLOR, "-activeforeground", "activeForeground",
            "ActiveForeground", DEF_LEGEND_ACTIVE_FOREGROUND,
        Tk_Offset(RbcLegend, style.activeColor), TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-activeforeground", "activeForeground",
            "ActiveForeground", DEF_LEGEND_ACTIVE_FG_MONO, Tk_Offset(RbcLegend,
            style.activeColor), TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_RELIEF, "-activerelief", "activeRelief", "Relief",
            DEF_LEGEND_ACTIVE_RELIEF, Tk_Offset(RbcLegend, activeRelief),
        TK_CONFIG_