Tcl Source Code

Check-in [1d719b3ad1]
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:Created branch scriptics-tclpro-1-2-synthetic
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | scriptics-tclpro-1-2 | scriptics-tclpro-1-2-synthetic
Files: files | file ages | folders
SHA1: 1d719b3ad1c19c3c90a8f4ca931caeed9ba2c8d7
User & Date: cvs2fossil 1999-02-19 02:17:04
Context
1999-02-19
02:17
Created branch scriptics-tclpro-1-2-synthetic Closed-Leaf check-in: 1d719b3ad1 user: cvs2fossil tags: scriptics-tclpro-1-2, scriptics-tclpro-1-2-synthetic
02:17
changed so helpfile generation can work from the build environment check-in: 29c3f02f33 user: stanton tags: core-8-0-5-branch
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Deleted README.

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
Tcl

RCS: @(#) $Id: README,v 1.13 1999/02/09 03:31:55 stanton Exp $

1. Introduction
---------------

This directory and its descendants contain the sources and documentation
for Tcl, an embeddable scripting language.  The information here
corresponds to release 8.0.5, which is the fifth patch update for Tcl 8.0.
This patch includes many bug fixes; see the "changes" file for a complete
list.  Tcl 8.0 is a major new release that replaces the core of the
interpreter with an on-the-fly bytecode compiler to improve execution
speed.  It also includes several other new features such as namespaces and
binary I/O, plus many bug fixes.  The compiler introduces a few
incompatibilities that may affect existing Tcl scripts; the
incompatibilities are relatively obscure but may require modifications to
some old scripts before they can run with this version. The compiler
introduces many new C-level APIs, but the old APIs are still supported.
See below for more details.

2. Documentation
----------------

The best way to get started with Tcl is to read one of the introductory
books on Tcl:

    Practical Programming in Tcl and Tk, 2nd Edition, by Brent Welch,
    Prentice-Hall, 1997, ISBN 0-13-616830-2

    Tcl and the Tk Toolkit, by John Ousterhout,
    Addison-Wesley, 1994, ISBN 0-201-63337-X

    Exploring Expect, by Don Libes,
    O'Reilly and Associates, 1995, ISBN 1-56592-090-2

Other books are listed at
http://www.scriptics.com/resource/doc/books/
http://www.tclconsortium.org/resources/books.html

The "doc" subdirectory in this release contains a complete set of reference
manual entries for Tcl.  Files with extension ".1" are for programs (for
example, tclsh.1); files with extension ".3" are for C library procedures;
and files with extension ".n" describe Tcl commands.  The file "doc/Tcl.n"
gives a quick summary of the Tcl language syntax.  To print any of the man
pages, cd to the "doc" directory and invoke your favorite variant of
troff using the normal -man macros, for example

		ditroff -man Tcl.n

to print Tcl.n.  If Tcl has been installed correctly and your "man"
program supports it, you should be able to access the Tcl manual entries
using the normal "man" mechanisms, such as

		man Tcl

There is also an official home for Tcl and Tk on the Web:
	http://www.scriptics.com
These Web pages include information about the latest releases, products
related to Tcl and Tk, reports on bug fixes and porting issues, HTML
versions of the manual pages, and pointers to many other Tcl/Tk Web
pages at other sites.  Check them out!

3. Compiling and installing Tcl
-------------------------------

This release contains everything you should need to compile and run
Tcl under UNIX, Macintoshes, and PCs (either Windows NT, Windows 95,
or Win 3.1 with Win32s).

Before trying to compile Tcl you should do the following things:

    (a) Check for a binary release.  Pre-compiled binary releases are
        available now for PCs, Macintoshes, and several flavors of UNIX.
        Binary releases are much easier to install than source releases.
        To find out whether a binary release is available for your
        platform, check the Scriptics Tcl Resource Center
        (http://www.scriptics.com/resource).  Also, check in
        the FTP directory from which you retrieved the base
        distribution.

    (b) Make sure you have the most recent patch release.  Look in the
	FTP directory from which you retrieved this distribution to see
	if it has been updated with patches.  Patch releases fix bugs
	without changing any features, so you should normally use the
	latest patch release for the version of Tcl that you want. 
	Patch releases are available in two forms.  A file like
	tcl8.0.5.tar.Z is a complete release for patch level 5 of Tcl
	version 8.0.  If there is a file with a higher patch level than
	this release, just fetch the file with the highest patch level
	and use it.

Once you've done this, change to the "unix" subdirectory if you're
compiling under UNIX, "win" if you're compiling under Windows, or
"mac" if you're compiling on a Macintosh.  Then follow the instructions
in the README file in that directory for compiling Tcl, installing it,
and running the test suite.

4. Summary of changes in Tcl 8.0
--------------------------------

Here are the most significant changes in Tcl 8.0.  In addition to these
changes, there are several smaller changes and bug fixes.  See the file
"changes" for a complete list of all changes.

    1. Bytecode compiler.  The core of the Tcl interpreter has been
    replaced with an on-the-fly compiler that translates Tcl scripts to
    byte codes; a new interpreter then executes the byte codes. In
    earlier versions of Tcl, strings were used as a universal
    representation;  in Tcl 8.0 strings are replaced with Tcl_Obj
    structures ("objects") that can hold both a string value and an
    internal form such as a binary integer or compiled bytecodes.  The
    new objects make it possible to store information in efficient
    internal forms and avoid the constant translations to and from
    strings that occurred with the old interpreter.  We have not yet
    converted all of Tcl to take full advantage of the compiler and
    objects and have not converted any of Tk yet, but even so you
    should see speedups of 2-3x on many programs and you may see
    speedups as much as 10-20x in some cases (such as code that
    manipulates long lists).  Future releases should achieve even
    greater speedups.  The compiler introduces only a few minor changes
    at the level of Tcl scripts, but it introduces many new C APIs for
    managing objects.  See, for example, the manual entries doc/*Obj*.3.

    2. Namespaces.  There is a new namespace mechanism based on the
    namespace implementation by Michael McLennan of Lucent Technologies.
    This includes new "namespace" and "variable" commands.  There are
    many new C APIs associated with namespaces, but they will not be
    exported until Tcl 8.1.  Note: the syntax of the namespace command
    has been changed slightly since the b1 release.  See the changes
    file for details.

    3. Binary I/O.  The new object system in Tcl 8.0 supports binary
    strings (internally, strings are counted in addition to being null
    terminated).  There is a new "binary" command for inserting and
    extracting data to/from binary strings.  Commands such as "puts",
    "gets", and "read" commands now operate correctly on binary data. 
    There is a new variable tcl_platform(byteOrder) to identify the
    native byte order for the current host.

    4. Random numbers.  The "expr" command now contains a random number
    generator, which can be accessed via the "rand()" and "srand()" math
    functions.

    5. Safe-Tcl enhancements.  There is a new "hidden command"
    mechanism, implemented with the Tcl commands "interp hide", "interp
    expose", "interp invokehidden", and "interp hidden" and the C APIs
    Tcl_HideCommand and Tcl_ExposeCommand.  There is now support for
    safe packages and extension loading, including new library
    procedures such as safe::interpCreate (see the manual entry safe.n
    for details).

    6. There is a new package "registry" available under Windows for
    accessing the Windows registry.

    7. There is a new command "file attributes" for getting and setting
    things like permissions and owner.  There is also a new command
    "file nativename" for getting back the platform-specific name for a
    particular file.

    8. There is a new "fcopy" command to copy data between channels. 
    This replaces and improves upon the not-so-secret unsupported old
    command "unsupported0".

    9. There is a new package "http" for doing GET, POST, and HEAD
    requests via the HTTP/1.0 protocol.  See the manual entry http.n
    for details.

    10. There are new library procedures for finding word breaks in
    strings.  See the manual entry library.n for details.

    11. There are new C APIs Tcl_Finalize (for cleaning up before
    unloading the Tcl DLL) and Tcl_Ungets for pushing bytes back into a
    channel's input buffer.

    12. Tcl now supports serial I/O devices on Windows and Unix, with a
    new fconfigure -mode option.  The Windows driver does not yet
    support event-driven I/O.

    13. The lsort command has new options -dictionary and -index.  The
    -index option allows for very rapid sorting based on an element
    of a list.

    14. The event notifier has been completely rewritten (again).  It
    should now allow Tcl to use an external event loop (like Motif's)
    when it is embedded in other applications.  No script-level
    interfaces have changed, but many of the C APIs have.

Tcl 8.0 introduces the following incompatibilities that may affect Tcl
scripts that worked under Tcl 7.6 and earlier releases:

    1. Variable and command names may not include the character sequence
    "::" anymore: this sequence is now used as a namespace separator.

    2. The semantics of some Tcl commands have been changed slightly to
    maximize performance under the compiler.  These incompatibilities
    are documented on the Web so that we can keep the list up-to-date.
    See the URL http://www.sunlabs.com/research/tcl/compiler.html.

    3. 2-digit years are now parsed differently by the "clock" command
    to handle year 2000 issues better (years 00-38 are treated as
    2000-2038 instead of 1900-1938).

    4. The old Macintosh commands "cp", "mkdir", "mv", "rm", and "rmdir"
    are no longer supported; all of these features are now available on
    all platforms via the "file" command.

    5. The variable tcl_precision is now shared between interpreters
    and defaults to 12 digits instead of 6; safe interpreters cannot
    modify tcl_precision.  The new object system in Tcl 8.0 causes
    floating-to-string conversions (and the associated rounding) to
    occur much less often than in Tcl 7.6, which can sometimes cause
    behavioral changes.

    6. The C APIs associated with the notifier have changed substantially.

    7. The procedures Tcl_CreateModalTimeout and Tcl_DeleteModalTimeout
    have been removed.

    8. Tcl_CreateFileHandler and Tcl_DeleteFileHandler now take Unix
    fd's and are only supported on the Unix platform

    9. The C APIs for creating channel drivers have changed as part of
    the new notifier implementation.  The Tcl_File interfaces have been
    removed.  Tcl_GetChannelFile has been replaced with
    Tcl_GetChannelHandle.  Tcl_MakeFileChannel now takes a platform-
    specific file handle.  Tcl_DriverGetOptionProc procedures now take
    an additional interp argument.

5. Tcl newsgroup
-----------------

There is a network news group "comp.lang.tcl" intended for the exchange
of information about Tcl, Tk, and related applications.  Feel free to use
the newsgroup both for general information questions and for bug reports.
We read the newsgroup and will attempt to fix bugs and problems reported
to it.

When using comp.lang.tcl, please be sure that your e-mail return address
is correctly set in your postings.  This allows people to respond directly
to you, rather than the entire newsgroup, for answers that are not of
general interest.  A bad e-mail return address may prevent you from
getting answers to your questions.  You may have to reconfigure your news
reading software to ensure that it is supplying valid e-mail addresses.

6. Tcl contributed archive
--------------------------

Many people have created exciting packages and applications based on Tcl
and/or Tk and made them freely available to the Tcl community.  An archive
of these contributions is kept on the machine ftp.neosoft.com.  You
can access the archive using anonymous FTP;  the Tcl contributed archive is
in the directory "/pub/tcl".  The archive also contains several FAQ
("frequently asked questions") documents that provide solutions to problems
that are commonly encountered by TCL newcomers.

7. Tcl Resource Center
----------------------
Visit http://www.scritics.com/resource/ to see an annotated index of
many Tcl resources available on the World Wide Web.  This includes
papers, books, and FAQs, as well as extensions, applications, binary
releases, and patches.  You can contribute patches by sending them
to <[email protected]>.  You can also recommend more URLs for the
resource center using the forms labeled "Add a Resource".

8. Mailing lists
----------------

A couple of  Mailing List have been set up to discuss Macintosh or
Windows related Tcl issues.  In order to use these Mailing Lists you
must have access to the internet.  To subscribe send a message to:
	
	[email protected]
	[email protected]
	
In the body of the message (the subject will be ignored) put:
	
	subscribe mactcl Joe Blow
	
Replacing Joe Blow with your real name, of course.  (Use wintcl
instead of mactcl if your interested in the Windows list.)  If you
would just like to receive more information about the list without
subscribing put the line:

	information mactcl
	
in the body instead (or wintcl).

9. Support and bug fixes
------------------------

We're very interested in receiving bug reports and suggestions for
improvements.  We prefer that you send this information to the
comp.lang.tcl newsgroup rather than to any of us at Scriptics.  We'll see
anything on comp.lang.tcl, and in addition someone else who reads 
comp.lang.tcl may be able to offer a solution.  The normal turn-around
time for bugs is 3-6 weeks.  Enhancements may take longer and may not
happen at all unless there is widespread support for them (we're
trying to slow the rate at which Tcl turns into a kitchen sink).  It's
very difficult to make incompatible changes to Tcl at this point, due
to the size of the installed base.

When reporting bugs, please provide a short tclsh script that we can
use to reproduce the bug.  Make sure that the script runs with a
bare-bones tclsh and doesn't depend on any extensions or other
programs, particularly those that exist only at your site.  Also,
please include three additional pieces of information with the
script:
    (a) how do we use the script to make the problem happen (e.g.
	what things do we click on, in what order)?
    (b) what happens when you do these things (presumably this is
        undesirable)?
    (c) what did you expect to happen instead?

The Tcl community is too large for us to provide much individual
support for users.  If you need help we suggest that you post questions
to comp.lang.tcl.  We read the newsgroup and will attempt to answer
esoteric questions for which no-one else is likely to know the answer.
In addition, Tcl support and training are available commercially from
Scriptics ([email protected]), NeoSoft ([email protected]),
Computerized Processes Unlimited ([email protected]),
and Data Kinetics ([email protected]).

10. Tcl version numbers
----------------------

You can test the current version of Tcl by examining the
tcl_version and tcl_patchLevel variables.  The tcl_patchLevel
variable follows the naming rules outlined below (e.g., 8.0.4).
The tcl_version just has the major.minor numbers in it (e.g., 8.0)

Each Tcl release is identified by two numbers separated by a dot, e.g.
6.7 or 7.0.  If a new release contains changes that are likely to break
existing C code or Tcl scripts then the major release number increments
and the minor number resets to zero: 6.0, 7.0, etc.  If a new release
contains only bug fixes and compatible changes, then the minor number
increments without changing the major number, e.g. 7.1, 7.2, etc.  If
you have C code or Tcl scripts that work with release X.Y, then they
should also work with any release X.Z as long as Z > Y.

Alpha and beta releases have an additional suffix of the form a2 or b1.
For example, Tcl 7.0b1 is the first beta release of Tcl version 7.0,
Tcl 7.0b2 is the second beta release, and so on.  A beta release is an
initial version of a new release, used to fix bugs and bad features before
declaring the release stable.  An alpha release is like a beta release,
except it's likely to need even more work before it's "ready for prime
time".  New releases are normally preceded by one or more alpha and beta
releases.  We hope that lots of people will try out the alpha and beta
releases and report problems.  We'll make new alpha/beta releases to fix
the problems, until eventually there is a beta release that appears to
be stable.  Once this occurs we'll make the final release.

We can't promise to maintain compatibility among alpha and beta releases.
For example, release 7.1b2 may not be backward compatible with 7.1b1, even
though the final 7.1 release will be backward compatible with 7.0.  This
allows us to change new features as we find problems during beta testing.
We'll try to minimize incompatibilities between beta releases, but if
a major problem turns up then we'll fix it even if it introduces an
incompatibility.  Once the official release is made then there won't
be any more incompatibilities until the next release with a new major
version number.

(Note: This compatibility is true for Tcl scripts, but historically the Tcl
C APIs have changed enough between releases that you may need to work a bit to
upgrade extensions.)

Patch releases have a suffix such as p1 or p2.  These releases contain
bug fixes only.  A patch release (e.g Tcl 7.6p2) should be completely
compatible with the base release from which it is derived (e.g. Tcl
7.6), and you should normally use the highest available patch release.

As of 8.0.3, the patch releases use a second . instead of 'p'.  So,
the 8.0 release went to 8.0p1, 8.0p2, 8.0.3, 8.0.4, and 8.0.5.  The
alphas and betas will still use the 'a' and 'b' letters in their
tcl_patchLevel.

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































































































































































































































































































































































































































































































































Deleted changes.

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
Recent user-visible changes to Tcl:

RCS: @(#) $Id: changes,v 1.41 1999/02/03 19:12:25 stanton Exp $

1. No more [command1] [command2] construct for grouping multiple
commands on a single command line.

2. Semi-colon now available for grouping commands on a line.

3. For a command to span multiple lines, must now use backslash-return
at the end of each line but the last.

4. "Var" command has been changed to "set".

5. Double-quotes now available as an argument grouping character.

6. "Return" may be used at top-level.

7. More backslash sequences available now.  In particular, backslash-newline
may be used to join lines in command files.

8. New or modified built-in commands:  case, return, for, glob, info,
print, return, set, source, string, uplevel.

9. After an error, the variable "errorInfo" is filled with a stack
trace showing what was being executed when the error occurred.

10. Command abbreviations are accepted when parsing commands, but
are not recommended except for purely-interactive commands.

11. $, set, and expr all complain now if a non-existent variable is
referenced.

12. History facilities exist now.  See Tcl.man and Tcl_RecordAndEval.man.

13. Changed to distinguish between empty variables and those that don't
exist at all.  Interfaces to Tcl_GetVar and Tcl_ParseVar have changed
(NULL return value is now possible).  *** POTENTIAL INCOMPATIBILITY ***

14. Changed meaning of "level" argument to "uplevel" command (1 now means
"go up one level", not "go to level 1"; "#1" means "go to level 1").
*** POTENTIAL INCOMPATIBILITY ***

15. 3/19/90 Added "info exists" option to see if variable exists.

16. 3/19/90 Added "noAbbrev" variable to prohibit command abbreviations.

17. 3/19/90 Added extra errorInfo option to "error" command.

18. 3/21/90 Double-quotes now only affect space:  command, variable,
and backslash substitutions still occur inside double-quotes.
*** POTENTIAL INCOMPATIBILITY ***

19. 3/21/90 Added support for \r.

20. 3/21/90 List, concat, eval, and glob commands all expect at least
one argument now.  *** POTENTIAL INCOMPATIBILITY ***

21. 3/22/90 Added "?:" operators to expressions.

22. 3/25/90 Fixed bug in Tcl_Result that caused memory to get trashed.

------------------- Released version 3.1 ---------------------

23. 3/29/90 Fixed bug that caused "file a.b/c ext" to return ".b/c".

24. 3/29/90 Semi-colon is not treated specially when enclosed in
double-quotes.

------------------- Released version 3.2 ---------------------

25. 4/16/90 Rewrote "exec" not to use select or signals anymore.
Should be more Sys-V compatible, and no slower in the normal case.

26. 4/18/90 Rewrote "glob" to eliminate GNU code (there's no GNU code
left in Tcl, now), and added Tcl_TildeSubst procedure.  Added automatic
tilde-substitution in many commands, including "glob".

------------------- Released version 3.3 ---------------------

27. 7/11/90 Added "Tcl_AppendResult" procedure.

28. 7/20/90 "History" with no options now defaults to "history info"
rather than to "history redo".  Although this is a backward incompatibility,
it should only be used interactively and thus shouldn't present any
compatibility problems with scripts.

29. 7/20/90 Added "Tcl_GetInteger", "Tcl_GetDouble", and "Tcl_GetBoolean"
procedures.

30. 7/22/90 Removed "Tcl_WatchInterp" procedure:  doesn't seem to be
necessary, since the same effect can be achieved with the deletion
callbacks on individual commands.  *** POTENTIAL INCOMPATIBILITY ***

31. 7/23/90 Added variable tracing:  Tcl_TraceVar, Tcl_UnTraceVar,
and Tcl_VarTraceInfo procedures, "trace" command.

32. 8/9/90 Mailed out list of all bug fixes since 3.3 release.

33. 8/29/90 Fixed bugs in Tcl_Merge relating to backslashes and
semi-colons.  Mailed out patch.

34. 9/3/90 Fixed bug in tclBasic.c: quotes weren't quoting ]'s.
Mailed out patch.

35. 9/19/90 Rewrote exec to always use files both for input and
output to the process.  The old pipe-based version didn't work if
the exec'ed process forked a child and then exited:  Tcl waited
around for stdout to get closed, which didn't happen until the
grandchild exited.

36. 11/5/90 ERR_IN_PROGRESS flag wasn't being cleared soon enough
in Tcl_Eval, allowing error messages from different commands to
pile up in $errorInfo.  Fixed by re-arranging code in Tcl_Eval that
re-initializes result and ERR_IN_PROGRESS flag.  Didn't mail out
patch:  changes too complicated to describe.

37. 12/19/90 Added Tcl_VarEval procedure as a convenience for
assembling and executing Tcl commands.

38. 1/29/91 Fixed core leak in Tcl_AddErrorInfo.  Also changed procedure
and Tcl_Eval so that first call to Tcl_AddErrorInfo need not come from
Tcl_Eval.

----------------- Released version 5.0 with Tk ------------------

39. 4/3/91 Removed change bars from manual entries, leaving only those
that came after version 3.3 was released.

40. 5/17/91 Changed tests to conform to Mary Ann May-Pumphrey's approach.
 
41. 5/23/91 Massive revision to Tcl parser to simplify the implementation
of string and floating-point support in expressions.  Newlines inside
[] are now treated as command separators rather than word separators
(this makes newline treatment consistent throughout Tcl).
*** POTENTIAL INCOMPATIBILITY ***

42. 5/23/91 Massive rewrite of expression code to support floating-point
values and simple string comparisons.  The C interfaces to expression
routines have changed (Tcl_Expr is replaced by Tcl_ExprLong, Tcl_ExprDouble,
etc.), but all old Tcl expression strings should be accepted by the new
expression code.
*** POTENTIAL INCOMPATIBILITY ***

43. 5/23/91 Modified tclHistory.c to check for negative "keep" value.

44. 5/23/91 Modified Tcl_Backslash to handle backslash-newline.  It now
returns 0 to indicate that a backslash sequence should be replaced by
no character at all.
*** POTENTIAL INCOMPATIBILITY ***

45. 5/29/91 Modified to use ANSI C function prototypes.  Must set
"USE_ANSI" switch when compiling to get prototypes.

46. 5/29/91 Completed test suite by providing tests for all of the
built-in Tcl commands.

47. 5/29/91 Changed Tcl_Concat to eliminate leading and trailing
white-space in each of the things it concatenates and to ignore
elements that are empty or have only white space in them.  This
produces cleaner output from the "concat" command.
*** POTENTIAL INCOMPATIBILITY ***

48. 5/31/91 Changed "set" command and Tcl_SetVar procedure to return
new value of variable.

49. 6/1/91 Added "while" and "cd" commands.

50. 6/1/91 Changed "exec" to delete the last character of program
output if it is a newline.  In most cases this makes it easier to
process program-generated output.
*** POTENTIAL INCOMPATIBILITY ***

51. 6/1/91 Made sure that pointers are never used after freeing them.

52. 6/1/91 Fixed bug in TclWordEnd where it wasn't dealing with
[] inside quotes correctly.

53. 6/8/91 Fixed exec.test to accept return values of either 1 or
255 from "false" command.

54. 7/6/91 Massive overhaul of variable management.  Associative
arrays now available, along with "unset" command (and Tcl_UnsetVar
procedure).  Variable traces have been completely reworked:
interfaces different both from Tcl and C, and multiple traces may
exist on same variable.  Can no longer redefine existing local
variable to be global.  Calling sequences have changed slightly
for Tcl_GetVar and Tcl_SetVar ("global" is now "flags"). Tcl_SetVar
can fail and return a NULL result.  New forms of variable-manipulation
procedures:  Tcl_GetVar2, Tcl_SetVar2, etc.  Syntax of variable
$-notation changed to support array indexing.
*** POTENTIAL INCOMPATIBILITY ***

55. 7/6/91 Added new list-manipulation procedures:  Tcl_ScanElement,
Tcl_ConvertElement, Tcl_AppendElement.

56. 7/12/91 Created new procedure Tcl_EvalFile, which does most of the
work of the "source" command.

57. 7/20/91 Major reworking of "exec" command to allow pipelines,
more redirection, background.  Added new procedures Tcl_Fork,
Tcl_WaitPids, Tcl_DetachPids, and Tcl_CreatePipeline.  The old
"< input" notation has been replaced by "<< input" ("<" is for
redirection from a file).  Also handles error returns and abnormal
terminations (e.g. signals) differently.
*** POTENTIAL INCOMPATIBILITY ***

58. 7/21/91 Added "append" and "lappend" commands.

59. 7/22/91 Reworked error messages and manual entries to use
?x? as the notation for an optional argument x, instead of [x].  The
bracket notation was often confused with the use of brackets for
command substitution.  Also modified error messages to be more
consistent.

60. 7/23/91 Tcl_DeleteCommand now returns an indication of whether
or not the command actually existed, and the "rename" command uses
this information to return an error if an attempt is made to delete
a non-existent command.
*** POTENTIAL INCOMPATIBILITY ***

61. 7/25/91 Added new "errorCode" mechanism, along with procedures
Tcl_SetErrorCode, Tcl_UnixError, and Tcl_ResetResult.  Renamed
Tcl_Return to Tcl_SetResult, but left a #define for Tcl_Return to
avoid compatibility problems.

62. 7/26/91 Extended "case" command with alternate syntax where all
patterns and commands are together in a single list argument:  makes
it easier to write multi-line case statements.

63. 7/27/91 Changed "print" command to perform tilde-substitution on
the file name.

64. 7/27/91 Added "tolower", "toupper", "trim", "trimleft", and "trimright"
options to "string" command.

65. 7/29/91 Added "atime", "mtime", "size", and "stat" options to "file"
command.

66. 8/1/91 Added "split" and "join" commands.

67. 8/11/91 Added commands for file I/O, including "open", "close",
"read", "gets", "puts", "flush", "eof", "seek", and "tell".

68. 8/14/91 Switched to use a hash table for command lookups.  Command
abbreviations no longer have direct support in the Tcl interpreter, but
it should be possible to simulate them with the auto-load features
described below.  The "noAbbrev" variable is no longer used by Tcl.
*** POTENTIAL INCOMPATIBILITY ***

68.5 8/15/91 Added support for "unknown" command, which can be used to
complete abbreviations, auto-load library files, auto-exec shell
commands, etc.

69. 8/15/91 Added -nocomplain switch to "glob" command.

70. 8/20/91 Added "info library" option and TCL_LIBRARY #define.  Also
added "info script" option.

71. 8/20/91 Changed "file" command to take "option" argument as first
argument (before file name), for consistency with other Tcl commands.
*** POTENTIAL INCOMPATIBILITY ***

72. 8/20/91 Changed format of information in $errorInfo variable:
comments such as 
    ("while" body line 1)
are now on separate lines from commands being executed.
*** POTENTIAL INCOMPATIBILITY ***

73. 8/20/91 Changed Tcl_AppendResult so that it (eventually) frees
large buffers that it allocates.

74. 8/21/91 Added "linsert", "lreplace", "lsearch", and "lsort"
commands.

75. 8/28/91 Added "incr" and "exit" commands.

76. 8/30/91 Added "regexp" and "regsub" commands.

77. 9/4/91 Changed "dynamic" field in interpreters to "freeProc" (procedure
address).  This allows for alternative storage managers.
*** POTENTIAL INCOMPATIBILITY ***

78. 9/6/91 Added "index", "length", and "range" options to "string"
command.  Added "lindex", "llength", and "lrange" commands.

79. 9/8/91 Removed "index", "length", "print" and "range" commands.
"Print" is redundant with "puts", but less general, and the other
commands are replaced with the new commands described in change 78
above.
*** POTENTIAL INCOMPATIBILITY ***

80. 9/8/91 Changed history revision to occur even when history command
is nested;  needed in order to allow "history" to be invoked from
"unknown" procedure.

81. 9/13/91 Changed "panic" not to use vfprintf (it's uglier and less
general now, but makes it easier to run Tcl on systems that don't
have vfprintf).  Also changed "strerror" not to redeclare sys_errlist.

82. 9/19/91 Lots of changes to improve portability to different UNIX
systems, including addition of "config" script to adapt Tcl to the
configuration of the system it's being compiled on.

83. 9/22/91 Added "pwd" command.

84. 9/22/91 Renamed manual pages so that their filenames are no more
than 14 characters in length, moved to "doc" subdirectory.

85. 9/24/91 Redid manual entries so they contain the supplemental
macros that they need;  can just print with "troff -man" or "man"
now.

86. 9/26/91 Created initial version of script library, including
a version of "unknown" that does auto-loading, auto-execution, and
abbreviation expansion.  This library is used by tclTest
automatically.  See the "library" manual entry for details.

----------------- Released version 6.0, 9/26/91 ------------------

87. 9/30/91 Made "string tolower" and "string toupper" check case
before converting:  on some systems, "tolower" and "toupper" assume
that character already has particular case.

88. 9/30/91 Fixed bug in Tcl_SetResult:  wasn't always setting freeProc
correctly when called with NULL value.  This tended to cause memory
allocation errors later.

89. 10/3/91 Added "upvar" command.

90. 10/4/91 Changed "format" so that internally it converts %D to %ld,
%U to %lu, %O to %lo, and %F to %f.  This eliminates some compatibility
problems on some machines without affecting behavior.

91. 10/10/91 Fixed bug in "regsub" that caused core dumps with the -all
option when the last match wasn't at the end of the string.

92. 10/17/91 Fixed problems with backslash sequences:  \r support was
incomplete and \f and \v weren't supported at all.

93. 10/24/91 Added Tcl_InitHistory procedure.

94. 10/24/91 Changed "regexp" to store "-1 -1" in subMatchVars that
don't match, rather than returning an error.

95. 10/27/91 Modified "regexp" to return actual strings in matchVar
and subMatchVars instead of indices.  Added "-indices" switch to cause
indices to be returned.
*** POTENTIAL INCOMPATIBILITY ***

96. 10/27/91 Fixed bug in "scan" where it used hardwired constants for
sizes of floats and doubles instead of using "sizeof".

97. 10/31/91 Fixed bug in tclParse.c where parse-related error messages
weren't being storage-managed correctly, causing spurious free's.

98. 10/31/91 Form feed and vertical tab characters are now considered
to be space characters by the parser.

99. 10/31/91 Added TCL_LEAVE_ERR_MSG flag to procedures like Tcl_SetVar.

100. 11/7/91 Fixed bug in "case" where "in" argument couldn't be omitted
if all case branches were embedded in a single list.

101. 11/7/91 Switched to use "pid_t" and "uid_t" and other official
POSIC types and function prototypes.

----------------- Released version 6.1, 11/7/91 ------------------

102. 12/2/91 Modified Tcl_ScanElement and Tcl_ConvertElement in several
ways.  First, allowed caller to request that only backslashes be used
(no braces).  Second, made Tcl_ConvertElement more aggressive in using
backslashes for braces and quotes.

103. 12/5/91 Added "type", "lstat", and "readlink" options to "file"
command, plus added new "type" element to output of "stat" and "lstat"
options.

104. 12/10/91 Manual entries had first lines that caused "man" program
to try weird preprocessor.  Added blank comment lines to fix problem.

105. 12/16/91 Fixed a few bugs in auto_mkindex proc:  wasn't handling
errors properly, and hadn't been upgraded for new "regexp" syntax.

106. 1/2/92 Fixed bug in "file" command where it didn't properly handle
a file names containing tildes where the indicated user doesn't exist.

107. 1/2/92 Fixed lots of cases in tclUnixStr.c where two different
errno symbols (e.g. EWOULDBLOCK and EAGAIN) have the same number;  Tcl
will only use one of them.

108. 1/2/92 Lots of changes to configuration script to handle many more
systems more gracefully.  E.g. should now detect the bogus strtoul that
comes with AIX and substitute Tcl's own version instead.

----------------- Released version 6.2, 1/10/92 ------------------

109. 1/20/92 Config didn't have code to actually use "uid_t" variable
to set TCL_UIT_T #define.

110. 2/10/92 Tcl_Eval didn't properly reset "numLevels" variable when
too-deep recursion occurred.

111. 2/29/92 Added "on" and "off" to keywords accepted by Tcl_GetBoolean.

112. 3/19/92 Config wasn't installing default version of strtod.c for
systems that don't have one in libc.a.

113. 3/23/92 Fixed bug in tclExpr.c where numbers with leading "."s,
like 0.75, couldn't be properly substituted into expressions with
variable or command substitution.

114. 3/25/92 Fixed bug in tclUnixAZ.c where "gets" command wasn't
checking to make sure that it was able to write the variable OK.

115. 4/16/92 Fixed bug in tclUnixAZ.c where "read" command didn't
compute file size right for device files.

116. 4/23/92 Fixed but in tclCmdMZ.c where "trace vinfo" was overwriting
the trace command.

----------------- Released version 6.3, 5/1/92 ------------------

117. 5/1/92 Added Tcl_GlobalEval.

118. 6/1/92 Changed auto-load facility to source files at global level.

119. 6/8/92 Tcl_ParseVar wasn't always setting termPtr after errors, which
sometimes caused core dumps.

120. 6/21/92 Fixed bug in initialization of regexp pattern cache.  This
bug caused segmentation violations in regexp commands under some conditions.

121. 6/22/92 Changed implementation of "glob" command to eliminate
trailing slashes on directory names:  they confuse some systems.  There
shouldn't be any user-visible changes in functionality except for names
in error messages not having trailing slashes.

122. 7/2/92 Fixed bug that caused 'string match ** ""' to return 0.

123. 7/2/92 Fixed bug in Tcl_CreateCmdBuf where it wasn't initializing
the buffer to an empty string.

124. 7/6/92 Fixed bug in "case" command where it used NULL pattern string
after errors in the "default" clause.

125. 7/25/92 Speeded up auto_load procedure:  don't reread all the index
files unless the path has changed.

126. 8/3/92 Changed tclUnix.h to define MAXPATHLEN from PATH_MAX, not
_POSIX_PATH_MAX.

----------------- Released version 6.4, 8/7/92 ------------------

127. 8/10/92 Changed tclBasic.c so that comment lines can be continued by
putting a backslash before the newline.

128. 8/21/92 Modified "unknown" to allow the source-ing of a file for
an auto-load to trigger other nested auto-loads, as long as there isn't
any recursion on the same command name.

129. 8/25/92 Modified "format" command to allow " " and "+" flags, and
allow flags in any order.

130. 9/14/92 Modified Tcl_ParseVar so that it doesn't actually attempt
to look up the variable if "noEval" mode is in effect in the interpreter
(it just parses the name).  This avoids the errors that used to occur
in statements like "expr {[info exists foo] && $foo}".

131. 9/14/92 Fixed bug in "uplevel" command where it didn't output the
correct error message if a level was specified but no command.

132. 9/14/92 Renamed manual entries to have extensions like .3 and .n,
and added "install" target to Makefile.

133. 9/18/92 Modified "unknown" command to emulate !!, !<num>, and
^<old>^<new> csh history substitutions.

134. 9/21/92 Made the config script cleverer about figuring out which
switches to pass to "nm".

135. 9/23/92 Fixed tclVar.c to be sure to copy flags when growing variables.
Used to forget about traces in progress and make extra recursive calls
on trace procs.

136. 9/28/92 Fixed bug in auto_reset where it was unsetting variables
that might not exist.

137. 10/7/92 Changed "parray" library procedure to print any array
accessible to caller, local or global.

138. 10/15/92 Fixed bug where propagation of new environment variable
values among interpreters took N! time if there exist N interpreters.

139. 10/16/92 Changed auto_reset procedure so that it also deletes any
existing procedures that are in the auto_load index (the assumption is
that they should be re-loaded to get the latest versions).

140. 10/21/92 Fixed bug that caused lists to be incorrectly generated
for elements that contained backslash-newline sequences.

141. 12/9/92 Added support for TCL_LIBRARY environment variable:  use
it as library location if it's present.

142. 12/9/92 Added "info complete" command, Tcl_CommandComplete procedure.

143. 12/16/92 Changed the Makefile to check to make sure "config" has been
run (can't run config directly from the Makefile because it modifies the
Makefile;  thus make has to be run again after running config).

----------------- Released version 6.5, 12/17/92 ------------------

144. 12/21/92 Changed config to look in several places for libc file.

145. 12/23/92 Added "elseif" support to if.  Also, "then", "else", and
"elseif" may no longer be abbreviated.
*** POTENTIAL INCOMPATIBILITY ***

146. 12/28/92 Changed "puts" and "read" to support initial "-nonewline"
switch instead of additional "nonewline" argument.  The old form is
still supported, but it is discouraged and is no longer documented.
Also changed "puts" to make the file argument default to stdout: e.g.
"puts foo" will print foo on standard output.

147. 1/6/93 Fixed bug whereby backslash-newline wasn't working when
typed interactively, or in "info complete".

148. 1/22/93 Fixed bugs in "lreplace" and "linsert" where close
quotes were being lost from last element before replacement or
insertion.

149. 1/29/93 Fixed bug in Tcl_AssembleCmd where it wasn't requiring
a newline at the end of a line before considering a command to be
complete.  The bug caused some very long lines in script files to
be processed as multiple separate commands.

150. 1/29/93 Various changes in Makefile to add more configuration
options, simplify installation, fix bugs (e.g. don't use -f switch
for cp), etc.

151. 1/29/93 Changed "name1" and "name2" identifiers to "part1" and
"part2" to avoid name conflicts with stupid C++ implementations that
use "name1" and "name2" in a reserved way.

152. 2/1/93 Added "putenv" procedure to replace the standard system
version so that it will work correctly with Tcl's environment handling.

----------------- Released version 6.6, 2/5/93 ------------------

153. 2/10/93 Fixed bugs in config script:  missing "endif" in libc loop,
and tried to use strncasecmp.c instead of strcasecmp.c.

154. 2/10/93 Makefile improvements:  added RANLIB variable for easier
Sys-V configuration, added SHELL variable for SGI systems.

----------------- Released version 6.7, 2/11/93 ------------------

153. 2/6/93 Changes in backslash processing:
    - \Cx, \Mx, \CMx, \e sequences no longer special
    - \<newline> also eats up any space after the newline, replacing
      the whole sequence with a single space character
    - Hex sequences like \x24 are now supported, along with ANSI C's \a.
    - "format" no longer does backslash processing on its format string
    - there is no longer any special meaning to a 0 return value from
      Tcl_Backslash
    - unknown backslash sequences, like (e.g. \*), are replaced with
      the following character (e.g. *), instead of just treating the
      backslash as an ordinary character.
*** POTENTIAL INCOMPATIBILITY ***

154. 2/6/93 Updated all copyright notices.  The meaning hasn't changed
at all but the wording does a better job of protecting U.C. from
liability (according to U.C. lawyers, anyway).

155. 2/6/93 Changed "regsub" so that it overwrites the result variable
in all cases, even if there is no match.
*** POTENTIAL INCOMPATIBILITY ***

156. 2/8/93 Added support for XPG3 %n$ conversion specifiers to "format"
command.

157. 2/17/93 Fixed bug in Tcl_Eval where errors due to infinite
recursion could result in core dumps.

158. 2/17/93 Improved the auto-load mechanism to deal gracefully (i.e.
return an error) with a situation where a library file that supposedly
defines a procedure doesn't actually define it.

159. 2/17/93 Renamed Tcl_UnixError procedure to Tcl_PosixError, and
changed errorCode variable usage to use POSIX as keyword instead of
UNIX.
*** POTENTIAL INCOMPATIBILITY ***

160. 2/19/93 Changes to exec and process control:
    - Added support for >>, >&, >>&, |&, <@, >@, and >&@ forms of redirection.
    - When exec puts processes into background, it returns a list of
      their pids as result.
    - Added support for <file, >file, etc. (i.e. no space between
      ">" and file name.
    - Added -keepnewline option.
    - Deleted Tcl_Fork and Tcl_WaitPids procedures (just use fork and
      waitpid instead).
    - Added waitpid compatibility procedure for systems that don't have
      it.
    - Added Tcl_ReapDetachedProcs procedure.
    - Changed "exec" to return an error if there is stderr output, even
      if the command returns a 0 exit status (it's always been documented
      this way, but the implementation wasn't correct).
    - If a process returns a non-zero exit status but doesn't generate
      any diagnostic output, then Tcl generates an error message for it.
*** POTENTIAL INCOMPATIBILITY ***

161. 2/25/93 Fixed two memory-management problems having to do with
managing the old result during variable trace callbacks.

162. 3/1/93 Added dynamic string library:  Tcl_DStringInit, Tcl_DStringAppend,
Tcl_DStringFree, Tcl_DStringResult, etc.

163. 3/1/93 Modified glob command to only return the names of files that
exist, and to only return names ending in "/" if the file is a directory.
*** POTENTIAL INCOMPATIBILITY ***

164. 3/19/93 Modified not to use system calls like "read" directly,
but instead to use special Tcl procedures that retry automatically
if interrupted by signals.

165. 4/3/93 Eliminated "noSep" argument to Tcl_AppendElement, plus
TCL_NO_SPACE flag for Tcl_SetVar and Tcl_SetVar2.
*** POTENTIAL INCOMPATIBILITY ***

166. 4/3/93 Eliminated "flags" and "termPtr" arguments to Tcl_Eval.
*** POTENTIAL INCOMPATIBILITY ***

167. 4/3/93 Changes to expressions:
    - The "expr" command now accepts multiple arguments, which are
      concatenated together with space separators.
    - Integers aren't automatically promoted to floating-point if they
      overflow the word size:  errors are generated instead.
    - Tcl can now handle "NaN" and other special values if the underlying
      library procedures handle them.
    - When printing floating-point numbers, Tcl ensures that there is a "."
      or "e" in the number, so it can't be treated as an integer accidentally.
      The procedure Tcl_PrintDouble is available to provide this function
      in other contexts.  Also, the variable "tcl_precision" can be used
      to set the precision for printing (must be a decimal number giving
      digits of precision).
    - Expressions now support transcendental and other functions, e.g. sin,
      acos, hypot, ceil, and round.  Can add new math functions with
      Tcl_CreateMathFunc().
    - Boolean expressions can now have any of the string values accepted
      by Tcl_GetBoolean, such as "yes" or "no".
*** POTENTIAL INCOMPATIBILITY ***

168. 4/5/93 Changed Tcl_UnsetVar and Tcl_UnsetVar2 to return TCL_OK
or TCL_ERROR instead of 0 or -1.
*** POTENTIAL INCOMPATIBILITY ***

169. 4/5/93 Eliminated Tcl_CmdBuf structure and associated procedures;
can use Tcl_DStrings instead.
*** POTENTIAL INCOMPATIBILITY ***

170. 4/8/93 Changed interface to Tcl_TildeSubst to use a dynamic
string for buffer space.  This makes the procedure re-entrant and
thread-safe, whereas it wasn't before.
*** POTENTIAL INCOMPATIBILITY ***

171. 4/14/93 Eliminated tclHash.h, and moved everything from it to
tcl.h
*** POTENTIAL INCOMPATIBILITY ***

172. 4/15/93 Eliminated Tcl_InitHistory, made "history" command always
be part of interpreter.
*** POTENTIAL INCOMPATIBILITY ***

173. 4/16/93 Modified "file" command so that "readable" option always
exists, even on machines that don't support symbolic links (always returns
same error as if the file wasn't a symbolic link).

174. 4/26/93 Fixed bugs in "regsub" where ^ patterns didn't get handled
right (pretended not to match when it really did, and looped infinitely
if -all was specified).

175. 4/29/93 Various improvements in the handling of variables:
    - Can create variables and array elements during a read trace.
    - Can delete variables during traces (note: unset traces will be
      invoked when this happens).
    - Can upvar to array elements.
    - Can retarget an upvar to another variable by re-issuing the
      upvar command with a different "other" variable.

176. 5/3/93 Added Tcl_GetCommandInfo, which returns info about a Tcl
command such as whether it exists and its ClientData.  Also added
Tcl_SetCommandInfo, which allows any of this information to be modified
and also allows a command's delete procedure to have a different
ClientData value than its command procedure.

177. 5/5/93 Added Tcl_RegExpMatch procedure.

178. 5/6/93 Fixed bug in "scan" where it didn't properly handle
%% conversion specifiers.  Also changed "scan" to use Tcl_PrintDouble
for printing real values.

179. 5/7/93 Added "-exact", "-glob", and "-regexp" options to "lsearch"
command to allow different kinds of pattern matching.

180. 5/7/93 Added many new switches to "lsort" to control the sorting
process: "-ascii", "-integer", "-real", "-command", "-increasing",
and "-decreasing".

181. 5/10/93 Changes to file I/O:
    - Modified "open" command to support a list of POSIX access flags
      like {WRONLY CREAT TRUNC} in addition to current fopen-style
      access modes.  Also added "permissions" argument to set permissions
      of newly-created files.
    - Fixed Scott Bolte's bug (can close stdin etc. in application and
      then re-open them with Tcl commands).
    - Exported access to Tcl's file table with new procedures Tcl_EnterFile
      and Tcl_GetOpenFile.

182. 5/15/93 Added new "pid" command, which can be used to retrieve
either the current process id or a list of the process ids in a
pipeline opened with "open |..."

183. 6/3/93 Changed to use GNU autoconfig for configuration instead of
the home-brew "config" script.  Also made many other configuration-related
changes, such as using <unistd.h> instead of explicitly declaring system
calls in tclUnix.h.

184. 6/4/93 Fixed bug where core-dumps could occur if a procedure
redefined itself (the memory for the procedure's body could get
reallocated in the middle of evaluating the body);  implemented
simple reference count mechanism.

185. 6/5/93 Changed tclIndex file format in two ways:  (a) it's now
eval-ed instead of parsed, which makes it 3-4x faster; (b) the entries
in auto_index are now commands to evaluate, which allows commands to
be loaded in different ways such as dynamic-loading of C code.  The
old tclIndex file format is still supported.

186. 6/7/93 Eliminated tclTest program, added new "tclsh" program
that is more like wish (allows script files to be invoked automatically
using "#!/usr/local/bin/tclsh", makes arguments available to script,
etc.).  Added support for Tcl_AppInit plus default version;  this
allows new Tcl applications to be created without modifying the
main program for tclsh.

187. 6/7/93 Fixed bug in TclWordEnd that kept backslash-newline from
working correctly in some cases during interactive input.

188. 6/9/93 Added Tcl_LinkVar and related procedures, which automatically
keep a Tcl variable in sync with a C variable.

189. 6/16/93 Increased maximum nesting depth from 100 to 1000.

190. 6/16/93 Modified "trace var" command so that error messages from
within traces are returned properly as the result of the variable
access, instead of the generic "access disallowed by trace command"
message.

191. 6/16/93 Added Tcl_CallWhenDeleted to provide callbacks when an
interpreter is deleted (same functionality as Tcl_WatchInterp, which
used to exist in versions before 6.0).

193. 6/16/93 Added "-code" argument to "return" command;  it's there
primarily for completeness, so that procedures implementing control
constructs can reflect exceptional conditions back to their callers.

194. 6/16/93 Split up Tcl.n to make separate manual entries for each
Tcl command.  Tcl.n now contains a summary of the language syntax.

195. 6/17/93 Added new "switch" command to replace "case": allows
alternate forms of pattern matching (exact, glob, regexp), replaces
pattern lists with single patterns (but you can use "-" bodies to
share one body among several patterns), eliminates "in" noise word.
"Case" command is now obsolete.

196. 6/17/93 Changed the "exec", "glob", "regexp", and "regsub" commands
to include a "--" switch.  All initial arguments starting with "-" are now
treated as switches unless a "--" switch is present to end the list.
*** POTENTIAL INCOMPATIBILITY ***

197. 6/17/93 Changed auto-exec so that the subprocess gets stdin, stdout,
and stderr from the parent.  This allows truly interactive sub-processes
(e.g. vi) to be auto-exec'ed from a tcl shell command line.

198. 6/18/93 Added patchlevel.h, for use in coordinating future patch
releases, and also added "info patchlevel" command to make the patch
level available to Tcl scripts.

199. 6/19/93 Modified "glob" command so that a leading "//" in a name
gets left as is (this is needed for systems like Apollos where "//" is
the super-root;  Tcl used to collapse the two slashes into a single
slash).

200. 7/7/93 Added Tcl_SetRecursionLimit procedure so that the maximum
allowable nesting depth can be controlled for an interpreter from C.

----------------- Released version 7.0 Beta 1, 7/9/93 ------------------

201. 7/12/93 Modified Tcl_GetInt and tclExpr.c so that full-precision
unsigned integers can be specified without overflow errors.

202. 7/12/93 Configuration changes:  eliminate leading blank line in
configure script;  provide separate targets in Makefile for installing
binary and non-binary information; check for size_t and a few other
potentially missing typedefs; don't put tclAppInit.o into libtcl.a;
better checks for matherr support.

203. 7/14/93 Changed tclExpr.c to check the termination pointer before
errno after strtod calls, to avoid problems with some versions of
strtod that set errno in unexpected ways.

204. 7/16/93 Changed "scan" command to be more ANSI-conformant:
eliminated %F, %D, etc., added code to ignore "l", "h", and "L"
modifiers but always convert %e, %f, and %g with implicit "l";
also added support for %u and %i.  Also changed "format" command
to eliminate %D, %U, %O, and add %i.
*** POTENTIAL INCOMPATIBILITY ***

205. 7/17/93 Changed "uplevel" and "upvar" so that they can be used
from global level to global level:  this used to generate an error.

206. 7/19/93 Renamed "setenv", "putenv", and "unsetenv" procedures
to avoid conflicts with system procedures with the same names.  If
you want Tcl's procedures to override the system procedures, do it
in the Makefile (instructions are in the Makefile).
*** POTENTIAL INCOMPATIBILITY ***

----------------- Released version 7.0 Beta 2, 7/21/93 ------------------

207. 7/21/93 Fixed bug in tclVar.c where freed memory was accidentally
used if a procedure returned an element of a local array.

208. 7/22/93 Fixed bug in "unknown" where it didn't properly handle
errors occurring in the "auto_load" procedure, leaving its state
inconsistent.

209. 7/23/93 Changed exec's ">2" redirection operator to "2>" for
consistency with sh.  This is incompatible with earlier beta releases
of 7.0 but not with pre-7.0 releases, which didn't support either
operator.

210. 7/28/93 Changed backslash-newline handling so that the resulting
space character *is* treated as a word separator unless the backslash
sequence is in quotes or braces.  This is incompatible with 7.0b1
and 7.0b2 but is more compatible with pre-7.0 versions that the b1
and b2 releases were.

211. 7/28/93 Eliminated Tcl_LinkedVarWritable, added TCL_LINK_READ_ONLY to
Tcl_LinkVar to accomplish same purpose.  This change is incompatible
with earlier beta releases, but not with releases before Tcl 7.0.

212. 7/29/93 Renamed regexp C functions so they won't clash with POSIX
regexp functions that use the same name.

213. 8/3/93 Added "-errorinfo" and "-errorcode" options to "return"
command: these allow for much better handling of the errorInfo
and errorCode variables in some cases.

214. 8/12/93 Changed "expr" so that % always returns a remainder with
the same sign as the divisor and absolute value smaller than the
divisor.

215. 8/14/93 Turned off auto-exec in "unknown" unless the command
was typed interactively.  This means you must use "exec" when
invoking subprocesses, unless it's a command that's typed interactively.
*** POTENTIAL INCOMPATIBILITY ***

216. 8/14/93 Added support for tcl_prompt1 and tcl_prompt2 variables
to tclMain.c:  makes prompts user-settable.

217. 8/14/93 Added asynchronous handlers (Tcl_AsyncCreate etc.) so
that signals can be taken cleanly by Tcl applications.

218. 8/16/93 Moved information about open files from the interpreter
structure to global variables so that a file can be opened in one
interpreter and read or written in another.

219. 8/16/93 Removed ENV_FLAGS from Makefile, so that there's no
official support for overriding setenv, unsetenv, and putenv.

220. 8/20/93 Various configuration improvements:  coerce chars
to unsigned chars before using macros like isspace;  source ~/.tclshrc
file during initialization if it exists and program is running
interactively;  allow there to be directories in auto_path that don't
exist or don't have tclIndex files (ignore them); added Tcl_Init
procedure and changed Tcl_AppInit to call it.

221. 8/21/93 Fixed bug in expr where "+", "-", and " " were all
getting treated as integers with value 0.

222. 8/26/93 Added "tcl_interactive" variable to tclsh.

223. 8/27/93 Added procedure Tcl_FilePermissions to return whether a
given file can be read or written or both.  Modified Tcl_EnterFile
to take a permissions mask rather than separate read and write arguments.

224. 8/28/93 Fixed performance bug in "glob" command (unnecessary call
to "access" for each file caused a 5-10x slow-down for big directories).

----------------- Released version 7.0 Beta 3, 8/28/93 ------------------

225. 9/9/93 Renamed regexp.h to tclRegexp.h to avoid conflicts with system
include file by same name.

226. 9/9/93 Added Tcl_DontCallWhenDeleted.

227. 9/16/93 Changed not to call exit C procedure directly;  instead
always invoke "exit" Tcl command so that application can redefine the
command to do additional cleanup.

228. 9/17/93 Changed auto-exec to handle names that contain slashes
(i.e. don't use PATH for them).

229. 9/23/93 Fixed bug in "read" and "gets" commands where they didn't
clear EOF conditions.

----------------- Released version 7.0, 9/29/93 ------------------

230. 10/7/93 "Scan" command wasn't properly aligning things in memory,
so segmentation faults could arise under some circumstances.

231. 10/7/93 Fixed bug in Tcl_ConvertElement where it forgot to
backslash leading curly brace when creating lists.

232. 10/7/93 Eliminated dependency of tclMain.c on tclInt.h and
tclUnix.h, so that people can copy the file out of the Tcl source
directory to make modified private versions.

233. 10/8/93 Fixed bug in auto-loader that reversed the priority order
of entries in auto_path for new-style index files.  Now things are
back to the way they were before 3.0:  first in auto_path is always
highest priority.

234. 10/13/93 Fixed bug where Tcl_CommandComplete didn't recognize
comments and treat them as such.  Thus if you typed the line
    # {
interactively, Tcl would think that the command wasn't complete and
wait for more input before evaluating the script.

235. 10/14/93 Fixed bug where "regsub" didn't set the output variable
if the input string was empty.

236. 10/23/93 Fixed bug where Tcl_CreatePipeline didn't close off enough
file descriptors in child processes, causing children not to exit
properly in some cases.

237. 10/28/93 Changed "list" and "concat" commands not to generate
errors if given zero arguments, but instead to just return an empty
string.

----------------- Released version 7.1, 11/4/93 ------------------

Note: there is no 7.2 release.  It was flawed and was thus withdrawn
shortly after it was released.

238. 11/10/93 TclMain.c didn't compile on some systems because of
R_OK in call to "access".  Changed to eliminate call to "access".

----------------- Released version 7.3, 11/26/93 ------------------

239. 11/6/93 Modified "lindex", "linsert", "lrange", and "lreplace"
so that "end" can be specified as an index.

240. 11/6/93 Modified "append" and "lappend" to allow only two
words total (i.e., nothing to append) without generating an error.

241. 12/2/93 Changed to use EAGAIN as the errno for non-blocking
I/O instead of EWOULDBLOCK:  this should fix problem where non-blocking
I/O didn't work correctly on System-V systems.

242. 12/22/93 Fixed bug in expressions where cancelled evaluation
wasn't always working correctly (e.g. "set one 1; eval {1 || 1/$one}"
failed with a divide by zero error).

243. 1/6/94 Changed TCL_VOLATILE definition from -1 to the address of
a dummy procedure Tcl_Volatile, since -1 causes portability problems on
some machines (e.g., Crays).

244. 2/4/94 Added support for unary plus.

245. 2/17/94 Changed Tcl_RecordAndEval and "history" command to
call Tcl_GlobalEval instead of Tcl_Eval.  Otherwise, invocation of
these facilities in nested procedures can cause unwanted results.

246. 2/17/94 Fixed bug in tclExpr.c where an expression such as
"expr {"12398712938788234-1298379" != ""}" triggers an integer
overflow error for the number in quotes, even though it isn't really
a proper integer anyway.

247. 2/19/94 Added new procedure Tcl_DStringGetResult to move result
from interpreter to a dynamic string.

248. 2/19/94 Fixed bug in Tcl_DStringResult that caused it to overwrite
the contents of a static result in some situations.  This can cause
bizarre errors such as variables suddenly having empty values.

249. 2/21/94 Fixed bug in Tcl_AppendElement, Tcl_DStringAppendElement,
and the "lappend" command that caused improper omission of a separator
space in some cases.  For example, the script
    set x "abc{"; lappend x "def"
used to return the result "abc{def" instead of "abc{ def".

250. 3/3/94 Tcl_ConvertElement was outputting empty elements as \0 if
TCL_DONT_USE_BRACES was set.  This depends on old pre-7.0 meaning of
\0, which is no longer in effect, so it didn't really work.  Changed
to output empty elements as {} always.

251. 3/3/94 Renamed Tcl_DStringTrunc to Tcl_DStringSetLength and extended
it so that it can be used to lengthen a string as well as shorten it.
Tcl_DStringTrunc is defined as a macro for backward compatibility, but
it is deprecated.

252. 3/3/94 Added Tcl_AllowExceptions procedure.

253. 3/13/94 Fixed bug in Tcl_FormatCmd that could cause "format"
to mis-behave on 64-bit Big-Endian machines.

254. 3/13/94 Changed to use vfork instead of fork on systems where
vfork exists.

255. 3/23/94 Fixed bug in expressions where ?: didn't associate
right-to-left as they should.

256. 4/3/94 Fixed "exec" to flush any files used in >@ or >&@
redirection in exec, so that data buffered for them is written
before any new data added by the subprocess.

257. 4/3/94 Added "subst" command.

258. 5/20/94 The tclsh main program is now called Tcl_Main;  tclAppInit.c
has a "main" procedure that calls Tcl_Main.  This makes it easier to use
Tcl with C++ programs, which need their own main programs, and it also
allows an application to prefilter the argument list before calling
Tcl_Main.
*** POTENTIAL INCOMPATIBILITY ***

259. 6/6/94 Fixed bug in procedure returns where the errorInfo variable
could get truncated if an unset trace was invoked as part of returning
from the procedure.

260. 6/13/94 Added "wordstart" and "wordend" options to "string" command.

261. 6/27/94 Fixed bug in expressions where they didn't properly cancel
the evaluation of math functions in &&, ||, and ?:.

262. 7/11/94 Incorrect boolean values, like "ogle", weren't being
handled properly.

263. 7/15/94 Added Tcl_RegExpCompile, Tcl_RegExpExec, and Tcl_RegExpRange,
which provide lower-level access to regular expression pattern matching.

264. 7/22/94 Fixed bug in "glob" command where "glob -nocomplain ~bad_user"
would complain about a missing user.  Now it doesn't complain anymore.

265. 8/4/94 Fixed bug with linked variables where they didn't behave
correctly when accessed via upvars.

266. 8/17/94 Fixed bug in Tcl_EvalFile where it didn't clear interp->result.

267. 8/31/94 Modified "open" command so that errors in exec-ing
subprocesses are returned by the open immediately, rather than
being delayed until the "close" is executed.

268. 9/9/94 Modified "expr" command to generate errors for integer
overflow (includes addition, subtraction, negation, multiplication,
division).

269. 9/23/94 Modified "regsub" to return a count of the number of
matches and replacements, rather than 0/1.

279. 10/4/94 Added new features to "array" command:
    - added "get" and "set" commands for easy conversion between arrays
      and lists.
    - added "exists" command to see if a variable is an array, changed
      "names" and "size" commands to treat a non-existent array (or scalar
      variable) just like an empty one.
    - added pattern option to "names" command.

280. 10/6/94 Modified Tcl_SetVar2 so that read traces on variables get
called during append operations.

281. 10/20/94 Fixed bug in "read" command where reading from stdin
required two control-D's to stop the reading.

282. 11/3/94 Changed "expr" command to use longs for division just like
all other expr operators;  it previously used ints for division.

283. 11/4/94 Fixed bugs in "unknown" procedure:  it wasn't properly
handling exception returns from commands that were executed after
being auto-loaded.

----------------- Released version 7.4b1, 12/23/94 ------------------

284. 12/26/94 Fixed "install" target in Makefile (couldn't always
find install program).

285. 12/26/94 Added strcncasecmp procedure to compat directory.

286. 1/3/95 Fixed all procedure calls to explicitly cast arguments:
implicit conversions from prototypes (especially integer->double)
don't work when compiling under non-ANSI compilers.  Tcl is now clean
under gcc -Wconversion.

287. 1/4/95 Fixed problem in Tcl_ArrayCmd where same name was used for
both a label and a variable;  caused problems on several older compilers,
making array command misbehave and causing many errors in Tcl test suite.

----------------- Released version 7.4b2, 1/12/95 ------------------

288. 2/9/95 Modified Tcl_CreateCommand to return a token, and added
Tcl_GetCommandName procedure.  Together, these procedures make it possible
to track renames of a command.

289. 2/13/95 Fixed bug in expr where "089" was interpreted as a
floating-point number rather than a bogus octal number.
*** POTENTIAL INCOMPATIBILITY ***

290. 2/14/95 Added code to Tcl_GetInt and Tcl_GetDouble to check for
overflows when reading in numbers.

291. 2/18/95 Changed "array set" to stop after first error, rather than
continuing after error.

292. 2/20/95 Upgraded to use autoconf version 2.2.

293. 2/20/95 Fixed core dump that could occur in "scan" command if a
close bracket was omitted.

294. 2/27/95 Changed Makefile to always use install-sh for installations:
there's just too much variation among "install" system programs, which
makes installation flakey.

----------------- Released version 7.4b3, 3/24/95 ------------------

3/25/95 (bug fix) Changed "install" to "./install" in Makefile so that
"make install" will work even when "." isn't in the search path.

3/29/95 (bug fix) Fixed bug where the auto-loading mechanism wasn't
protecting the values of the errorCode and errorInfo variables.

3/29/95 (new feature) Added optional pattern argument to "parray" procedure.

3/29/95 (bug fix) Made the full functionality of
    "return -code ... -errorcode ..."
work not just inside procedures, but also in sourced files and at
top level.

4/6/95 (new feature) Added "pattern" option to "array names" command.

4/18/95 (bug fix) Fixed bug in parser where it didn't allow backslash-newline
immediately after an argument in braces or quotes.

4/19/95 (new feature) Added tcl_library variable, which application can
set to override default library directory.

4/30/95 (bug fix) During trace callbacks for array elements, the variable
name used in the original reference would be temporarily modified to
separate the array name and element name;  if the trace callback used
the same name string, it would get the wrong name (the array name without
element).  Fixed to restore the variable name before making trace
callbacks.

4/30/95 (new feature) Added -nobackslashes, -nocommands, and -novariables
switches to "subst" command.

5/4/95 (new feature) Added TCL_EVAL_GLOBAL flag to Tcl_RecordAndEval.

5/5/95 (bug fix)  Format command would overrun memory when printing
integers with very large precision, as in "format %.1000d 0".

5/5/95 (portability improvement) Changed to use BSDgettimeofday on
IRIX machines, to avoid compilation problems with the gettimeofday
declaration.

5/6/95 (bug fix) Changed manual entries to use the standard .TH
macro instead of a custom .HS macro;  the .HS macro confuses index
generators like makewhatis.

5/9/95 (bug fix) Modified configure script to check for Solaris bug
that makes vfork unreliable (core dumps result if vforked child
changes a signal handler);  will use fork instead of vfork if the
bug is present.

6/5/95 (bug fix) Modified "lsort" command to disallow recursive calls
to lsort from a comparison function.  This is needed because qsort
is not reentrant.

6/5/95 (bug fix) Undid change 243 above:  changed TCL_VOLATILE and
TCL_DYNAMIC back to integer constants rather than procedure addresses.
This was needed because procedure addresses can have multiple values
under some dynamic loading systems (e.g. SunOS 4.1 and Windows).

6/8/95 (feature change) Modified interface to Tcl_Main to pass in the
address of the application-specific initialization procedure.
Tcl_AppInit is no longer hardwired into Tcl_Main.  This is needed
in order to make Tcl a shared library. 

6/8/95 (feature change) Modified Makefile so that the installed versions
of tclsh and libtcl.a have version number in them (e.g. tclsh7.4 and
libtcl7.4.a) and the library directory name also has an embedded version
number (e.g., /usr/local/lib/tcl7.4).  This should make it easier for
Tcl 7.4 to coexist with earlier versions.

----------------- Released version 7.4b4, 6/16/95 ------------------

6/19/95 (bug fix) Fixed bugs in tclCkalloc.c that caused core dumps
if TCL_MEM_DEBUG was enabled on word-addressed machines such as Crays.

6/21/95 (feature removal) Removed overflow checks for integer arithmetic:
they just cause too much trouble (e.g. for random  number generators).

6/28/95 (new features) Added tcl_patchLevel and tcl_version variables,
for consistency with Tk.

6/29/95 (bug fix) Fixed problem in Tcl_Eval where it didn't record
the right termination character if a script ended with a comment.  This
caused erroneous output for the following command, among others:
puts "[
expr 1+1
# duh!
]"

6/29/95 (message change) Changed the error message for ECHILD slightly
to provide a hint about why the problem is occurring.

----------------- Released version 7.4, 7/1/95 ------------------

7/18/95 (bug fix) Changed "lreplace" so that nothing is deleted if
the last index is less than the first index or if the last index
is < 0.

7/18/95 (bug fix) Fixed bugs with backslashes in comments:
Tcl_CommandComplete (and "info complete") didn't properly handle
strings ending in backslash-newline, and neither Tcl_CommandComplete
nor the Tcl parser handled other backslash sequences right, such
as two backslashes before a newline.

7/19/95 (bug fix) Modified Tcl_DeleteCommand to delete the hash table
entry for the command before invoking its callback.  This is needed in
order to deal with reentrancy.

7/22/95 (bug fix) "exec" wasn't reaping processes correctly after
certain errors (e.g. if the name of the executable was bogus, as
in "exec foobar").

7/27/95 (bug fix) Makefile.in wasn't using the LIBS variable provided
by the "configure" script.  This caused problems on some SCO systems.

7/27/95 (bug fix) The version of strtod in fixstrtod.c didn't properly
handle the case where endPtr == NULL.

----------------- Released patch 7.4p1, 7/29/95 -----------------------

8/4/95 (bug fix) C-level trace callbacks for variables were sometimes
receiving the PART1_NOT_PARSED flag, which could cause errors in
subsequent Tcl library calls using the flags. (JO)

8/4/95 (bug fix) Calls to toupper and tolower weren't using the
UCHAR macros, which caused trouble in non-U.S. locales. (JO)

8/10/95 (new feature) Added the "load" command for dynamic loading of
binary packages, and the Tcl_PackageInitProc prototype for package
initialization procedures. (JO)

8/23/95 (new features) Added "info sharedlibextension" and
"info nameofexecutable" commands, plus Tcl_FindExtension procedure. (JO)

8/25/95 (bug fix) If the target of an "upvar" was non-existent but
had traces set, the traces were silently lost.  Change to generate
an error instead. (JO)

8/25/95 (bug fix) Undid change from 7/19, so that commands can stay
around while their deletion callbacks execute.  Added lots of code to
handle all of the reentrancy problems that this opens up. (JO)

8/25/95 (bug fix) Fixed core dump that could occur in TclDeleteVars
if there was an upvar from one entry in the table to the next entry
in the same table. (JO)

8/28/95 (bug fix) Exec wasn't handling bad user names properly, as
in "exec ~bogus_user/foo". (JO)

8/29/95 (bug fixes) Changed backslash-newline handling to correct two
problems:
    - Only spaces and tabs following the backslash-newline are now
      absorbed as part of the backslash-newline.  Newlinew are no
      longer absorbed (add another backslash if you want to absorb
      another newline).
    - TclWordEnd returns the character just before the backslash in
      the sequence as the end of the sequence;  it used to not consider
      the backslash-newline as a word separator. (JO)

8/31/95 (new feature) Changed man page installation (with "mkLinks"
script) to create additional links for manual pages corresponding to
each of the procedure and command names described in the pages. (JO)

9/10/95 Reorganized Tcl sources for Windows and Mac ports.  All sources
are now in subdirectories:  "generic" contains sources that work on all
platforms, "windows", "mac", and "unix" directories contain platform-
specific sources.  Some UNIX sources are also used on other platforms. (SS)

9/10/95 (feature change) Eliminated exported global variables (they
don't work with Windows DLLs).  Replaced tcl_AsyncReady and
tcl_FileCloseProc with procedures Tcl_AsyncReady() and
Tcl_SetFileCloseProc().  Replaced C variable tcl_RcFileName with
a Tcl variable tcl_rcFileName. (SS)
*** POTENTIAL INCOMPATIBILITY ***

9/11/95 (new feature) Added procedure Tcl_SetPanicProc to override
the default implementation of "panic". (SS)

9/11/95 (new feature) Added "interp" command to allow creation of
new interpreters and execution of untrusted scripts.  Added many new
procedures, such as Tcl_CreateSlave, Tcl_CreateAlias,and Tcl_MakeSafe,
to provide C-level access to the interpreter facility. This mechanism
now provides almost all of the generic functions of Borenstein's and
Rose's Safe-Tcl (but not any Tk or email-related stuff).  (JL)

9/11/95 (feature change) Changed file management so that files are
no longer shared between interpreters:  a file cannot normally be
referenced in one interpreter if it was opened in another.  This
feature is needed to support safe interpreters.  Added Tcl_ShareHandle()
procedure for allowing files to be shared, and added "interp" argument
to Tcl_FilePermissions procedure. (JL)
*** POTENTIAL INCOMPATIBILITY ***

9/11/95 (new feature) Added "AssocData" mechanism, whereby extensions
can associate their own data with an interpreter and get called back
when the interpreter is deleted.  This is visible at C level via the
procedures Tcl_SetAssocData and Tcl_GetAssocData.  (JL)

9/11/95 (new feature) Added Tcl_ErrnoMsg to translate an errno value
into a human-readable string.  This is now used instead of calling
strerror because strerror mesages vary dramatically from platform
to platform, which messes up Tcl tests.  Tcl_ErrnoMsg uses the standard
POSIX messages for all the common signals, and calls strerror for
signals it doesn't understand.

----------------- Released patch 7.5p2, 9/15/95 -----------------------

----------------- Released 7.5a1, 9/15/95 -----------------------

9/22/95 (bug fix) Changed auto_mkindex to create tclIndex files that
handle directories whose paths might contain spaces. (RJ)

9/27/95 (bug fix) The "format" command didn't check for huge or negative
width specifiers, which could cause core dumps. (JO)

9/27/95 (bug fix) Core dumps could occur if an interactive command typed
to tclsh returned a very long result for tclsh to print out.  The bug is
actually in printf (in Solaris 2.3 and 2.4, at least);  switched to use
puts instead.  (JO)

9/28/95 (bug fix) Changed makefile.bc to eliminate a false dependency
for tcl1675.dll on the Borland run time library. (SS)

9/28/95 (bug fix) Fixed tcl75.dll so it looks for tcl1675.dll instead
of tcl16.dll. (SS)

9/28/95 (bug fix) Tcl was not correctly detecting the difference
between Win32s and Windows '95. (SS)

9/28/95 (bug fix) "exec" was not passing environment changes to child
processes under Windows. (SS)

9/28/95 (bug fix) Changed Tcl to ensure that open files are not passed
to child processes under Windows. (SS)

9/28/95 (bug fix) Fixed Windows '95 and NT versions of exec so it can
handle both console and windows apps.   (SS)

9/28/95 (bug fix) Fixed Windows version of exec so it no longer leaves
temp files lying around.  Also changed it so the temp files are
created in the appropriate system dependent temp directory. (SS)

9/28/95 (bug fix) Eliminated source dependency on the Win32s Universal
Thunk header file, since it is not bundled with VC++. (SS)

9/28/95 (bug fix) Under Windows, Tcl now constructs the HOME
environment variable from HOMEPATH and HOMEDRIVE when HOME is not
already set. (SS)

9/28/95 (bug fix) Added support for "info nameofexecutable" and "info
sharedlibextension" to the Windows version. (SS)

9/28/95 (bug fix) Changed tclsh to correctly parse command line
arguments so that backslashes are preserved under Windows. (SS)

9/29/95 (bug fix) Tcl 7.5a1 treated either return or newline as end
of line in "gets", which caused lines ending in CRLF to be treated as
two separate lines.  Changed to allow only character as end-of-line:
carriage return on Macs, newline elsewhere. (JO)

9/29/95 (new feature) Changed to install "configInfo" file in same
directory as library scripts.  It didn't used to get installed. (JO)

9/29/95 (bug fix) Tcl was not converting Win32 errors into POSIX
errors under some circumstances. (SS)

10/2/95 (bug fix) Safe interpreters no longer get initialized with
a call to Tcl_Init(). (JL)

10/1/95 (new feature) Added "tcl_platform" global variable to provide
environment information such as the instruction set and operating
system. (JO)

10/1/95 (bug fix) "exec" command wasn't always generating the
"child process exited abnormally" message when it should have.  (JO)

10/2/95 (bug fix) Changed "mkLinks.tcl" so that the scripts it generates
won't create links that overwrite original manual entries (there was
a problem where pack-old.n was overwriting pack.n).  (JO)

10/2/95 (feature change) Changed to use -ldl for dynamic loading under
Linux if it is available, but fall back to -ldld if it isn't.  (JO)

10/2/95 (bug fix) File sharing was causing refcounts to reach 0
prematurely for stdin, stdout and stderr, under some circumstances. (JL)

10/2/95 (platform support) Added support for Visual C++ compiler on
Windows, Windows '95 and Windows NT, code donated by Gordon Chaffee. (JL)

10/3/95 (bug fix) Tcl now frees any libraries that it loads before it
exits. (SS)

10/03/95 (bug fix) Fixed bug in Macintosh ls command where the -l
and -C options would fail in anything but the HOME directory. (RJ)

----------------- Released 7.5a2, 10/6/95 -----------------------

10/10/95 (bug fix) "file dirnam /." was returning ":" on UNIX instead
of "/". (JO)

10/13/95 (bug fix) Eliminated dependency on MKS toolkit for generating
the tcl.def file from Borland object files. (SS)

10/17/95 (new features) Moved the event loop from Tcl to Tk, made major
revisions along the way:
    - New Tcl commands:  after, update, vwait (replaces "tkwait variable").
    - "tkerror" is now replaced with "bgerror".
    - The following procedures are similar to their old Tk counterparts:
      Tcl_DoOneEvent, Tcl_Sleep, Tcl_DoWhenIdle, Tcl_CancelIdleCall,
      Tcl_CreateFileHandler, Tcl_DeleteFileHandler, Tcl_CreateTimerHandler,
      Tcl_DeleteTimerHandler, Tcl_BackgroundError.
    - Revised notifier, add new concept of "event source" with the following
      procedures:  Tcl_CreateEventSource, Tcl_DeleteEventSource,
      Tcl_WatchFile, Tcl_SetMaxBlockTime, Tcl_FileReady, Tcl_QueueEvent,
      Tcl_WaitForEvent. (JO)

10/31/95 (new features) Implemented cross platform file name support to make
it easier to write cross platform scripts.  Tcl now understands 4 file naming
conventions: Windows (both DOS and UNC), Mac, Unix, and Network.  The network
convention is a new naming mechanism that can be used to paths in a platform
independent fashion.  See the "file" command manual page for more details.
The primary interfaces changes are:
    - All Tcl commands that expect a file name now accept both network and
      native form.
    - Two new "file" subcommands, "nativename" and "networkname", provide a
      way to convert between network and native form.
    - Renamed Tcl_TildeSubst to Tcl_TranslateFileName, and changed it so that
      it always returns a filename in native form.  Tcl_TildeSubst is defined
      as a macro for backward compatibility, but it is deprecated. (SS)

11/5/95 (new feature) Made "tkerror" and "bgerror" synonyms, so that
either name can be used to manipulate the command (provides temporary
backward compatibility for existing scripts that use tkerror). (JO)

11/5/95 (new feature) Added exit handlers and new C procedures
Tcl_CreateExitHandler, Tcl_DeleteExitHandler, and Tcl_Exit. (JO)

11/6/95 (new feature) Added pid command for Macintosh version of
Tcl (it didn't previously exist on the Mac). (RJ)

11/7/95 (new feature) New generic IO facility and support for IO to
files, pipes and sockets based on a common buffering scheme. Support
for asynchronous (non-blocking) IO and for event driver IO. Support
for automatic (background) asynchronous flushing and asynchronous
closing of channels. (JL)

11/7/95 (new feature)  Added new commands "fconfigure" and "fblocked"
to support new I/O features such as nonblocking I/O.  Added "socket"
command for creating TCP client and server sockets. (JL).

11/7/95 (new feature) Complete set of C APIs to the new generic IO
facility:
    - Opening channels: Tcl_OpenFileChannel, Tcl_OpenCommandChannel,
      Tcl_OpenTcpClient, Tcl_OpenTcpServer.
    - I/O procedures on channels, which roughly mirror the ANSI C stdio
      library:  Tcl_Read, Tcl_Gets, Tcl_Write, Tcl_Flush, Tcl_Seek,
      Tcl_Tell, Tcl_Close, Tcl_Eof, Tcl_InputBlocked, Tcl_GetChannelOption,
      Tcl_SetChannelOption.
    - Extension mechanism for creating new kinds of channels:
      Tcl_CreateChannel, Tcl_GetChannelInstanceData, Tcl_GetChannelType,
      Tcl_GetChannelName, Tcl_GetChannelFile, Tcl_RegisterChannel,
      Tcl_UnregisterChannel, Tcl_GetChannel.
    - Event-driven I/O on channels: Tcl_CreateChannelHandler,
      Tcl_DeleteChannelHandler. (JL)

11/7/95 (new feature) Channel driver interface specification to allow
new types of channels to be added easily to Tcl. Currently being used
in three drivers - for files, pipes and TCP-based sockets. (JL).

11/7/95 (new feature) interp delete now takes any number of path
names of interpreters to delete, including zero. (JL).

11/8/95 (new feature) implemented 'info hostname' and Tcl_GetHostName
command to get host name of machine on which the Tcl process is running. (JL)

11/9/95 (new feature) Implemented file APIs for access to low level files
on each system. The APIs are: Tcl_CloseFile, Tcl_OpenFile, Tcl_ReadFile,
Tcl_WriteFile and Tcl_SeekFile. Also implemented Tcl_WaitPid which waits
in a system dependent manner for a child process. (JL)

11/9/95 (new feature) Added Tcl_UpdateLinkedVar procedure to force a
Tcl variable to be updated after its C variable changes. (JO)

11/9/95 (bug fix) The glob command has been totally reimplemented so
that it can support different file name conventions.  It now handles
Windows file names (both UNC and drive-relative) properly.  It also
supports nested braces correctly now. (SS)

11/13/95 (bug fix) Fixed Makefile.in so that configure can be run
from a clean directory separate from the Tcl source tree, and compilations
can be performed there. (JO)

11/14/95 (bug fix) Fixed file sharing between interpreters and file
transferring between interpreters to correctly manage the refcount so that
files are closed when the last reference to them is discarded. (JL)

11/14/95 (bug fix) Fixed gettimeofday implementation for the
Macintosh.  This fixes several timing related bugs. (RJ)

11/17/95 (new feature) Added missing support for info nameofexecutable
on the Macintosh. (RJ)

11/17/95 (bug fix) The Tcl variables argc argv and argv0 now return
something reasonable on the Mac.  (RJ)

11/22/95 (new feature) Implemented "auto-detect" mode for end of line
translations. On input, standalone "\r" mean MAC mode, standalone "\n"
mean Unix mode and "\r\n" means Windows mode. On output, the mode is
modified to whatever the platform specific mode for that platform is. (JL)

11/24/95 (feature change) Replaced "configInfo" file with tclConfig.sh,
which is more complete and uses slightly different names.  Also
arranged for tclConfig.sh to be installed in the platform-specific
library directory instead of Tcl's script library directory. (JO)
*** POTENTIAL INCOMPATIBILITY with Tcl 7.5a2, but not with Tcl 7.4 ***

----------------- Released patch 7.4p3, 11/28/95 -----------------------

12/5/95 (new feature) Added Tcl_File facility to support platform-
independent file handles.  Changed all interfaces that used Unix-
style integer fd's to use Tcl_File's instead. (SS)
*** POTENTIAL INCOMPATIBILITY ***

12/5/95 (new feature) Added a new "clock" command to Tcl.  The command
allows you to get the current "clicks" or seconds & allows you to
format or scan human readable time/date strings. (RJ)

12/18/95 (new feature) Moved Tk_Preserve, Tk_Release, and Tk_EventuallyFree
to Tcl, renamed to Tcl_Preserve, Tcl_Release, and Tcl_EventuallyFree. (JO)

12/18/95 (new feature) Added new "package" command and associated
procedures Tcl_PkgRequire and Tcl_PkgProvide.   Also wrote
pkg_mkIndex library procedure to create index files from binaries
and scripts. (JO)

12/20/95 (new feature) Added Tcl_WaitForFile procedure. (JO)

12/21/95 (new features) Made package name argument to "load" optional
(Tcl will now attempt to guess the package name if necessary).  Also
added Tcl_StaticPackage and support in "load" for statically linked
packages.  (JO)

12/22/95 (new feature) Upgraded the foreach command to accept multiple
loop variables and multiple value lists.  This lets you iterate over
multiple lists in parallel, and/or assign multiple loop variables from
one value list during each iteration. The only potential compatibility
problem is with scripts that used loop variables with a name that could be
construed to be a list of variable names (i.e. contained spaces).  (BW)

1/5/96 (new feature) Changed tclsh so it builds as a console mode
application under Windows.  Now tclsh can be used from the command
line with pipes or interactively.  Note that this only works under
Windows 95 or NT. (SS)

1/17/96 (new feature) Modified Makefile and configure script to allow
Tcl to be compiled as a shared library:  use the --enable-shared option
when configuing.  (JO)

1/17/96 (removed obsolete features)  Removed the procedures Tcl_EnterFile
and Tcl_GetOpenFile:  these no longer make sense with the new I/O system. (JL)
*** POTENTIAL INCOMPATIBILITY ***

1/19/96 (bug fixes) Prevented formation of circular aliases, through the
Tcl 'interp alias' command and through the 'rename' command, as well as
through the C API Tcl_CreateAlias. (JL)

1/19/96 (bug fixes) Fixed several bugs in direct deletion of interpreters
with Tcl_DeleteInterp when the interpreter is a slave; fixes based on a
patch received from Viktor Dukhovni of ESM. (JL)

1/19/96 (new feature) Implemented on-close handlers for channels; added
the C APIs Tcl_CreateCloseHandler and Tcl_DeleteCloseHandler. (JL)

1/19/96 (new feature) Implemented portable error reporting mechanism; added
the C APIs Tcl_SetErrno and Tcl_GetErrno. (JL)

1/24/96 (bug fix) Unknown command processing properly invokes external
commands under Windows NT and Windows '95 now. (SS)

1/23/96 (bug fix) Eliminated extremely long startup times under Windows '95.
The problem was a result of the option database initialization code that
concatenated $HOME with /.Xdefaults, resulting in a // in the middle of the
file name.  Under Windows '95, this is incorrectly interpreted as a UNC
path.  They delays came from the network timeouts needed to determine that
the file name was invalid.  Tcl_TranslateFileName now suppresses duplicate
slashes that aren't at the beginning of the file name. (SS)
				     
1/25/96 (bug fix) Changed exec and open to create children so they are
attached to the application's console if it exists. (SS)

1/31/96 (bug fix) Fixed command line parsing to handle embedded
spaces under Windows. (SS)

----------------- Released 7.5b1, 2/1/96 -----------------------

2/7/96 (bug fix) Fixed off by one error in argument parsing code under
Windows. (SS)

2/7/96 (bug fix) Fixed bugs in VC++ makefile that improperly
initialized the tcl75.dll.  Fixed bugs in Borland makefile that caused
build failures under Windows NT. (SS)

2/9/96 (bug fix) Fixed deadlock problem in AUTO end of line translation
mode which would cause a socket server with several concurrent clients
writing in CRLF mode to hang. (JL)

2/9/96 (API change) Replaced -linemode option to fconfigure with a
new -buffering option, added "none" setting to enable immediate write. (JL)
*** INCOMPATIBILITY with b1 ***

2/9/96 (new feature) Added C API Tcl_InputBuffered which returns the count
of bytes currently buffered in the input buffer of a channel, and o for
output only channels. (JL)

2/9/96 (new feature) Implemented asynchronous connect for sockets. (JL)

2/9/96 (new feature) Added C API Tcl_SetDefaultTranslation to set (per
channel) the default end of line translation mode. This is the mode that
will be installed if an output operation is done on the channel while it is
still in AUTO mode. (JL)

2/9/96 (bug fix) Changed Tcl_OpenCommandChannel interface to properly
handle all of the combinations of stdio inheritance in background
pipelines.  See the Tcl_OpenFileChannel(3) man page for more
info.  This change fixes the bug where exec of a background pipeline
was not getting passed the stdio handles properly. (SS)

2/9/96 (bug fix) Removed the new Tcl_CreatePipeline interface, and
restored the old version for Unix platforms only.  All new code should
use Tcl_CreateCommandChannel instead. (SS)

2/9/96 (bug fix) Changed Makefile.in to use -L and -ltcl7.5 for Tcl
library so that shared libraries are more likely to be found correctly
on more platforms. (JO)

2/13/96 (new feature) Added C API Tcl_SetNotifierData and
Tcl_GetNotifierData to allow notifier and channel driver writers to
associate data with a Tcl_File.  The result of this change is that
Tcl_GetFileInfo now always returns an OS file handle, and Tcl_GetFile
can be used to construct a Tcl_File for an externally constructed OS
handle. (SS)

2/13/96 (bug fix) Changed Windows socket implementation so it doesn't
set SO_REUSEADDR on server sockets.  Now attempts to create a server
socket on a port that is already in use will be properly identified
and an error will be generated. (SS)

2/13/96 (bug fix) Fixed problems with DLL initialization under Visual
C++ that left the C run time library uninitialized. (SS)

2/13/96 (bug fix) Fixed Windows socket initialization so it loads
winsock the first time it is used, rather than at the time tcl75.dll
is loaded.  This should fix the bug where the modem immediately starts
trying to connect to a service provider when wish or tclsh are
started. (SS)

2/13/96 (new feature) Added C APIs Tcl_MakeFileChannel and
Tcl_MakeTcpClientChannel to wrap up existing fds and sockets into
channels. Provided implementations on Unix and Windows. (JL)

2/13/96 (bug fix) Fixed bug with seek leaving EOF and BLOCKING set. (JL)

2/14/96 (bug fix) Fixed reentrancy problem in fileevent handling
and made it more robust in the face of errors. (JL)

2/14/96 (feature change) Made generic IO level emulate blocking mode if the
channel driver is unable to provide it, e.g. if the low level device is
always nonblocking. Thus, now blocking behavior is an advisory setting for
channel drivers and can be ignored safely if the channel driver is unable
to provide it. (JL)

2/15/96 (new feature) Added "binary" end of line translation mode, which is
a synonym of "lf" mode. (JL)

2/15/96 (bug fix) Fixed reentrancy problem in fileevent handling vs
deletion of channel event handlers. (JL)

2/15/96 (bug fix) Fixed bug in event handling which would cause a
nonblocking channel to not see further readable events after the first
readable event that had insufficient input. (JL)

2/17/96 (bug fix) "info complete" didn't properly handle comments
in nested commands. (JO)

2/21/96 (bug fix) "exec" under Windows NT/95 did not properly handle
very long command lines (>200 chars). (SS)

2/21/96 (bug fix) Sockets could get into an infinite loop if a read
event arrived after all of the available data had been read. (SS)

2/22/96 (bug fix) Added cast of st_size elements to (long) before
sprintf-ing in "file size" command.  This is needed to handle systems
like NetBSD with 64-bit file offsets.  (JO)

----------------- Released 7.5b2, 2/23/96 -----------------------

2/23/96 (bug fix) TCL_VARARGS macro in tcl.h wasn't defined properly
when compiling with C++.  (JO)

2/24/96 (bug fix) Removed dependencies on Makefile in the UNIX Makefile:
this caused problems on some platforms (like Linux?). (JO)

2/24/96 (bug fix) Fixed configuration bug that made Tcl not compile
correctly on Linux machines with neither -ldl or -ldld. (JO)

2/24/96 (new feature) Added a block of comments and definitions to
Makefile.in to make it easier to have Tcl's TclSetEnv etc. replace
the library procedures setenv etc, so that calls to setenv etc. in
the application automatically update the Tcl "env" variable. (JO)

2/27/96 (feature change) Added optional Tcl_Interp * argument (may be NULL)
to C API Tcl_Close and simplified closing of command channels. (JL)
*** INCOMPATIBILITY with Tcl 7.5b2, but not with Tcl 7.4 ***

2/27/96 (feature change) Added optional Tcl_Interp * argument (may be NULL)
to C type definition Tcl_DriverCloseProc; modified all channel drivers to
implement close procedures that accept the additional argument. (JL)
*** INCOMPATIBILITY with Tcl 7.5b2, but not with Tcl 7.4 ***

2/28/96 (bug fix) Fixed memory leak that could occur if an upvar
referred to an element of an array in the same stack frame as the
upvar. (JO)

2/29/96 (feature change) Modified both Tcl_DoOneEvent and Tcl_WaitForEvent
so that they return immediately in cases where they would otherwise
block forever (e.g. if there are no event handlers of any sort). (JO)

2/29/96 (new feature) Added C APIs Tcl_GetChannelBufferSize and
Tcl_SetChannelBufferSize to set and retrieve the size, in bytes, for
buffers allocated to store input or output in a channel. (JL)

2/29/96 (new feature) Added option -buffersize to Tcl fconfigure command
to allow Tcl scripts to query and set the size of channel buffers. (JL)

2/29/96 (feature removed) Removed channel driver function to specify
the buffer size to use when allocating a buffer. Removed the C typedef
for Tcl_DriverBufferSizeProc. Channels are now created with a default
buffer size of 4K. (JL)
*** INCOMPATIBILITY with Tcl 7.5b2, but not with Tcl 7.4 ***

2/29/96 (feature change) The channel driver function for setting blocking
mode on the device may now be NULL. If the generic code detects that the
function is NULL, operations that set the blocking mode on the channel
simply succeed. (JL)

3/2/96 (bug fix) Fixed core dump that could occur if a syntax error
(such as missing close paren) occurred in an array reference with a
very long array name. (JO)

3/4/96 (bug fix) Removed code in the "auto_load" procedure that deletes
all existing auto-load information whenever the "auto_path" variable
is changed.  Instead, new information adds to what was already there.
Otherwise, changing the "auto_path" variable causes all package-
related information to be lost.  If you really want to get rid of
existing auto-load information, use auto_reset before setting auto_path. (JO)

3/5/96 (new feature) Added version suffix to shared library names so that
Tcl will compile under NetBSD and FreeBSD (I hope).  (JO)

3/6/96 (bug fix) Cleaned up error messages in new I/O system to correspond
more closely to old I/O system. (JO)

3/6/96 (new feature) Added -myaddr and -myport options to the socket
command, removed -tcp and -- options.  This lets clients and servers
choose a particular interface.  Also changed the default server address
from the hostname to INADDR_ANY.  The server accept callback now gets
passed the client's port as well as IP address.  The C interfaces for
Tcl_OpenTcpClient and Tcl_OpenTcpServer have changed to support the
above changes. (BW)
*** POTENTIAL INCOMPATIBILITY with Tcl 7.5b2, but not with Tcl 7.4 ***

3/6/96 (changed feature) The library function auto_mkindex will now
default to using the pattern "*.tcl" if no pattern is given. (RJ)

3/6/96 (bug fix) The socket channel code for the Macintosh has been
rewritten to use native MacTcp.  (RJ)

3/7/96 (new feature) Added Tcl_SetStdChannel and Tcl_GetStdChannel
interfaces to allow applications to explicitly set and get the global
standard channels. (SS)

3/7/96 (bug fix) Tcl did close not the file descriptors associated
with "stdout", etc. when the corresponding channels were closed.  (SS)

3/7/96 (bug fix) Reworked shared library and dynamic loading stuff to
try to get it working under AIX.  Added new @[email protected] autoconf
symbol as part of this.  AIX probably doesn't work yet, but it should
be a lot closer. (JO)

3/7/96 (feature change) Added Tcl_ChannelProc typedef and changed the
signature of Tcl_CreateChannelHandler and Tcl_DeleteChannelHandler to take
Tcl_ChannelProc arguments instead of Tcl_FileProc arguments. This change
should not affect any code outside Tcl because the signatures of
Tcl_ChannelProc and Tcl_FileProc are compatible. (JL)

3/7/96 (API change) Modified signature of Tcl_GetChannelOption to return
an int instead of char *, and to take a Tcl_DString * argument. Modified
the implementation so that the option name can be NULL, to mean that the
call should retrieve a list of alternating option names and values. (JL)
*** INCOMPATIBILITY with Tcl 7.5b2, but not with Tcl 7.4 ***

3/7/96 (API change) Added Tcl_DriverSetOptionProc, Tcl_DriverGetOptionProc
typedefs, added two slots setOptionProc and getOptionProc to the channel
type structure. These may be NULL to indicate that the channel type does
not support any options. (JL)
*** INCOMPATIBILITY with Tcl 7.5b2, but not with Tcl 7.4 ***

3/7/96 (feature change) stdin, stdout and stderr can now be put into
nonblocking mode. (JL)

3/8/96 (feature change) Eliminated dependence on the registry for
finding the Tcl library files. (SS)

----------------- Released 7.5b3, 3/8/96 -----------------------

3/12/96 (feature improvement) Modified startup script to look in several
different places for the Tcl library directory.  This should allow Tcl
to find the libraries under all but the weirdest conditions, even without
the TCL_LIBRARY environment variable being set. (JO)

3/13/96 (bug fix) Eliminated use of the "linger" option from the Windows
socket implementation. (JL)

3/13/96 (new feature) Added -peername and -sockname options for fconfigure
for socket channels. Code contributed by John Haxby of HP. (JL)

3/13/96 (bug fix) Fixed panic and core dump that would occur if the accept
callback script on a server socket encountered an error. (JL)

3/13/96 (feature change) Added -async option to the Tcl socket command.
If the command is creating a client socket and the flag is present, the
client is connected asynchronously. If the option is absent (the default),
the client socket is connected synchronously, and the command returns only
when the connection has been completed or failed. This change was suggested
by Mark Diekhans. (JL)

3/13/96 (feature change) Modified the signature of Tcl_OpenTcpClient to
take an additional int argument, async. If nonzero, the client is connected
to the server asynchronously. If the value is zero, the connection is made
synchronously, and the call to Tcl_OpenTcpClient returns only when the
connection fails or succeeds. This change was suggested by Mark Diekhans. (JL)
*** INCOMPATIBILITY with Tcl 7.5b3, but not with Tcl 7.4 ***

3/14/96 (bug fix) "tclsh bogus_file_name" didn't print an error message. (JO)

3/14/96 (bug fix) Added new procedures to tclCkalloc.c so that libraries
and applications can be compiled with TCL_MEM_DEBUG even if Tcl isn't
(however, the converse is still not true).  Patches provided by Jan
Nijtmans. (JO)

3/15/96 (bug fix) Marked standard IO handles of a process as close-on-exec
to fix bug in Ultrix where exec was not sharing standard IO handles with
subprocesses. Fix suggested by Mark Diekhans. (JL)

3/15/96 (bug fix) Fixed asynchronous close mechanism so that it closes the
channel instead of leaking system resources. The manifestation was that Tcl
would eventually run out of file descriptors if it was handling a large
number of nonblocking sockets or pipes with high congestion. (JL)

3/15/96 (bug fix) Fixed tests so that they no longer leak file descriptors.
The manifestation was that Tcl would eventually run out of file descriptors
if the tests were rerun many times (> a hundred times on Solaris). (JL)

3/15/96 (bug fix) Fixed channel creation code so that it never creates
unnamed channels. This would cause a panic and core dump when the channel
was closed. (JL)

3/16/96 (bug fixes) Made lots of changes in configuration stuff to get
Tcl working under AIX (finally).  Tcl should now support the "load"
command under AIX and should work either with or without shared
libraries for Tcl and Tk. (JO)

3/21/96 (configuration improvement) Changed configure script so it
doesn't use version numbers (as in -ltcl7.5 and libtcl7.5.so) under
SunOS 4.1, where they don't work anyway.  (JO)

3/22/96 (new feature) Added C API Tcl_InterpDeleted that allows extension
writers to discover when an interpreter is being deleted. (JL)

3/22/96 (bug fix) The standard IO channels are now added to each
trusted interpreter as soon as the interpreter is created. This ensures
against the bug where a child would do IO before the master had done any,
and then the child is destroyed - the standard IO channels would be then
closed and the master would be unable to do any IO. (JL)

3/22/96 (bug fix) Made Tcl more robust against interpreter deletion, by
using Tcl_Preserve, Tcl_Release and Tcl_EventuallyFree to split the process
of interpreter deletion into two distinct phases. Also went through all of
Tcl and added calls to Tcl_Preserve and Tcl_Delete where needed. (JL)

3/22/96 (bug fix) Fixed several places where C code was reading and writing
into freed memory, especially during interpreter deletion. (JL)

3/22/96 (bug fix) Fixed very deep bug in Tcl_Release that caused memory to
be freed twice if the release callback did Tcl_Preserve and Tcl_Release on
the same memory as the chunk currently being freed. (JL)

3/22/96 (bug fix) Removed several memory leaks that would cause memory
buildup on half-K chunks in the generic IO level. (JL)

3/22/96 (bug fix) Fixed several core dumps which occurred when new
AssocData was being created during the cleanups in interpreter deletion.
The solution implemented now is to loop repeatedly over the AssocData until
none is left to clean up. (JL)

3/22/96 (bug fix) Fixed a bug in event handling which caused an infinite
loop if there were no files being watched and no timer. Fix suggested by
Jan Nijtmans. (JL)

3/22/96 (bug fix) Fixed Tcl_CreateCommand, Tcl_DeleteCommand to be more
robust if the interpreter is being deleted. Also fixed several order
dependency bugs in Tcl_DeleteCommand which kicked in when an interpreter
was being deleted. (JL)

3/26/96 (bug fix) Upon a "short read", the generic code no longer calls
the driver for more input. Doing this caused blocking on some platforms
even on nonblocking channels. Bug and fix courtesy Mark Roseman. (JL)

3/26/96 (new feature) Added 'package Tcltest' which is present only in
test versions of Tcl; this allows the testing commands to be loaded into
new interpreters besides the main one. (JL)

3/26/96 (restored feature) Recreated the Tcl_GetOpenFile C API. You can
now get a FILE * from a registered channel; Unix only. (JL)

3/27/96 (bug fix) The regular expression code did not support more
than 9 subexpressions.  It now supports up to 20. (SS)

4/1/96 (bug fixes) The CHANNEL_BLOCKED bit was being left on on a short
read, so that fileevents wouldn't fire correctly. Bug reported by Mark
Roseman.(JL, RJ)

4/1/96 (bug fix) Moved Tcl_Release to match Tcl_Preserve exactly, in
tclInterp.c; previously interpreters were being freed only conditionally
and sometimes not at all. (JL)

4/1/96 (bug fix) Fixed error reporting in slave interpreters when the
error message was being generated directly by C code. Fix suggested by
Viktor Dukhovni of ESM. (JL)

4/2/96 (bug fixes) Fixed a series of bugs in Windows sockets that caused
events to variously get lost, to get sent multiple times, or to be ignored
by the driver. The manifestation was blocking if the channel is blocking,
and either getting EAGAIN or infinite loops if the channel is nonblocking.
This series of bugs was found by Ian Wallis of Cisco. Now all tests (also
those that were previously commented out) in socket.test pass.  (JL, SS)

4/2/96 (feature change/bug fix) Eliminated network name support in
favor of better native name support.  Added "file split", "file join",
and "file pathtype" commands.  See the "file" man page for more
details. (SS)
*** INCOMPATIBILITY with Tcl 7.5b3, but not with Tcl 7.4 ***

4/2/96 (bug fix) Changed implementation of auto_mkindex so tclIndex
files will properly handle path names in a cross platform context. (SS)

4/5/96 (bug fix) Fixed Tcl_ReadCmd to use the channel buffer size as the
chunk size it reads, instead of a fixed 4K size. Thus, on large reads, the
user can set the channel buffer size to a large size and the read will
occur orders of magnitude faster. For example, on a 2MB file, reading in 4K
chunks took 34 seconds, while reading in 1MB chunks took 1.5 seconds (on a
SS-20). Problem identified and fix suggested by John Haxby of HP. (JL)

4/5/96 (bug fix) Fixed socket creation code to invoke gethostbyname only if
inet_addr failed (very unlikely). Before this change the order was reversed
and this made things much slower than they needed to be (gethostbyname
generally requires an RPC, which is slow). Problem identified and fix
suggested by John Loverso of OSF. (JL)

4/9/96 (feature change) Modified "auto" translation mode so that it
recognizes any of "\n", "\r" and "\r\n" in input as end of line, so
that a file can have mixed end-of-line sequences. It now outputs
the platform specific end of line sequence on each platform for files and
pipes, and for sockets it produces crlf in output on all platforms. (JL)
*** INCOMPATIBILITY with Tcl 7.5b3, but not with Tcl 7.4 ***

4/11/96 (new feature) Added -eofchar option to Tcl_SetChannelOption to allow
setting of an end of file character for input and output. If an input eof
char is set, it is recognized as EOF and further input from the channel is
not presented to the caller. If an output eof char is set, on output, that
byte is appended to the channel when it is closed. On Unix and Macintosh,
all channels start with no eof char set for input or output. On Windows,
files and pipes start with input and output eof chars set to Crlt-Z (ascii
26), and sockets start with no input or output eof char. (JL)
*** INCOMPATIBILITY with Tcl 7.5b3, but not with Tcl 7.4 ***

4/17/96 (bug fix) Fixed series of bugs with handling of crlf sequence split
across buffer boundaries in input, in AUTO mode. (JL, BW)

4/17/96 (test suite improvement) Fixed test suite so that tests that
depend on the availability of Unix commands such as echo, cat and others
are not run if these commands are not present. (JL)

4/17/96 (test suite improvement) The socket test now automatically starts,
on platformst that support exec, a separate process for remote testsing. (JL)

----------------- Released 7.5, 4/21/96 -----------------------

5/1/96 (bug fix) "file tail ~" did not correctly return the tail
portion of the user's home directory. (SS)

5/1/96 (bug fix) Fixed bug in TclGetEnv where it didn't lookup environment
variables correctly:  could confuse "H" and "HOME", for example.  (JO)

5/1/96 (bug fix) Changed to install tclConfig.sh under "make install-binaries",
not "make install-libraries".  (JO)

5/2/96 (bug fix) Changed pkg_mkIndex not to attempt to "load" a file unless
it has the standard shared library extension.  On SunOS, attempts to load
Tcl scripts cause the whole application to be aborted (there's no way to
get the error back into Tcl).  (JO)

5/7/96 (bug fix) Moved initScript in tclUnixInit.c to writable memory to
avoid potential core dumps. (JO)

5/7/96 (bug fix) Auto_reset procedure was removing procedure from init.tcl,
such as pkg_mkIndex.  (JO)

5/7/96 (bug fix) Fixed cast on socket address resolution code that
would cause a failure to connect on Dec Alphas. (JL)

5/7/96 (bug fix) Added "time", "subst" and "fileevent" commands to set of
commands available in a safe interpreter. (JL)

5/13/96 (bug fix) Preventing OS level handles for stdin, stdout and stderr
from being implicitly closed when the last reference to the standard
channel containing that handle is discarded when an interpreter is deleted.
Explicitly closing standard channels by using "close" still works. (JL)

5/21/96 (bug fix) Do not create channels for stdin, stdout and stderr on
Unix if the devices are closed. This prevents a duplicate channel name
panic later on when the fd is used to open a channel and the channel is
registered in an interpreter. (JL)

5/23/96 (bug fix) Fixed bug that prevented the use of standard channels in
interpreters created after the last interpreter was destroyed. In the sequence

	interp = Tcl_CreateInterp();
	Tcl_DeleteInterp(interp);
	interp = Tcl_CreateInterp();

channels for stdio would not be available in the second interpreter. (JL)

5/23/96 (bug fix) Fixed bug that allowed Tcl_MakeFileChannel to create new
channels with Tcl_Files in them that are already used by another channel.
This would cause core dumps when the Tcl_Files were being freed twice. (JL)

5/23/96 (bug fix) Fixed a logical timing bug that caused a standard channel
to be removed from the standard channel table too early when the channel
was being closed. If the channel was being flushed asynchronously, it could
get recreated before being actually destroyed, and the recreated channel
would contain the same Tcl_File as the one being closed, leading to
dangling pointers and core dumps. (JL)

5/27/96 (bug fix) Fixed a bug in Tcl_GetChannelOption which caused it to
always return a list of one element, a list of the settings, for
-translation and -eofchar options. Now correctly returns the value
described by the documentation (Mark Diekhans found this, thanks!). (JL)

5/30/96 (bug fix) Fixed a couple of syntax errors in io.test. (JL)

5/30/96 (bug fix) If a fileevent scripts gets an error, delete it before
causing a background error. This is to allow the error handler to reinstall
the fileevent and to prevent infinite loops if the event loop is reentered
in the error handler. (JL)

5/31/96 (bug fix) Channels now will get properly flushed on exit. (JL)

6/5/96 (bug fix) Changed Tcl_Ckalloc, Tcl_Ckfree, and Tcl_Ckrealloc to
Tcl_Alloc, Tcl_Free, and Tcl_Realloc.  Added documentation for these
routines now that they are officially supported.  Extension writers
should use these routines instead of free() and malloc(). (SS)

6/10/96 (bug fix) Changes the Tcl close command so that it no longer
waits on nonblocking pipes for the piped processes to exit; instead it
reaps them in the background. (JL)

6/11/96 (bug fix) Increased the length of the listen queue for server
sockets on Unix from 5 to 100. Some OSes will disregard this and reset it
to 5, but we should try to get as long a queue as we can, for performance
reasons. (JL)

6/11/96 (bug fix) Fixed windows sockets bug that caused a cascade of events
if the fileevent script read less than was available. Now reading less than
is available does not cause a flood of Tcl events. (JL, SS)

6/11/96 (bug fix) Fixed bug in background flushing on closed channels that
would prevent the last buffer from getting flushed. (JL)

6/13/96 (bug fix) Fixed bug in Windows sockets that caused a core dump if
a DLL linked with tcl.dll and referred to e.g. ntohs() without opening a
Tcl socket. The problem was that the indirection table was not being
initialized. (JL)

6/13/96 (bug fix) Fixed OS level resource leak that would occur when a
Tcl channel was still registered in some interpreter when the process
exits. Previously the channel was not being closed and the OS level handles
were not being released; the output was being flushed but the device was
not being closed. Now the device is properly closed. This was only a
problem on Win3.1 and MacOS. (JL, SS)

6/28/96 (bug fix) Fixed bug where transient errors were leaving an error
code around, so that it would erroneously get reported later. This bug was
exercised intermittently by closing a channel to a file on a very loaded
NFS server, or to a socket whose other end blocked. (JL, BW)

7/3/96 (bug fix) Fileevents declared in an interpreter are now deleted
when the channel is closed in that interpreter. Before this fix, the
fileevent would hang around until the channel is completely closed, and
would cause errors if events happened before the channel was closed. This
could happen in two cases: first if the channel is shared between several
interpreters, and second if an async flush is in progress that prevents the
channel from being closed until the flush finishes. (JL)

7/10/96 (bug fix) Fixed bugs in both "lrange" and "lreplace" commands
where too much white space was being removed. For example, the command
		lreplace {\}\     hello} end end
was returning "\}\", losing the significant space in the first list
element and corrupting the list. (JO)

7/20/96 (bug fix) The procedure pkg_mkIndex didn't work properly for
extensions that depend on Tk, because it didn't load Tk into the child
interpreter before loading the extension.  Now it loads Tk if Tk is
present in the parent. (JO)

7/23/96 (bug fix) Added compat version of strftime to fix crashes
resulting from bad implementations under Windows. (SS)

7/23/96 (bug fix) Standard implementations of gmtime() and localtime()
under Windows did not handle dates before 1970, so they were replaced
with a revised implementation. (SS)

7/23/96 (bug fix) Tcl would crash on exit under Borland 5.0 because
the global environ pointer was left pointing to freed memory. (SS)

7/29/96 (bug fix) Fixed memory leak in Tcl_LoadCmd that could occur if
a package's AppInit procedure called Tcl_StaticPackage to register
static packages. (JO)

8/1/96 (bug fix) Fixed a series of bugs in Windows sockets so that async
writebehind in the presence of read event handlers now works, and so that
async writebehind also works on sockets for which a read event handler was
declared and whose channels were then closed before the async write
finished. The bug was reported by John Loverso and Steven Wahl,
independently, test case supplied by John Loverso. (JL)

----------------- Released patch 7.5p1, 8/2/96 -----------------------

5/8/96 (new feature) Added Tcl_GetChannelMode C API for retrieving whether
a channel is open for reading and writing. (JL)

5/8/96 (API changes) Revised C APIs for channel drivers:
    - Removed all Tcl_Files from channel driver interface; you can now have
      channels that are not based on Tcl_Files.
    - Added channelReadyProc and watchChannelProc procedures to interface;
      these are used to implement event notification for channels.
    - Added getFileProc to channel driver, to allow the generic IO code
      to retrieve a Tcl_File from a channel (presumably if the channel
      uses Tcl_Files they will be stored inside its instanceData). (JL)
*** INCOMPATIBILITY with Tcl 7.5 ***

5/8/96 (API change) The Tcl_CreateChannel C API was modified to not take
Tcl_File arguments, and instead to take a mask specifying whether the
channel is readable and/or writable. (JL)
*** INCOMPATIBILITY with Tcl 7.5 ***

6/3/96 (bug fix) Made Tcl_SetVar2 robust against the case where the value
of the variable is a NULL pointer instead of "". (JL)

6/17/96 (bug fix) Fixed "reading uninitialized memory" error reported by
Purify, in Tcl_Preserve/Tcl_Release. (JL)

8/9/96 (bug fix) Fixed bug in init.tcl that caused incorrect error message
if the act of autoloading a procedure caused the procedure to be invoked
again. (JO)

8/9/96 (bug fix) Configure script produced bad library names and extensions
under SunOS and a few other platforms if the --disable-load switch was used.
(JO)

8/9/96 (bug fix) Tcl_UpdateLinkedVar generated an error if the variable
being updated was read-only. (JO)

8/14/96 (bug fix) The macintosh now supports synchronous socket
connections.  Other minor bugs were also fixed. (RJ)

8/15/96 (configuration improvement) Changed the file patchlevel.h
to be tclPatch.h.  This avoids conflict with the Tk file and is now
in 8.3 format on the Windows platform. (RJ)

8/20/96 (bug fix) Fixed core dump in interp alias command for interpreters
created with Tcl_CreateInterp (as opposed to with Tcl_CreateSlave). (JL)

8/20/96 (bug fix) No longer masking ECONNRESET on Windows sockets so
that the higher level of the IO mechanism sees the error instead of
entering an infinite loop. (JL)

8/20/96 (bug fix) Destroying the last interpreter no longer closes the
standard channels. (JL)

8/20/96 (bug fix) Closing one of the stdin, stdout or stderr channels and
then opening a new channel now correctly assigns the new channel as the
standard channel that was closed. (JL)

8/20/96 (bug fix) Added code to unix/tclUnixChan.c for using ioctl with
FIONBIO instead of fcntl with O_NONBLOCK, for those versions of Unix where
either O_NONBLOCK is not supported or implemented incorrectly. (JL)

8/21/96 (bug fix) Fixed "file extension" so it correctly returns the
extension on files like "foo..c" as "..c" instead of ".c". (SS)

8/22/96 (bug fix) If environ[] contains static strings, Tcl would core
dump in TclSetupEnv because it was trying to write NULLs into the actual
data in environ[]. Now we instead copy as appropriate. (JL)

8/22/96 (added impl) Added missing implementation of Tcl_MakeTcpClientChannel
for Windows platform. Code contributed by Mark Diekhans. (JL)

8/22/96 (new feature) Added a new memory allocator for the Macintosh
version of Tcl.  It's quite a bit faster than MetroWerk's version. (RJ)

8/26/96 (documentation update) Removed old change bars (for all changes
in Tcl 7.5 and earlier releases) from manual entries. (JO)

8/27/96 (enhancement) The exec and open commands behave better and work in 
more situations under Windows NT and Windows 95.  Documentation describes 
what is still lacking. (CS)

8/27/96 (enhancement) The Windows makefiles will now compile even if the
compiler is not in the path and/or the compiler's environment variables
have not been set up. (CS) 

8/27/96 (configuration improvement) The Windows resource files are 
automatically updated when the version/patch level changes.  The header file
now has a comment that reminds the user which other files must be manually
updated when the version/patch level changes. (CS)

8/28/96 (new feature) Added file manipulation features (copy, rename, delete,
mkdir) that are supported on all platforms. They are implemented as 
subcommands to the "file" command. See the documentation for the "file"
command for more information. (JH)

----------------- Released 7.6b1, 8/30/96 -----------------------

9/3/96 (bug fix) Simplified code so that standard channels are created
lazily, they are added to an interpreter lazily, and they are never added
to a safe interpreter. (JL)

9/3/96 (bug fix) Closing a channel after closing a standard channel, e.g.
stdout, would cause the implicit recreation of that standard channel. (JL)

9/3/96 (new feature) Now calling Tcl_RegisterChannel with a NULL
interpreter increments the refcount so that code outside any interpreter
can use channels that are also registered in interpreters, without worrying
that the channel may turn into a dangling pointer at any time. Calling
Tcl_UnregisterChannel with a NULL interpreter only decrements the recount
so that code outside any interpreter can safely declare it is no longer
interested in a channel. (JL)

9/4/96 (new features) Two changes to dynamic loading:
    - If the file name is empty in the "load" command and there is no
      statically loaded version of the package, a dynamically loaded
      version will be used if there is one.
    - Tcl_StaticPackage ignores redundant calls for the same package. (JO)

9/6/96 (bug fix) Platform specific procedures for manipulating files are
no longer macros and have been prefixed with "Tclp", such as TclpRenameFile.
Unix file code now handles symbolic links and other special files correctly.
The semantics of file copy and file rename has been changed so that if
a target directory exists, the source files will NOT be merged with the
existing files. (JH)

9/6/96 (bug fix) If standard channel is NULL, because Tcl cannot connect
to the standard channel, do not increment the refcount. The channel can
be NULL if there is for example no standard input. (JL)

9/6/96 (portability improvement) Changed parsing of backslash sequences
like \n to translate directly to absolute values like 0xa instead of
letting the compiler do the translation.  This guarantees that the
translation is done the same everywhere. (JO)

9/9/96 (bug fix) If channel is opened and not associated with any
interpreter, but Tcl decides to use it as one of the standard channels, it
became impossible to close the channel with Tcl_Close -- instead you had
to call Tcl_UnregisterChannel. Fixed now so that it's safe to call
Tcl_Close even when Tcl is using the channel as one of the standard ones. (JL)

9/11/96 (feature change) The Tcl library is now placed in the Tcl
shared libraries resource.  You no longer need to place the Tcl files
in your applications explicitly.  (RJ)

9/11/96 (feature change) Extensions no longer automatically have the
resource fork of the extension opened for it.  Instead you need to
use the tclMacLibrary.c file in your extension.  (RJ)
*** POTENTIAL INCOMPATIBILITY ***

9/12/96 (bug fix) The extension loading mechanism on the Macintosh now
looks at the 'cfrg' resource to determine where to load the code
fragment from.  This means FAT fragments should now work. (RJ)

9/18/96 (enhancement) The exec and open commands behave better and work in
more situations under Windows 3.X.  Documentation describes what is still
lacking.  (CS)

9/19/96 (bug fix) Fixed a panic which would occur if you delete a
non-existent alias before any aliases are created. Now instead correctly
returns an error that the alias is not found. (JL)

9/19/96 (bug fix) Slave interpreters could rename aliases and they would
not get deleted when the alias was being redefined. This led to dangling
pointers etc. (JL)

9/19/96 (bug fix) Fixed a panic where a hash table entry was being deleted
twice during alias management operations. (JL)

9/19/96 (bug fix) Fixed bug in event loop that could cause the input focus
in Tk to get confused during menu traversal, among other problems.  The
problem was related to handling of the "marker" when its event was
deleted. (JO)

9/26/96 (bug fix) Windows was losing EOF on a socket if the FD_CLOSE event
happened to precede any left over FD_READ events. Now correctly remembers
seeing FD_CLOSE, so that trailing FD_READ events are not discarded if they
do not contain any data. This allows Tcl to correctly get a zero read and
notice EOF. (JL)

9/26/96 (bug fix) Was not resetting READABLE state properly on sockets
under Windows if the driver discarded an FD_READ event because no data was
present. Now correctly resets the state. (JL)

9/30/96 (bug fix) Made EOF sticky on Windows sockets, so that fileevent
readable will fire repeatedly until the socket is closed. Previously the
fileevent fired only once. This could lead to never-closed connections if
the Tcl script in the fileevent wasn't closing the socket immediately. (JL)

10/2/96 (new feature) Improved the package loader:
    - Added new variable tcl_pkgPath, which holds the default
      directories under which packages are normally installed (each
      package goes in a separate subdirectory of a directory in
      $tcl_pkgPath).  These directories are included in auto_path by
      default.
    - Changed the package auto-loader to look for pkgIndex.tcl files 
      not only in the auto_path directories but also in their immediate
      children.  This should make it easier to install and uninstall
      packages (don't have to change auto_path or merge pkgIndex.tcl
      files). (JO)

10/3/96 (bug fix) Changed tclsh to look for tclshrc.tcl instead of
tclsh.rc on startup under Windows.  This is more consistent with wish and
uses the right extension. (SS)
*** POTENTIAL INCOMPATIBILITY ***

10/8/96 (bug fix) Convertclock does not parse 24-hour times of the
form "hhmm" correctly when hour = 00.  In the parse code, hour must be
>= 100 for minutes to be non-zero.  Thanks to Lint LaCour for this
bug fix. (RJ)

10/11/96 (bug fix) Under Windows, the pid command returned the process
handle instead of the process id. (SS)

----------------- Released 7.6, 10/16/96 -----------------------

10/29/96 (bug fix) Under Windows, sockets would consume 100% CPU time after
the first accept(), due to a typo. (JL)

10/29/96 (bug fix) Incorrect refcount management caused standard channels
not to get deleted at process exit or DLL unload time, causing a memory
leak of upwards of 20K each time. (JL)

11/7/96 (bug fix) Auto-exec didn't work on file names that contained
spaces. (JO)

11/8/96 (bug fix) Fixed core dump that would occur if more than one call
to Tcl_DeleteChannelHandler was made to delete a given channel handler. (JL)

11/8/96 (bug fix) Fixed test for return value in Tcl_Seek and Tcl_SeekCmd
to only treat -1 as error, instead of all negative numbers. (JL)

11/12/96 (bug fix) Do not blocking waiting for processes at the end of a
pipe during exit cleanup. (JL)

11/12/96 (bug fix) If we are in exit cleanup, do not close the system level
file descriptors 0, 1 and 2. Previously they were being closed which is
incorrect, in the embedded case. This led to weird behavior for programs
that want to interpose on I/O through the standard file descriptors (e.g.
Netscape Navigator). (JL)

11/15/96 (bug fix) Fixed core dump on Windows sockets due to dependency on
deletion order at exit. Now all socket functions check to see if sockets
are (still) initialized, before calling through function pointers. Before,
they would call and might end up calling unloaded object code. (JL)

11/15/96 (bug fix) Fixed core dump in Windows socket initialization routine
if sockets were not installed on the system. Before, it was not properly
checking the result of attempting to load the socket DLL, so it would call
through uninitialized function pointers. (JL)

11/15/96 (bug fix) Fixed memory leak in Windows sockets which left socket
DLL handle open and could hold the socket DLL in memory uneccessarily,
until a reboot. (JL)

12/4/96 (bug fix) Fixed bug in Macintosh socket code that could result
in lost data if a client was closed too soon after sending data. (RJ)

12/17/96 (bug fix) Fixed deadlock bug in Windows sockets due to losing an
event. This was happening because of an interaction between buffering and
nonblocking mode on sockets. Now switched to sockets being blocking by
default, so we are also no longer emulating blocking through a private
event loop. (JL)

1/21/97 (performance bug fix) Client TCP connections were slow to create
because getservbyname was always called on the port.  Now this is only
done if Tcl_GetInt fails. (BW)

1/21/97 (configuration fix) Made it possible to override TCL_PACKAGE_PATH
during make.  Previously it was only set during autoconf process.

1/29/97 (bug fix) Fixed some problems with the clock command that
impacted how dates were scaned after the year 2000. (RJ)

----------------- Released 7.6p2, 1/31/97 -----------------------

2/5/97 (bug fix) Fixed a bug where in CR-LF translation mode, \r bytes
in the input stream were not being handled correctly. (JL)

2/24/97 (bug fix) Fix bug with exec under Win32s not being able to create
stderr file which caused all execs to fail.  Fixed temp file leak under
Win32s.  Fixed optional parameter bug with SearchPath that only happened
under Win32s 1.25. (CCS)

----------------------------------------------------------
Changes for Tcl 7.6 go above this line.
Changes for Tcl 7.7 go below this line.
----------------------------------------------------------

5/8/96 (new feature) Added Tcl_Ungets C API for putting a sequence of bytes
into a channel's input buffer. This can be used for "push" model channels
where the input is obtained via callbacks instead of by request of the
generic IO code. No Tcl procedure yet. (JL)

11/15/96 (new feature) Implemented hidden commands. New C APIs:
	Tcl_HideCommand		-- hides an existing exposed command.
	Tcl_ExposeCommand	-- exposes an existing hidden command.
New tcl APIs:
	interp invokehidden	-- invokes a hidden command in a slave.
	interp hide		-- hides an existing exposed command.
	interp expose		-- exposes an existing hidden command.
	interp hidden		-- returns a list of hidden commands.
The implementation of Safe Tcl now uses the new hidden commands facility
to implement the safe base, instead of deleting the commands from a safe
interpreter. (JL)

11/15/96 (new feature) Implemented the safe base, a mechanism for
installing and requesting security policies, purely in Tcl code. Overloads
the package command to also allow an interpreter to "require" a policy. The
following new library commands are provided:
	tcl_safeCreateInterp	-- creates a slave an initializes the
				   policy mechanism.
	tcl_safeInitInterp	-- initializes an existing slave with the
				   policy mechanism.
	tcl_safeDeleteInterp	-- deletes a slave and deinitializes the
				   policy mechanism.
Added a new file to the library, safeinit.tcl, to hold implementation. (JL)
On 7/9/97, removed the policy loading mechanism from the Safe Base. Left
only the Safe Base aliases dealing with auto-loading and source. (JL)

12/6/96 (new feature) Implemented Tcl_Finalize, an API that should be
called by a process when it is done using Tcl. This API runs all the exit
handlers to allow them to clean up resources etc. (JL)

12/17/96 (new feature) Add an http Tcl script package to the Tcl library.
This package implements the client side of HTTP/1.0; the GET, HEAD,
and POST requests. (BW)

1/21/97 (new feature) Added a "marktrusted" subcommand to the "interp" and
to the interpreter object command. It removes the "safe" mark on an
interpreter and disables hard-wired checks for safety in the C sources. (JL)

1/21/97 (removed feature) Removed "vwait" from set of commands available in
a safe interpreter. (JL)

2/11/97 (new feature, bug fix) http package.  Added -accept to http_config
so you can set the Accept header.  Added -handler option to http_get so
you can supply your own data handler.  Also fixed POST operation to
set the correct MIME type on the request. (BW)

----------------------------------------------------------
Changes for Tcl 7.7 go above this line.
Changes for Tcl 8.0 go below this line.
----------------------------------------------------------

9/17/96 (bug fix) Using "upvar" it was possible to turn an array element
into an array itself.  Changed to disallow this; it was quirky and didn't
really work correctly anyway. (JO)

10/21/96 (new feature) The core of the Tcl interpreter has been replaced
with an on-the-fly compiler that translates Tcl scripts to bytecoded
instructions; a new interpreter then executes the bytecodes. The compiler
introduces only a few minor changes at the level of Tcl scripts. The biggest
changes are to expressions and lists.
    - A second level of substitutions is no longer done for expressions.
      This substantially improves their execution time. This means that
      the expression "$x*4" produces a different result than in the past
      if x is "$y+2". Fortunately, not much code depends on the old
      two-level semantics. Some expressions that do, such as
      "expr [join $list +]" can be recoded to work in Tcl8.0 by adding
      an eval: e.g., "eval expr [join $list +]".
    - Lists are now completely parsed on the first list operation to
      create a faster internal representation. In the past, if you had a
      misformed list but the erroneous part was after the point you
      inserted or extracted an element, then you never saw an error.
      In Tcl8.0 an error will be reported. This should only effect
      incorrect programs that took advantage of behavior of the old
      implementation that was not documented in the man pages.
Other changes to Tcl scripts are discussed in the web page at
http://www.sunlabs.com/research/tcl/compiler.html. (BL)
*** POTENTIAL INCOMPATIBILITY ***

10/21/96 (new feature) In earlier versions of Tcl, strings were used as a
universal representation; in Tcl 8.0 strings are replaced with Tcl_Obj
structures ("objects") that can hold both a string value and an internal
form such as a binary integer or compiled bytecodes. The new objects make it
possible to store information in efficient internal forms and avoid the
constant translations to and from strings that occurred with the old
interpreter. There are new many new C APIs for managing objects. Some of the
new library procedures for objects (such as Tcl_EvalObj) resemble existing
string-based procedures (such as Tcl_Eval) but take advantage of the
internal form stored in Tcl objects for greater speed. Other new procedures
manage objects and allow extension writers to define new kinds of objects.
See the manual entries doc/*Obj*.3 (BL)

10/24/96 (bug fix) Fixed memory leak on exit caused by some IO related
data structures not being deallocated on exit because their refcount was
artificially boosted. (JL)

10/24/96 (bug fix) Fixed core dump in Tcl_Close if called with NULL
Tcl_Channel. (JL)

11/19/96 (new feature) Added library procedures for finding word
breaks in strings in a platform specific manner.  See the library.n
manual entry for more information. (SS)

11/22/96 (feature improvements) Added support for different levels of
tracing during bytecode compilation and execution. This should help in
tracking down suspected problems with the compiler or with converting
existing code to use Tcl8.0. Two global Tcl variables, traceCompile
and traceExec, can be set to generate tracing information in stdout:
    - traceCompile: 0  no tracing (default)
                    1  trace compilations of top level commands and procs
                    2  trace and display instructions for all compilations
    - traceExec:    0  no tracing
                    1  trace only calls to Tcl procs
                    2  trace invocations of all commands including procs
                    3  detailed trace showing the result of each instruction
traceExec >= 2 provides a one line summary of each called command and
its arguments. Commands that have been "compiled away" such as set are
not shown. (BL)

11/30/96 (bug fix) The command "info nameofexecutable" could sometimes
return the name of a directory. (JO)

11/30/96 (feature improvements) Changed the code in library/init.tcl
that reads in pkgIndex.tcl so that (a) it reads the files from child
directories before those in the parent, so that the parent gets
precedence, and (b) it doesn't quit if there is an error in a
pkgIndex.tcl file;  instead, it prints an error message on standard
error and continues. (JO)

10/5/96 (feature improvements) Partial implementation of binary string
support: the ability for Tcl string values to contain embedded null bytes.
Changed the Tcl object-based APIs to take a byte pointer and length pair
instead of a null-terminated C string. Modified several object type managers
to support binary strings but not, for example, the list type manager.
Existing string-based C APIs are unchanged and will truncate binary
strings. Compiled scripts containing nulls are also truncated. (BL)

12/12/96 (feature change) Removed the commands "cp", "mkdir", "mv",
"rm", and "rmdir" from the Macintosh version of Tcl.  They were never
officially supported and their functionality is now available via
the file command. (RJ)

----------------- Released 8.0a1, 12/20/96 -----------------------

1/7/97 (bug fix) Under Windows, "file stat c:" was returning error instead
of stat for current dir on c: drive.

1/10/97 (new feature) Added Tcl_GetIndexFromObj procedure for quick
lookups of keyword arguments. (JO)

1/12/97 (new feature) Serial IO channel drivers for Windows and Unix,
available by using Tcl open command to open pseudo-files like "com1:" or
"/dev/ttya".  New option to Tcl fconfigure command for serial files:  
"-mode baud,parity,data,stop" to specify baud rate, parity, data bits, and
stop bits.  Serial IO is not yet available on Mac.

1/16/97 (feature change) Restored the Tcl7.x "two level substitution
semantics" for expressions. Expressions not enclosed in braces are
implemented, in general, by calling the expr command procedure
(Tcl_ExprObjCmd) at runtime after the Tcl interpreter has already done a
first round of substitutions. This is slow (about Tcl7.x speed) because new
code for the expression is generally compiled each time. However, if the
expression has only variable substitutions (and not command substitutions),
"optimistic" fast code is generated inline. This inline code will fail if a
second round of substitutions is needed (i.e., if the value of a substituted
variable itself requires more substitutions). The optimistic code will
catch the error and back off to call the slower but guaranteed correct
expr command procedure. (BL)

1/16/97 (feature improvements) Added Tcl_ExprLongObj and Tcl_ExprDoubleObj
to round out expression-related procedures. (BL)

1/16/97 (feature change) Under Windows, at startup the environment variables
"path", "comspec", and "windir" in any capitalization are converted
automatically to upper case.  The PATH variable could be spelled as path,
Path, PaTh, etc. and it makes programming rather annoying.  All other
environment variables are left alone. (CS)

1/20/97 (new features) Rewrote the "lsort" command:
    - The new version is based on reentrant merge sort code provided
      by Richard Hipp, so it eliminates the reentrancy and stability
      problems with the old qsort-based implementation.
    - The new version supports a -dictionary option for sorting, and
      it also supports a -index option for sorting lists using one
      element for comparison.
    - The new version is an object command, so it works well with the
      Tcl compiler, especially in conjunction with the new -index
      option.  When the -index option is used, this version of lsort
      is more than 100 times faster than the Tcl 7.6 lsort, which had
      to use the -command option to get the same effect. (JO)

1/20/97 (feature improvements) Added the improved debugging support for Tcl
objects prototyped by Karl Lehenbauer <[email protected]>.
If TCL_MEM_DEBUG is defined, the object creation calls use Tcl_DbCkalloc
directly in order to record the caller's source file name and line
number. (BL)

1/21/97 (removed feature) Desupported the tcl_precision variable: if
set, it is ignored.  Tcl now uses the full 17 digits of precision when
converting real numbers to strings (with the new object system real
numbers are rarely converted to strings so there is no efficiency
disadvantage to printing all 17 digits; the new scheme improves
accuracy and simplifies several APIs). (JO)
*** POTENTIAL INCOMPATIBILITY ***

1/21/97 (feature change) Removed the "interp" argument for the
procedures Tcl_GetStringFromObj, Tcl_StringObjAppend, and
Tcl_StringObjAppendObj.  Also removed the "interp" argument for
the updateStringProc procedure in Tcl_ObjType structures.  With
the tcl_precision changes above, these are no longer needed. (JO)
*** POTENTIAL INCOMPATIBILITY with Tcl 8.0a1, but not with Tcl 7.6 ***

1/22/97 (bug fix) Fixed http.tcl so that http_reset does not result in
an extra call to the command callback.  In addition, if the transaction
gets a premature eof, the state(status) is "eof", not "ok". (BW)

----------------- Released 8.0a2, 1/24/97 -----------------------

1/29/97 (feature change) Changed how two digit years are parsed in the
clock command.  The old interface just added 1900 which will seem
broken by the year 2000.  The new scheme follows the POSIX standard
and treats dates 70-99 as 1970-1999 and dates 00-38 as 2000-2038.  All
other two digit dates are undefined. (RJ)
*** POTENTIAL INCOMPATIBILITY ***

2/4/97 (bug fix) Fixed bug in clock code that dealt with relative
dates.  Using the relative month code you could get an invalid date
because it jumped into a non-existant day.  (For example, Jan 31
to Feb 31.)  The code now will return the last valid day of the
month in these situations.  Thanks to Hume Smith for sending in
this bug fix.  (RJ)

2/10/97 (feature change) Eliminated Tcl_StringObjAppend and 
Tcl_StringObjAppendObj procedures, replaced them with Tcl_AppendToObj
and Tcl_AppendStringsToObj procedures.  Added new procedure
Tcl_SetObjLength. (JO)
*** POTENTIAL INCOMPATIBILITY with Tcl 8.0a2, but not with Tcl 7.6 ***

2/10/97 (new feature) Added Tcl_WrongNumArgs procedure for generating
error messages about incorrect number of arguments. (JO)

2/11/97 (new feature, bug fix) http package.  Added -accept to http_config
so you can set the Accept header.  Added -handler option to http_get so
you can supply your own data handler.  Also fixed POST operation to
set the correct MIME type on the request. (BW)

2/22/97 (bug fix) Fixed bug that caused $tcl_platform(osVersion) to be
computed incorrectly under AIX. (JO)

2/25/97 (new feature, feature change) Added support for both int and long
integer objects. Added Tcl_NewLongObj/Tcl_GetLongFromObj/Tcl_SetLongFromObj
procedures and renamed the Tcl_Obj internalRep intValue member to
longValue. Tcl_GetIntFromObj now checks for integer values too large to
represent as non-long integers. Changed Tcl_GetAllObjTypes to
Tcl_AppendAllObjTypes. (BL)

3/5/97 (new feature) Added new Tcl_SetListObj procedure to round out
collection of procedures that set the type and value of existing Tcl
objects. (BL)

3/6/97 (new feature) Added -global flag for interp invokehidden. (JL)

3/6/97 (new feature, feature change) Added isNativeObjectProc field to the
Tcl_CmdInfo structure to indicate (when 1) if the command has an
object-based command procedure. Removed the nameLength arg from
Tcl_CreateObjCommand since command names can't contain null characters. (BL)

3/6/97 (bug fix) Fixed bug in "unknown" procedure that caused auto-
loading to fail on commands whose names begin with digits. (JO)

3/7/97 (bug fix) Auto-loading now works in Safe Base. Safe interpreters
only accept the Version 2 and onwards tclIndex files. (JL)

3/13/97 (bug fix) Fixed core dump due to interaction between aliases and
hidden commands. Bug found by Lindsay Marshall. (JL)

3/14/97 (bug fix) Fixed mac bugs relating to time.  The -gmt option
now adjusts the time in the correct direction.  (Thanks to Ed Hume for
reporting a fix to this problem.)  Also fixed file "mtime" etc. to
return times from GMT rather than local time zone.  (RJ)

3/18/97 (feature change) Declaration of objv in Tcl_ObjCmdProc function
changed from "Tcl_Obj *objv[]" to "Tcl_Obj *CONST objv[]".  All Tcl object
commands changed to use new declaration of objv.  Naive translation of
string-based command procs to object-based command procs could very easily
have yielded code where the contents of the objv array were changed.  This
is not a problem with string-based command procs, but doing something as
simple as objv[2] = objv[3] would corrupt the runtime stack and cause Tcl to
crash.  Introduced CONST in declaration of objv so that attempted assignment
of new pointer values to elements of the objv array will be caught by the
compiler. (CCS)
*** POTENTIAL INCOMPATIBILITY with Tcl 8.0a2 ***

3/19/97 (bug fix) Fixed panic due to object sharing. The root cause was
that old code was using Tcl_ResetResult instead of Tcl_ResetObjResult. (JL)

3/20/97 (new feature) Added a new subcommand for the file
command. file attributes filename can give a list of platform-specific
options (such as file/creator type on the Mac, permissions on Unix) or
set the values of them. Added a new subcommand for the file
command. file nativename name gives back the platform-specific form
for the file. This is useful when the filename is needed to pass to
the OS, such as exec under Windows 95 or AppleScript on the Mac. For
more info, see file.n. (SRP)

3/24/97 (removed feature) Removed the tcl_safePolicyPath procedure. Now
the policy path is computed from the auto_path by appending the directory
'policies' to each element. Also fixed several bugs in automatic tracking
of auto_path by computed policy path. (JL)
*** POTENTIAL INCOMPATIBILITY with Tcl 8.0a2 but not with Tcl 7.6 ***

4/8/97 (new feature) If the variable whose name is passed to lappend doesn't
already exist, and there are no value arguments, lappend now creates the
variable with an empty value instead of returning an error. Change suggested
by Tom Tromey. (BL)

4/9/97 (feature change) Changed the name of the TCL_PART1_NOT_PARSED flag to
TCL_PARSE_PART1. (BL)
*** POTENTIAL INCOMPATIBILITY with Tcl 8.0a2 but not with Tcl 7.6 ***

4/10/97 (bug fixes) Fixed various compilation-related bugs:
    - "UpdateStringOfCmdName should never be invoked" panic.
    - Bad code generated for expressions not in {}'s inside catch commands.
    - Segmentation fault in some command procedures when two argument
      object pointers refer to the same object.
    - Second level of substitutions were never done for expressions not
      in {}'s that consist of a single variable reference: e.g.,
      "set x 27; set bool {$x}; if $bool {puts foo}" would fail with error.
    - Bad code generated when code storage was grown while compiling some
      expressions: ones with compilation errors or consisting of only a
      variable reference.
    - Bugs involving multiple interpreters: wasn't checking that a
      procedure's code was compiled for the same interpreter as the one
      executing it, and didn't invalidate code on hidden-exposed command
      transitions.
    - "Bad stack top" panic when executing scripts that require a huge
      amount of stack space.
    - Incorrect sharing of code for procedure bodies, and procedure code
      deallocated before last execution of the procedure finished.
    - Fixed compilation of expression words in quotes. For example,
      if "0 < 3" {puts foo}.
    - Fixed performance bug in array set command with large assignments.
    - Tcl_SetObjLength segmentation fault setting length of empty object.
    - If Tcl_SetObjectResult was passed the same object as the interpreter's
      result object, it freed the object instead of doing nothing. Bug fix
      by Michael J. McLennan.
    - Tcl_ListObjAppendList inserted elements from the wrong list. Bug fix
      by Michael J. McLennan.
    - Segmentation fault if empty variable list was specified in a foreach
      command. Bug fix by Jan Nijtmans.
    - NULL command name was always passed to Tcl_CreateTrace callback
      procedure.
    - Wrong string representation generated for the value LONG_MIN.
      For example, expr 1<<31 printed incorrectly on a 32 bit machine.
    - "set {a($x)} 1" stored value in wrong variable.
    - Tcl_GetBooleanFromObj was not checking for garbage after a numeric
      value.
    - Garbled "bad operand type" error message when evaluating expressions
      not surrounded by {}'s. (BL)

4/16/97 (new feature) The expr command now has the "rand()" and
"srand()" functions for getting random numbers in expr. (RJ)

4/23/97 (bug fix) Fixed core dump in bgerror when the error handler command
deletes the current interpreter. Found by Juergen Schoenwald. (JL)

4/23/97 (feature change) The notifier interfaces have been redesigned
to make embedding in applications with external event loops possible.
A number of interfaces in the notifier and the channel drivers have
changed.  Refer to the Notifier.3 and CrtChannel.3 manual entries for
more details. (SS)
*** POTENTIAL INCOMPATIBILITY ***

4/23/97 (removed feature) The Tcl_File interfaces have been removed.
The Tcl_CreateFileHandler/Tcl_DeleteFileHandler interfaces now take
Unix fd's and are only supported on the Unix platform.
Tcl_GetChannelFile has been replaced with Tcl_GetChannelHandle.
Tcl_MakeFileChannel now takes a platform specific file handle. (SS)
*** POTENTIAL INCOMPATIBILITY ***

4/23/97 (removed feature) The modal timeout interface has been
removed (Tcl_CreateModalTimeout/Tcl_DeleteModalTimeout) (SS)
*** POTENTIAL INCOMPATIBILITY ***

4/23/97 (feature change) Channel drivers are now required to correctly
implement blocking behavior when they are in blocking mode. (SS)
*** POTENTIAL INCOMPATIBILITY ***

4/23/97 (new feature) Added the "binary" command for manipulating
binary strings. Also, changed the "puts", "gets", and "read" commands
to preserve embedded nulls.  (SS)

4/23/97 (new feature) Added tcl_platform(byteOrder) element to the
tcl_platform array to identify the native byte order for the current
host. (SS)

4/23/97 (bug fix) Fixed bug in date parsing around year boundaries. (SS)

4/24/97 (bug fix) In the process of copying a file owned by another user,
Tcl was changing the owner of the copy back to the owner of the original
file, therefore causing further file operations to fail because the current
user didn't own the copy anymore.  The owner of the copy is now left as the
current user. (CCS)

4/24/97 (feature change) Under Windows, don't automatically uppercase the
environment variable "windir" -- it's supposed to be lower case.  (CCS)

4/29/97 (new feature) Added namespace support based on a namespace
implementation by Michael J. McLennan of Lucent Technologies. A namespace
encapsulates a collection of commands and variables to ensure that they
won't interfere the commands and variables of other namespaces. The global
namespace holds all global variables and commands. Additional namespaces are
created with the new namespace command. The new variable command lets you
create Tcl variables inside a namespace. The names of Tcl variables and
commands may now be qualified by the name of the namespace containing them.
The key namespace-related commands are summarized below:
    - namespace ?eval? name arg ?arg...?
         Used to define the commands and variables in a namespace.
         Optionally creates the namespace.
    - namespace export ?-clear? ?pattern pattern...?
         Specifies which commands are exported from a namespace. These
         are the ones that can be imported into another namespace.
    - namespace import ?-force? ?pattern pattern...?
         Makes the specified commands accessible in the current namespace.
    - namespace current
         Returns the name of the current namespace.
    - variable name ?value? ?name ?value?...?
         Creates one or more namespace variables. (BTL)

5/1/97 (bug fix) Under Windows, file times were reported in GMT.  Should be
reported in local time. (CCS)

5/2/97 (feature change) Changed the name of the two Tcl variables used for
tracing bytecode compilation and execution to tcl_traceCompile and
tcl_traceExec respectively. These variables are now documented in the
tclvars man page. (BL)

5/5/97 (new feature) Support "end" as the index for "lsort -index". (BW)

5/5/97 (bug fixes) Cleaned up the way the http package resets connections (BW)

5/8/97 (feature change) Newly created Tcl objects now have a reference count
of zero instead of one. This simplifies C code that stores newly created
objects in Tcl variables or in data structures such as list objects. That C
code must increment the new object's reference count since the variable or
data structure will contain a long-term reference to the object. Formerly,
when new objects started out with reference count one, it was necessary to
decrement the new object's reference count after the store to make sure it
was left with the correct value; this is no longer necessary. (BL)

5/9/97 (new feature) Added the Tcl_GetsObj interface that takes an
object reference instead of a dynamic string (as in Tcl_Gets). (SS)

5/12/97 (new feature) Added Tcl_CreateAliasObj and Tcl_GetAliasObj C APIs
to allow an alias command to be created with a vector of Tcl_Obj structures
and to get the vector back later. (JL)

5/12/97 (feature change) Changed Tcl_ExposeCommand and Tcl_HideCommand to
leave an object result instead of a string result. (JL)

5/14/97 (feature change) Improved the handling of the interpreter result.
This is still either an object or a string, but the two values are now kept
consistent unless some C code reads or writes interp->result directly. See
the SetResult man page for details. Removed the Tcl_ResetObjResult
procedure. (BL)
*** POTENTIAL INCOMPATIBILITY with Tcl 8.0a2 ***

5/16/97 (new feature) Added "fcopy" command to move data between
channels.  Refer to the manual page for more information.  Removed the
"unsupported0" command since it is obsolete now.  (SS)

5/16/97 (new feature) Added Tcl_GetStringResult procedure to allow programs
to get an interpreter's result as a string. If the result was previously set
to an object, this procedure will convert the object to a string. Use of
Tcl_GetStringResult is intended to replace direct access to interp->result,
which is not safe. (BL)

5/20/97 (new features) Fixed "fcopy" to return the number of bytes
transferred in the blocking case.  Updated the http package to use
fcopy instead of unsupported0.  Added -timeout and -handler options to
http_get.  http_get is now blocking by default.  It is only non-blocking
if you supply a -command argument. (BW)

5/22/97 (bug fix) Fixed several bugs in the "lsort" command having to do
with the -dictionary option and the presence of numbers embedded in the
strings.  (JO)

----------------- Released 8.0b1, 5/27/97 -----------------------

6/2/97 (bug fix) Fixed bug in startup code that caused a problem in
finding the library files when they are installed in a directory
containing a space in the name. (SS)

6/2/97 (bug fix) Fixed bug in Unix notifier where the select mask was
not being cleared under some circumstances. (SS)

6/4/97 (bug fix) Fixed bug that prevented creation of Tk widgets in
namespaces. Tcl_CreateObjCommand and Tcl_CreateCommand now always create
commands in the global namespace unless the command names are qualified. Tcl
procedures continue to be created in the current namespace by default. (BL)

6/6/97 (new features) Added new namespace API procedures
Tcl_AppendExportList and Tcl_Export to allow C code to get and set a
namespace's export list. (BL)

6/11/97 (new feature) Added Tcl_ConcatObj. This object-based routine
parallels the string-based routine Tcl_Concat. (SRP)

6/11/97 (new feature) Added Tcl_SetObjErrorCode. This object-based
routines parallels the string-based routine Tcl_SetErrorCode. (SRP)

6/12/97 (bug fix) Fix the "unknown" procedure so that wish under Windows
will exec an external program, instead of always complaining "console1 not
opened for writing". (CCS)

6/12/97 (bug fix) Fixed core dump experienced by the following simple
script:
	interp create x
	x alias exec exec
	interp delete x
This panic was caused by not installing the new CmdDeleteProc when exec
got redefined by the alias creation step. Reported by Lindsay Marshal (JL)

6/13/97 (new features) Tcl objects newly created by Tcl_NewObj now have a
string representation that points to a shared heap string of length 1. (They
used to have NULL bytes and typePtr fields. This was treated as a special
case to indicate an empty string, but made type manager implementations
complex and error prone.) The new procedure Tcl_InvalidateStringRep is used
to mark an object's string representation invalid and to free any storage
associated with the old string representation. (BL)
*** POTENTIAL INCOMPATIBILITY with Tcl 8.0b1, but not with Tcl7.6 ***

6/16/97 (bug fix) Tcl_ScanCountedElement could leave braces unmatched
if the string ended with a backslash. (JO)

6/17/97 (bug fix) Fixed channel event bug where readable events would be
lost during recursive events loops if the input buffers contained
data. (SS)

6/17/97 (bug fix) Fixed bug in Windows socket code that didn't
reenable read events in the case where an external entity is also
reading from the socket. (SS)

6/18/97 (bug fix) Changed initial setting of the notifier service mode
to TCL_SERVICE_NONE to avoid unexpected event handling during
initialization. (SS)

6/19/97 (bug fix/feature change) The command callback to fcopy is now
called in case of errors during the background copy.  This adds a second,
optional argument to the callback that is the error string.  The callback
in case of errors is required for proper cleanup by the user of fcopy. (BW)
*** POTENTIAL INCOMPATIBILITY with Tcl 8.0b1, but not with Tcl 7.6 ***

6/19/97 (bug fix) Fixed a panic due to the following four line script:
	interp create x
	x alias foo bar
	x eval rename foo blotz
	x alias foo {}
The problem was that the interp code was not using the actual current name
of the command to be deleted as a result of un-aliasing foo. (JL)

6/19/97 (feature change) Pass interp down to the ChannelOption and
driver specific calls so system errors can be differentiated from syntax
ones. Changed Tcl_DriverGetOptionProc type. Affects Tcl_GetChannelOption,
TcpGetOptionProc,  TtyGetOptionProc, etc. (DL)
*** POTENTIAL INCOMPATIBILITY ***

6/19/97 (new feature) Added Tcl_BadChannelOption for use by by driver
specific option procedures (Set and Get) to return a complete and
meaningful error message. (DL)

6/19/97 (bug fixes) If a system call error occurs while doing an
fconfigure on tcp or tty/com channel: return the appropriate error
message (instead of the syntax error one or none). (Fixed for Unix and
most of the Win and Mac drivers). (DL)

6/20/97 (feature change) Eval is no longer assumed as the subcommand name
in namespace commands: you must now write "namespace eval nsName {...}".
Abbreviations of namespace subcommand names are now allowed. (BL)
*** POTENTIAL INCOMPATIBILITY with Tcl 8.0b1, but not with Tcl7.6 ***

6/20/97 (feature change) Changed the errorInfo traceback message for
compilation errors from "invoked from within" to "while compiling". (BL)

6/20/97 (bug fixes) Fixed various compilation-related bugs:
    - "UpdateStringOfCmdName should never be called" and
      "UpdateStringOfByteCode should never be called" panics.
    - Segfault in TclObjInterpProc getting procedure name after evaluation
      stack is reallocated (grown).
    - Could not use ":" at end of variable and command names.
    - Bad code generated for while and for commands with test expressions
      enclosed in quotes: e.g., "set i 0; while "$i > 5" {}".
    - Command trace procedures would crash if they did a Tcl_EvalObj that
      reallocated the evaluation stack.
    - Break and continue commands did not reset the interpreter result.
    - The Tcl_ExprXXX routines, both string- or object-based, always
      modified the interpreter result even if there was no error.
    - The argument parsing procedure used by several compile procedures
      always treated "]" as end of a command: e.g., "set a ]" would fail.
    - Changed errorInfo traceback message for compilation errors from 
      "invoked from within" to "while compiling".
    - Problem initializing Tcl object managers during interpreter creation.
    - Added check and error message if formal parameter to a procedure is
      an array element. (BL)

6/23/97 (new feature) Added "registry" package to allow manipulation
of the Windows system registry.  See manual entry for details. (SS)

6/24/97 (feature change) Converted http to a package and added the
http1.0 subdirectory of the Tcl script library.  This means you have
to do a "package require http" to use this, as advertised in the man page. (BW)
*** POTENTIAL INCOMPATIBILITY with Tcl 8.0b1, but not with Tcl 7.6 ***

6/24/97 (bug fix) Ensure that Tcl_Set/GetVar C APIs, when called without
TCL_LEAVE_ERR_MSG, don't touch the interp result. (DL)

6/26/97 (feature change) Changed name of Tcl_ExprStringObj to
Tcl_ExprObj. (BL)
*** POTENTIAL INCOMPATIBILITY with Tcl 8.0b1, but not with Tcl 7.6 ***

----------------- Released 8.0b2, 6/30/97 -----------------------

7/1/97 (new feature) TCL_BUILD_SHARED flag set in tclConfig.sh
when Tcl has been built with --enable-shared. A new tclLibObjs
make target, echoing the list of the .o's needed to build a tcl
library, is now provided. (DL)

7/1/97 (feature change) compat/getcwd.c removed and changed the
only place where getcwd is used so a new USEGETWD flag selects
the use of the replacement "getwd". Adding this flag is recommended
for SunOS 4 (because getcwd on SunOS 4 uses a pipe to pwd(1)!). (DL)

7/7/97 (feature change) The split command now supports binary data (i.e.,
null characters in strings). (BL)

7/7/97 (bug fix) string first returned the wrong result if the first
argument string was empty. (BL)

7/8/97 (bug fix) Fixed core dump in fcopy that could occur when a command
callback was supplied and an error or eof condition caused no background
activity.  A refcount bug triggered a panic in Tcl_ListObjAppendElement. (BW)

7/8/97 (bug fix) Relaxed the pattern matching on http_get so you do not
need a trailing path component.  You can now get away with just
http_get sunscript.sun.com					(BW)

7/9/97 (bug fix) Creating anonymous interpreters no longer smashes existing
commands with names similar to the generated name. Previously creating an
anonymous interpreter could smash an existing command, now it skips until
it finds a command name that isn't being used. (JL)

7/9/97 (feature change) Removed the policy management mechanism from the
Safe Base; left the aliases to source and load modules, and to do a limited
form of the "file" command. See entry of 11/15/96. (JL)

7/9/97 (bug fixes) Fixed various compilation-related bugs:
    - Line numbers in errorInfo now are the same as those in Tcl7.6 unless
there are compilation errors. Compilation error messages now include the
entire command in error.
    - Trailing ::s after namespace names weren't being ignored.
    - Could not refer to an namespace variable with an empty name using a
name of the form "n::". (BL)

7/9/97 (bug fix) Fixed bug in Tcl_Export that prevented you from exporting
from other than the current namespace. (BL)

7/9/97 (bug fix) env.test was removing env var needed for proper finding
of libraries in child process. (DL)

7/10/97 (bug fixes/new feature) Cleanup in Tcl_MakeSafe. Less information
is leaked to safe interps. Error message fixes for interp sub commands.
Likewise changes in safealias.tcl; tcl_safeCreateInterp can now be called
without argument to generate the slave name (like in interp create). (DL)

7/10/97 (bug fixes) Bytecode compiler now generates more detailed 
command location information: subcommands as well as commands now have
location information. This means command trace procedures now get the
correct source string for each command in their command parameter. (BL)

7/22/97 (bug fixes) Performance improvement in Safe interpreters
handling. Added new mask value to (tclInt.h) Interp.flags record. (DL)

7/22/97 (bug fix) Fixed panic in 'interp target {} foo'. This bug
was present since Tcl 7.6. (JL)

7/22/97 (bug fix) Fixed bug in compilation of procedures in namespaces: the
procedure's namespace must be used to look up compile procedures, not the
current namespace. (BL)

7/22/97 (bug fix) Use of the -channel option of http_get was not setting
the end of line translations mode on the channel, so copying binary data
with the -channel option was corrupting the result on non-unix platforms. (BW)

7/22/97 (bug fixes) file commands and ~user (seg fault and other
improper returns). (DL)

7/23/97 (feature change) Reenabled "vwait" in Safe Base. (JL)

7/23/97 (bug fixes) Fixed two bugs involving read traces on array variables
in procedures: trace procedures were sometimes not called, and reading
nonexistant array elements didn't create undefined element variables that
could later be defined by trace procedures. (BL)

7/24/97 (bug fix) Windows memory allocation performance was
superlinear in some cases.  Made the Mac allocator generic and changed
both the Mac and Windows platforms to use the new allocator instead of
malloc and free. (SS)

7/24/97 - 8/12/97 (bug fixes/change of features) Completely revamped safe
sourcing/loading (see safe.n) to hide pathnames, use virtual
paths tokens instead, improved security in several respects and made it
more tunable. Multi level interp loading can work too now. Package auto
loading now works in safe interps as long as the package directory is in 
the auto_path (no deep crawling allowed in safe interps). (DL)
*** POTENTIAL INCOMPATIBILITY with previous alpha and beta releases ***

7/24/97 (bug fixes) Made Tcl_SetVar* and Tcl_NewString* treat a NULL value
as an empty string. (This fixes hairy crash case where you would crash
because load command for other interps assumed presence of
errorInfo...). (DL)

7/28/97 (bug fix) Fixed pkg_mkIndex to understand namespaces.  It will
use the export list of a namespace and create auto_index entries for
all export commands.  Those names are in their fully qualified form in the
auto_index.  Therefore, I tweaked unknown to try both $cmd and ::$cmd.
Also fixed pkg_mkIndex so you can have "package require" commands inside
your packages.  These commands are ignored, which is mostly ok except
when you must load another package before loading yours because of
linking dependencies. (BW)

7/28/97 (bug fix) A variable created by the variable command now persists
until the namespace is destroyed or the variable is unset. This is true even
if the variable has not been initialized; these variables used to be
destroyed if an error occurred when accessing them. In addition, the "info
vars" command lists uninitialized namespace variables, while the "info
exists" command returns 0 for them. (BL)

7/29/97 (feature change)  Changed the http package to use the ::http
namespace. http_get renamed to http::geturl, http_config renamed to
http::config, http_formatQuery renamed to http::formatQuery.
It now provides the 2.0 version of the package.  
The 1.0 version is still available with the old names.
*** POTENTIAL INCOMPATIBILITY with Tcl 8.0b2 but not with Tcl 7.6 ***

7/29/97 (bug fix, new feature) Tcl_Main now uses Tcl objects internally to
preserve NULLs in commands and command output. Added new API procedure
Tcl_RecordAndEvalObj that resembles Tcl_RecordAndEval but takes an object
containing a command. (BL)

7/30/97 (bug fix) Tcl freed strings in the environ array even if it
did not allocate them. (SS)

7/30/97 (bug fix) If a procedure is renamed into a different namespace, it
now executes in the context of that namespace. (BL)

7/30/97 (bug fix) Prevent renaming of commands into and from namespaces as
part of hiding them. (JL)

7/31/97 (feature change) Moved the history command from C to tcl.
This uses the ::history namespace.  The "words" and "substitute" options
are no longer supported.  In addition, the "keep" option without a value
returns the current keep limit.  There is a new "clear" option.
The unknown command now supports !! again. (BW)
*** POTENTIAL INCOMPATIBILTY  ***

7/30/97 (bug fix) Made sure that a slave can not fool the master into
hiding the wrong command. Made sure we don't crash in hiding + namespaces
issues. (DL)

8/4/97 (bug fix) Concat, eval, uplevel, and similar commands were
incorrectly trimming trailing space characters from their arguments
even when the space characters were preceded by a backslash. (JO)

8/4/97 (bug fix) Removed the hard link between bgerror and tkerror.
Only bgerror is supported in tcl core. Tk will still look for a
tkerror but using regular tcl code for that feature. (DL)
*** POTENTIAL INCOMPATIBILTY with code relying on the hard link ***

8/6/97 (bug fix) Reduced size required for compiled bytecodes by using a
more compact encoding for the command pc-to-source map. (BL)

8/6/97 (new feature) Added support for additional compilation and execution
statistics when Tcl is compiled with the TCL_COMPILE_STATS flag. (BL)

8/7/97 (bug fix) Expressions not in {}s that have a comparison operator as
the topmost operator must be compiled out-of-line (call the expr cmd at
runtime) to properly support expr's two-level substitution semantics. An
example is "set a 2; set b {$a}; puts [expr $b == 2]". (BL)

8/11/97 (bug fix) The catch command would sometimes crash if a variable name
was given and the bytecode evaluation stack was grown when executing the
argument script. (BL)

8/12/97 (feature change) Reinstated the variable tcl_precision to control
the number of digits used when floating-point values are converted to
strings, with default of 12 digits.  However, had to make tcl_precision
shared among all interpreters (except that safe interpreters can't
modify it).  This makes the Tcl 8.0 behavior almost identical to 7.6
except that the default precision is 12 instead of 6. (JO)
*** POTENTIAL INCOMPATIBILITY ***

----------------- Released 8.0, 8/18/97 -----------------------

8/19/97 (bug fix) Minimal fix for glob -nocomplain bugs:
"glob -nocomplain unreadableDir/*" was generating an anonymous 
error. More in depth fixes will come with 8.1. (DL).

8/20/97 (bug fix) Removed check for FLT_MIN in binary command so
underflow conditions are handled by the compiler automatic
conversions. (SS)

8/20/97 (bug fixes) Fixed several compilation-related bugs:
    - Array cmd wasn't detecting arrays that, while compiled, do not yet
      exist (e.g., are marked undefined since they haven't been assigned
      to yet).
    - The GetToken procedure in tclCompExpr.c wasn't recognizing properly
      whether an integer token was invalid. For example, "0x$" is not
      a valid integer.
    - Performance bug in TclExecuteByteCode: the size of its stack frame
      was reduced by over 20% by moving errorInfo code elsewhere.
    - Uninitialized memory read error in tclCompile.c. (BL)

8/21/97 (bug fix) safe::interpConfigure now behave like Tk widget's
configure : it changes only the options you provide and you can get
the current value of any single option. New ?-nested boolean? and
?-statics boolean? for all safe::interp* commands but we still
accept (upward compatibility) the previously defined non valued
flags ?-noStatics? and ?-nestedLoadOk?. Improved the documentation. (DL).

8/22/97 (bug fix) Updated PrintDbl.3 to reflect the fact that the
tcl_precision variable is still used and that it is now shared by all
interpreters. (BL)

8/25/97 (bug fix) Fixed array access bug in IllegalExprOperandType
procedure in tclExecute.c: it was not properly supporting the || and &&
operators. (BL)

8/27/97 (bug fix) In cases where a channel handler was created with an
empty event mask while data was still buffered in the channel, the
channel code would get stuck spinning on a timer that would starve
idle handlers.  This mostly happened in Tk when reading from stdin. (SS)

9/4/97 (bug fix) Slave interps now inherit the maximum recursion limit
of their parent instead of starting back at the default. {nb: this still
does not prevent stack overflow by multi-interps recursion or aliasing} (DL)

9/11/97 (bug fix) An uninitialized variable in Tcl_WaitPid caused
pipes to fail to report eof properly under Windows. (SS)

9/12/97 (bug fix) "exec" was misidentifying some DOS executables as not 
executable. (CCS)

9/14/97 (bug fix) Was using the wrong structure in sizeof operation in
tclUnixChan.c. (JL)

9/15/97 (bug fix) Fixed notifier to break out of do-one-event loop if
Tcl_WaitForEvent returns 1, so that callers of Tcl_DoOneEvent will get
a chance to check whether the event just handled is significant. This
affected mainly recursive calls to Tcl_VWaitCmd; these did not get a
chance to notice that the variable they were waiting for has been set
and thus they didn't terminate the vwait. (JL, DL, SS)

9/15/97 (bug fix) Alignment problems in "binary format" would cause a
crash on some platforms when formatting floating point numbers. (SS)

9/15/97 (bug fix) Fixed bug in Macintosh socket code.  Now passes all
tests in socket.test that are not platform specific. (Thanks to Mark
Roseman for the pointer on the fix.)  (RJ)

9/18/97 (bug fix) Fixed bug -dictionary option of lsort that could
cause the compare function to run off the end of an array if the
number only contained 0's. (Thanks to Greg Couch for the report.) (RJ)

9/18/97 (bug fix) TclFinalizeEnvironment was not cleaning up 
properly. (DL, JI)

9/18/97 (bug fix) Fixed long-standing bug where an "array get" command
did not trigger traces on the array or its elements. (BL)

9/18/97 (bug fixes) Fixed compilation-related bugs:
    - Fixed errorInfo traceback information for toplevel coomands that
      contain nested commands.
    - In the expr command, && and || now accept boolean operands as well
      as numeric ones. (BL)

9/22/97 (bug fix) Fixed bug that prevented translation modes from being
set independently for input and output on sockets if input was "auto". (JL)

9/24/97 (bug fix) Tcl_EvalFile(3) and thus source(n) now works fine on
files containing NUL chars. (DL)

9/26/97 (bug fix) Fixed use of uninitialized memory in the environ array
that later could cause random core dumps. Applies to all platforms. (JL)

9/26/97 (bug fix) Fixed use of uninitialized memory in socket address data
structure under some circumstances. This could cause random core dumps.
This applies only to Unix. (JL)

9/26/97 (bug fix) Opening files on PC-NFS volumes would cause a hang
until the system timed after the file was closed. (SS)

10/6/97 (bug fix) The join(n) command, though objectified, was loosing
NULs in the joinString and in list elements after the 2nd one.
Now you can "join $list \0" for instance. (DL)

10/9/97 (bug fix) Under windows, if env(TMP) or env(TEMP) referred to a
non-existent directory, exec would fail when trying to create its temporary
files. (CCS)

10/9/97 (bug fix) Under mac and windows, "info hostname" would crash if 
sockets were installed but the hostname could not be determined anyhow.
Tcl_GetHostName() was returning NULL when it should have been returning 
an empty string. (CCS)

10/10/97 (bug fix) "file attribute /" returned error on windows. (CCS)

10/10/97 (bug fix) Fixed the auto_load procedure to handle procedures
defined in namespaces better.  Also fixed pgk_mkIndex so it sees procedures
defined in nested namespaces.  Index entries are still only made for
exported procedures. (BW)

10/13/97 (bug fix) On unix, for files with unknown group or owner
attributes, querying the "file attributes" would return an error rather than
returning the group's or owner's id number, although tha command accepts
numbers when setting the file's group or owner.  (CCS)

10/22/97 (bug fix) "fcopy" did not eval the callback script at the
global scope. (SS)

10/22/97 (bug fix) Fixed the signature of the CopyDone callback used in
the http package(s) so they can handle error cases properly. (BW)

10/28/97 (bug fixes) Fixed a problem where lappend would free the Tcl object
in a variable if a Tcl_ObjSetVar2 failed because of an error calling a trace
on the variable. (BL)

10/28/97 (bug fix) Changed binary scan to properly handle sign
extension of integers on 64-bit or larger machines. (SS)

11/3/97 (bug fixes) Fixed several bugs:
    - expressions such as "expr ($x)" must be compiled out-of-line
      (call the expr command procedure at runtime) to ensure the correct
      behavior when "$x" is an expression such as "5+10".
    - "array set a {}" now creates a new array var with an empty array
      value if the var didn't already exist.
    - "lreplace $foo end end" no longer returns an error (just an empty
      list) if foo is empty.
    - upvar will no longer create a variable in a namespace that refers
      to a variable in a procedure.
    - deleting a command trace within a command trace callback would
      make the code that calls traces to reference freed memory.
    - significantly sped up "string first" and "string last" (fix from
      [email protected]).
    - seg fault in Tcl_NewStringObj() when a NULL is passed as the byte
      pointer argument and Tcl is compiled with -DTCL_MEM_DEBUG.
    - documentation and error msg fixes. (BL)

11/3/97 (bug fix) Fixed a number of I/O bugs related to word sizes on
64-bit machines. (SS)

11/6/97 (bug fix) The exit code of the first process created by Tcl
on Windows was not properly reported due to an initialization
problem. (SS)

----------------- Released 8.0p1, 11/7/97 -----------------------

11/19/97 (bug fix) Fixed bug in linsert where it sometimes accidently
cleared out a shared argument list object. (BL).

11/19/97 (bug fix) Autoloading in namespaces was not working properly.
auto_mkindex is still not really namespace aware but most common
cases should now be handled properly (see init.test). (BW, DL)

11/20/97 (enhancement) Made the changes required by the new Apple
Universal Headers V.3.0, so that Tcl will compile with CW Pro 2.

11/24/97 (bug fix) Fixed tests in clock test suite that needed the
-gmt flag set.  Thanks to Jan Nijtmans for reporting the problem. (RJ)

----------------- Released 8.0p2, 11/25/97 -----------------------

12/3/97 (bug fix/optimization) Removed uneeded and potentially dangerous
instances of double evaluations if "if" and "expr" statements from
the library files. It is recommended that unless you need a double
evaluation you always use "expr {...}" instead of "expr ..." and
"if {...} ..." instead of "if ... ...". It will also be faster
thanks to the byte compiler. (DL)

---- Shipped as part of the plugin2.0b5 as 8.0p2Plugin1, Dec 8th 97 ----

12/8/97 (bug fix) Need to protect the newly accepted channel in an
accept callback on a socket, otherwise the callback may close it and
cause an error, which would cause the C code to attempt to close the
now deleted channel. Bumping the refcount assures that the channel sticks
around to be really closed in this case. (JL)

12/8/97 (bug fix) Need to protect the channel in a fileevent so that it
is not deleted before the fileevent handler returns. (CS, JL)

12/18/97 (bug fix) In the opt argument parsing package: if the description 
had only flags, the "too many arguments" case was not detected. The default
value was not used for the special "args" ending argument. (DL)

1/15/98 (improvement) Moved common part of initScript in common file.
Moved windows specific initialization to init.tcl so you can initialize
Tcl in windows without having to call Tcl_Init which is now only
searching for init.tcl {back ported from 8.1}. (DL)

---- Shipped as part of the plugin as 8.0p2Plugin2, Jan 15th 98 ----

5/27/98 (bug fix) Windows socket driver did not notice new data arriving
on nonblocking sockets until the event loop was entered. (SS)

5/27/98 (bug fix) Windows socket driver used FIONREAD, which is not
supported correctly by WinSock. (SS)

6/9/98 (bug fix) Generic channel code failed to report readable file
events on buffered data that was left behind by a gets or read that
did not consume all available data. (SS)

6/18/98 (bug fix) Compilation of loop expressions was too aggressive
and incorrectly inlined non-literal expressions. (SS)

6/18/98 (bug fix) "info var" and "info locals" incorrectly reported
the existence of compiler temporary variables. (SS)

6/18/98 (bug fix) Dictionary sorting used signed character
comparisons. (SS)

6/18/98 (bug fix) Compile procs corrupted the exception stack in some
cases. (SS)

6/18/98 (bug fix) Array set had erratic behavior when initializing a
variable from an empty value list. (SS)

6/18/98 (bug fix) The Windows registry package had a bad bounds check
that could lead to a crash. (SS)

6/18/98 (bug fix) The foreach compile proc did not correctly handle
non-local variable references. (SS)

6/25/98 (new features) Added name resolution hooks to support [incr Tcl].
There are new internal Tcl_*Resolver* APIs to add, query and remove the hooks. 
With this changes it should be possible to dynamically load [incr Tcl]
as an extension. (MM)

7/1/97 (bug fix) The commands "info args, body, default, procs" did
not correctly handle imported procedures. (RJ)

7/6/98 (improvement) pkg_mkIndex now implements the "package require"
command.  This makes it possible to create index files for packages
that require another package and then execute code from that package in
their file. Previously, this would throw an error because the required
package had not been loaded.  The -nopkgrequied flag is provided to
revert back to the old functionality. (EMS)

7/6/98 (improvement) back-ported the -direct flag from 8.1 into
pkg_mkIndex.  This results in pkgIndex.tcl files that contain direct
source or load commands instead of tclPkgSetup commands. (EMS)

7/6/98 (improvement) made changes to the AuxData items structures to support
storage of compiled scripts on disk. Also some related minor changes in
the compilation and execution engine. (EMS)

6/4/98 (enhancement) Added new internal routines to support inserting
and deleting from the stat, access, and open-file-channel mechanisms.
TclAccessInsertProc, TclStatInsertProc, & TclOpenFileChannelInsertProc
insert pointers to such routines; TclAccessDeleteProc, TclStatDeleteProc,
& TclOpenFileChannelDeleteProc delete pointers to such routines.  See
the file generic/tclIOUtils.c for more details. (SKS)
 
7/1/98 (enhancement) Added a new internal C variable
tclPreInitScript.  This is a pointer to a string that may hold an
initialization script; If this pointer is non-NULL it is evaluated in
Tcl_Init() prior to the built-in initialization script defined in the
file generic/tclInitScript.h.  (SKS)

7/6/98 (bug fix) Removed dead code in PlatformInitExitHandler so that
the TCL_LIBRARY value can be safely patched in binaries. (BW)

7/24/98 (enhancement) Incorporated a new version of auto_mkindex that
can support the [incr Tcl] class structures.  This version will index
all procedures in a source file, not just those where "proc" starts
at the beginning of the line.  If you want the old behavior, use the
auto_mkindex_old procedure. (MM)

7/24/98 (feature change) Changed the Windows registry key to be
HKEY_LOCAL_MACHINE\Software\Scriptics\Tcl\8.0, and to store the path
in the default value instead of "Root".  Also, this key can be
specified at compile time in case Tcl is being used in a different
context where it needs an alternate library path from the standard Tcl
installation. (SS)

7/24/98 (feature change) Changed the search order for init.tcl.  The
tcl_library variable can now be set before calling Tcl_Init to avoid
doing any searches.  If it isn't set, then Tcl checks
env(TCL_LIBRARY), the static value set at compile time, an install
directory relative to the executable, a source directory relative to
the executable, and a tcl directory relative to the source heirarchy
containing the executable.  See the comment at the top of
generic/tclInitScript.h for more details. (SS)

7/27/98 (config change) Changed the use of the DBGX flag in configure.in
and the makefile to be TCL_DBGX.  Users of tclConfig.sh may need to pass
this through their configure files with AC_SUBST. (BW)

729/98 (bug fix) Changed [info body] to return a copy of the body of a
compiled procedure instead of the body itself, to avoid invalidation
of the internal rep and loss of the byte-codes. (EMS)

8/5/98 (bug fix) The platform init code could walk off the end of a
buffer when reading the PkgPath registry value on Windows. (SS)

8/5/98 (Windows makefile change) Introduced a set of macros to deal with
exporting symbols when compiling DLLS on Windows. See win/README for
details. (EMS)

8/5/98 (addendum) Added a second Windows registry key under
HKEY_LOCAL_MACHINE\Software\Scriptics\Tcl\8.0, named "pkgPath".
This is a multi-string value used to initialize the tcl_pkgPath
variable. This is required if extension DLLs are in architecture specific
subdirectories. (SS)

8/6/98 (new feature) Added tcl_findLibrary to init.tcl for use by
extensions, including Tk.  This searches in a canonical way for
an extensions library directory and initialization file. (BW)

8/10/98 (bug fix) Imported commands used to get lost if the target
of the import was redefined.  Tcl_CreateCommand and Tcl_CreateObjCommand
were updated to restore import links. (Note that if you rename a command,
the import links move to the new name, and if you delete a command then
the import links get lost. These semantics have not changed.) (MC)

-------- Released 8.0.3 to the Tcl Consortium CD-ROM project, 8/10/98 ------

9/3/98 (bug fix) Tcl_Realloc was failing under Windows because the
GlobalReAlloc API was not correctly re-allocating blocks that were
32k+.  The fix was to use newer Win32 APIs (HeapAlloc, HeapFree, and
HeapReAlloc.) (BS)

10/5/98 (bug fix) Fixed bug in pkg_mkIndex that caused some files that do
a "package require" of packages in the Tcl libraries to give a warning like
	warning: "xx.tcl" provides more than one package ({xx 2.0} {yy 0.3})
and generate a broken pkgIndex.tcl file. (EMS)

10/5/98 (bug fix) Pkg_mkIndex was not doing a case-insensitive comparison
of extensions to determine whether to load or source a file. Thus, under
Windows, MYDLLNAME.DLL was sourced, and mydllname.dll loaded. (EMS)

10/5/98 (new feature) Created a new Tcl_Obj type, "procbody". This object's
internal representation holds a pointer to a Proc structure. Extended
TclCreateProc to take both strings and "procbody". (EMS)

10/13/98 (bug fix) The "info complete" command can now handle strings
with NULLs embedded.  Thanks to [email protected] 
for providing this fix. (RJ)

10/13/98 (bug fix) The "lsort -dictionary" command did not properly
handle some numbers starting with 0.  Thanks to Richard Hipp
<[email protected]> for submitting the fix to Scriptics. (RJ)

10/13/98 (bug fix) The function Tcl_SetListObj was creating an invalid
Tcl_Obj if the list had zero elements (despite what the comments said
it would do).  Thanks to Sebastian Wangnick for reporting the
problem. (RJ)

10/20/98 (new feature) Added tcl_platform(debug) element to the
tcl_platform array on Windows platform.  The existence of the debug
element of the tcl_platform array indicates that the particular Tcl
shell has been compiled with debug information.  Using
"info exists tcl_platform(debug)" a Tcl script can direct the
interpreter to load debug versions of DLLs with the load
command. (SKS)

10/20/98 (feature change) The Makefile and configure scripts have been
changed for IRIX to build n32 binaries instead of the old 32 abi
format.  If you have extensions built with the o32 abi's you will need
to update them to n32 for them to work with Tcl.  (RJ)
*** POTENTIAL INCOMPATIBILITY ***

10/23/98 (bug fix) tcl_findLibrary had a stray ] in one of the
pathnames it searched for the initialization script.  tclInitScript.h
was incorrectly adding the parent of tcl_library to tcl_pkgPath.  This
logic was moved into init.tcl, and the initialization of auto_path was
documented. Thanks to Donald Porter and Tom Silva for related
patches. (BW)

10/29/98 (bug fix) Fixed Tcl_NotifyChannel to use Tcl_Preserve instead
of Tcl_RegisterChannel so that 1) unregistered channels do not get
closed after their first fileevent, and 2) errors that occur during
close in a fileevent script are actually reflected by the close
command. (BW)

10/30/98 (bug fix) Overhaul of pkg_mkIndex to deal with transitive
package requires and packages split among scripts and binary files.
Also fixed ommision of global for errorInfo in tcl_findLibrary. (BW)

11/08/98 (bug fix) Fixed the resource command to always detect the
case where a file is opened a second time with the same permissions.
IM claims that this will always cause the same FileRef to be returned,
but in MacOS 8.1+, this is no longer the case, so we have to test for
this equality explicitly. (JI)

11/10/98 (feature change) When compiling with Metrowerk's MSL, use the
exit function from MSL rather than ExitToShell.  This allows MSL to
clean up its temporary files. Thanks to Vince Darley for this
improvement. (JI)

----------------- Released 8.0.4, 11/19/98 -----------------------

11/20/98 (bug fix) Handle possible NULL return in TclGetStdFiles. (RJ)

11/20/98 (bug fix) The dltests would not build on SGI.  They reported
that you could not mix n32 with 032 binaries.  The configure script
has been modified to get the EXTRA_CFLAGS from the tcl configure
script.  [Bug id: 840] (RJ)

12/3/98 (bug fix) Windows NT creates sockets so they are inheritable
by default.  Fixed socket code so it turns off this bit right after
creation so sockets aren't kept open by exec'ed processes. [Bug: 892]
Thanks to Kevin Kenny for this fix.  (SS)

1/11/98 (bug fix)  On HP, "info sharedlibextension" was returning 
empty string on static apps.  It now always returns ".sl".  (RJ)

1/28/99 (configure change) Now support -pipe option on gcc.  (RJ)

2/2/99 (bug fix) Fixed initialization problem on Windows where no
searching for init.tcl would be performed if the registry keys were
missing.  (stanton)

2/2/99 (bug fix) Added support for HKEY_PERFORMANCE_DATA and
HKEY_DYN_DATA keys in the "registry" command. (stanton)

2/2/99 (bug fix) ENOTSUP and EOPNOTSUPP clashed on some Linux
variants. (stanton)

2/2/99 (enhancement) The "open" command has been changed to use the
object interfaces. (stanton)

2/2/99 (bug fix) In some cases Tcl would crash due to an overflow of
the exception stack resulting from a missing byte code in some
expressions. (stanton)

2/2/99 (bug fix) Changed configure so Linux and IRIX shared libraries
are linked with the system libraries. (stanton)

2/2/99 (bug fix) Added support for BSDI 4.x (BSD/OS-4*) to the
configure script. (stanton)

2/2/99 (bug fix) Fixed bug where upvar could resurrect a namespace
variable after the namespace had been deleted. (stanton)

2/2/99 (bug fix) In some cases when creating variables, the
interpreter result was being modified even if the TCL_LEAVE_ERR_MSG
flag was set. (stanton)

2/2/99 (bug fix & new feature) Changed the socket drivers to properly
handle failures during an async socket connection.  Added a new
fconfigure option "-error" to retrieve the failure message.  See the
socket.n manual entry for details. (stanton)

2/2/99 (bug fix) Deleting a renamed interp alias could result in a
panic. (stanton)

2/2/99 (feature change/bug fix) Changed the behavior of "file
extension" so that it splits at the last period.  Now the extension of
a file like "foo..o" is ".o" instead of "..o" as in previous versions. 
*** POTENTIAL INCOMPATIBILITY ***
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted doc/DString.3.

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
'\"
'\" Copyright (c) 1993 The Regents of the University of California.
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\" 
'\" RCS: @(#) $Id: DString.3,v 1.2 1998/09/14 18:39:48 stanton Exp $
'\" 
.so man.macros
.TH Tcl_DString 3 7.4 Tcl "Tcl Library Procedures"
.BS
.SH NAME
Tcl_DStringInit, Tcl_DStringAppend, Tcl_DStringAppendElement, Tcl_DStringStartSublist, Tcl_DStringEndSublist, Tcl_DStringLength, Tcl_DStringValue, Tcl_DStringSetLength, Tcl_DStringFree, Tcl_DStringResult, Tcl_DStringGetResult \- manipulate dynamic strings
.SH SYNOPSIS
.nf
\fB#include <tcl.h>\fR
.sp
\fBTcl_DStringInit\fR(\fIdsPtr\fR)
.sp
char *
\fBTcl_DStringAppend\fR(\fIdsPtr, string, length\fR)
.sp
char *
\fBTcl_DStringAppendElement\fR(\fIdsPtr, string\fR)
.sp
\fBTcl_DStringStartSublist\fR(\fIdsPtr\fR)
.sp
\fBTcl_DStringEndSublist\fR(\fIdsPtr\fR)
.sp
int
\fBTcl_DStringLength\fR(\fIdsPtr\fR)
.sp
char *
\fBTcl_DStringValue\fR(\fIdsPtr\fR)
.sp
\fBTcl_DStringSetLength\fR(\fIdsPtr, newLength\fR)
.sp
\fBTcl_DStringFree\fR(\fIdsPtr\fR)
.sp
\fBTcl_DStringResult\fR(\fIinterp, dsPtr\fR)
.sp
\fBTcl_DStringGetResult\fR(\fIinterp, dsPtr\fR)
.SH ARGUMENTS
.AS Tcl_DString newLength
.AP Tcl_DString *dsPtr in/out
Pointer to structure that is used to manage a dynamic string.
.AP char *string in
Pointer to characters to add to dynamic string.
.AP int length in
Number of characters from string to add to dynamic string.  If -1,
add all characters up to null terminating character.
.AP int newLength in
New length for dynamic string, not including null terminating
character.
.AP Tcl_Interp *interp in/out
Interpreter whose result is to be set from or moved to the
dynamic string.
.BE

.SH DESCRIPTION
.PP
Dynamic strings provide a mechanism for building up arbitrarily long
strings by gradually appending information.  If the dynamic string is
short then there will be no memory allocation overhead;  as the string
gets larger, additional space will be allocated as needed.
.PP
\fBTcl_DStringInit\fR initializes a dynamic string to zero length.
The Tcl_DString structure must have been allocated by the caller.
No assumptions are made about the current state of the structure;
anything already in it is discarded.
If the structure has been used previously, \fBTcl_DStringFree\fR should
be called first to free up any memory allocated for the old
string.
.PP
\fBTcl_DStringAppend\fR adds new information to a dynamic string,
allocating more memory for the string if needed.
If \fIlength\fR is less than zero then everything in \fIstring\fR
is appended to the dynamic string;  otherwise \fIlength\fR
specifies the number of bytes to append.
\fBTcl_DStringAppend\fR returns a pointer to the characters of
the new string.  The string can also be retrieved from the
\fIstring\fR field of the Tcl_DString structure.
.PP
\fBTcl_DStringAppendElement\fR is similar to \fBTcl_DStringAppend\fR
except that it doesn't take a \fIlength\fR argument (it appends
all of \fIstring\fR) and it converts the string to a proper list element
before appending.
\fBTcl_DStringAppendElement\fR adds a separator space before the
new list element unless the new list element is the first in a
list or sub-list (i.e. either the current string is empty, or it
contains the single character ``{'', or the last two characters of
the current string are `` {'').
\fBTcl_DStringAppendElement\fR returns a pointer to the
characters of the new string.
.PP
\fBTcl_DStringStartSublist\fR and \fBTcl_DStringEndSublist\fR can be
used to create nested lists.
To append a list element that is itself a sublist, first
call \fBTcl_DStringStartSublist\fR, then call \fBTcl_DStringAppendElement\fR
for each of the elements in the sublist, then call
\fBTcl_DStringEndSublist\fR to end the sublist.
\fBTcl_DStringStartSublist\fR appends a space character if needed,
followed by an open brace;  \fBTcl_DStringEndSublist\fR appends
a close brace.
Lists can be nested to any depth.
.PP
\fBTcl_DStringLength\fR is a macro that returns the current length
of a dynamic string (not including the terminating null character).
\fBTcl_DStringValue\fR is a  macro that returns a pointer to the
current contents of a dynamic string.
.PP
.PP
\fBTcl_DStringSetLength\fR changes the length of a dynamic string.
If \fInewLength\fR is less than the string's current length, then
the string is truncated.
If \fInewLength\fR is greater than the string's current length,
then the string will become longer and new space will be allocated
for the string if needed.
However, \fBTcl_DStringSetLength\fR will not initialize the new
space except to provide a terminating null character;  it is up to the
caller to fill in the new space.
\fBTcl_DStringSetLength\fR does not free up the string's storage space
even if the string is truncated to zero length, so \fBTcl_DStringFree\fR
will still need to be called.
.PP
\fBTcl_DStringFree\fR should be called when you're finished using
the string.  It frees up any memory that was allocated for the string
and reinitializes the string's value to an empty string.
.PP
\fBTcl_DStringResult\fR sets the result of \fIinterp\fR to the value of
the dynamic string given by \fIdsPtr\fR.  It does this by moving
a pointer from \fIdsPtr\fR to \fIinterp->result\fR.
This saves the cost of allocating new memory and copying the string.
\fBTcl_DStringResult\fR also reinitializes the dynamic string to
an empty string.
.PP
\fBTcl_DStringGetResult\fR does the opposite of \fBTcl_DStringResult\fR.
It sets the value of \fIdsPtr\fR to the result of \fIinterp\fR and
it clears \fIinterp\fR's result.
If possible it does this by moving a pointer rather than by copying
the string.

.SH KEYWORDS
append, dynamic string, free, result
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































Deleted doc/Notifier.3.

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
'\"
'\" Copyright (c) 1995-1997 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\" 
'\" RCS: @(#) $Id: Notifier.3,v 1.2 1998/09/14 18:39:49 stanton Exp $
'\" 
.so man.macros
.TH Notifier 3 8.0 Tcl "Tcl Library Procedures"
.BS
.VS
.SH NAME
Tcl_CreateEventSource, Tcl_DeleteEventSource, Tcl_SetMaxBlockTime, Tcl_QueueEvent, Tcl_DeleteEvents, Tcl_WaitForEvent, Tcl_SetTimer, Tcl_ServiceAll, Tcl_ServiceEvent, Tcl_GetServiceMode, Tcl_SetServiceMode \- the event queue and notifier interfaces

.SH SYNOPSIS
.nf
\fB#include <tcl.h>\fR
.sp
\fBTcl_CreateEventSource\fR(\fIsetupProc, checkProc, clientData\fB)\fR
.sp
\fBTcl_DeleteEventSource\fR(\fIsetupProc, checkProc, clientData\fB)\fR
.sp
\fBTcl_SetMaxBlockTime\fR(\fItimePtr\fB)\fR
.sp
\fBTcl_QueueEvent\fR(\fIevPtr, position\fR)
.VS
.sp
\fBTcl_DeleteEvents\fR(\fIdeleteProc, clientData\fR)
.sp
int
\fBTcl_WaitForEvent\fR(\fItimePtr\fR)
.sp
\fBTcl_SetTimer\fR(\fItimePtr\fR)
.sp
int
\fBTcl_ServiceAll\fR()
.sp
int
\fBTcl_ServiceEvent\fR(\fIflags\fR)
.sp
int
\fBTcl_GetServiceMode\fR()
.sp
int		
\fBTcl_SetServiceMode\fR(\fImode\fR)
.VE

.SH ARGUMENTS
.AS Tcl_EventDeleteProc milliseconds
.AS Tcl_EventSetupProc *setupProc
.AP Tcl_EventSetupProc *setupProc in
Procedure to invoke to prepare for event wait in \fBTcl_DoOneEvent\fR.
.AP Tcl_EventCheckProc *checkProc in
Procedure for \fBTcl_DoOneEvent\fR to invoke after waiting for
events.  Checks to see if any events have occurred and, if so,
queues them.
.AP ClientData clientData in
Arbitrary one-word value to pass to \fIsetupProc\fR, \fIcheckProc\fR, or
\fIdeleteProc\fR.
.AP Tcl_Time *timePtr in
Indicates the maximum amount of time to wait for an event.  This
is specified as an interval (how long to wait), not an absolute
time (when to wakeup).  If the pointer passed to \fBTcl_WaitForEvent\fR
is NULL, it means there is no maximum wait time:  wait forever if
necessary.
.AP Tcl_Event *evPtr in
An event to add to the event queue.  The storage for the event must
have been allocated by the caller using \fBTcl_Alloc\fR or \fBckalloc\fR.
.AP Tcl_QueuePosition position in
Where to add the new event in the queue:  \fBTCL_QUEUE_TAIL\fR,
\fBTCL_QUEUE_HEAD\fR, or \fBTCL_QUEUE_MARK\fR.
.AP int flags in
What types of events to service.  These flags are the same as those
passed to \fBTcl_DoOneEvent\fR.
.AP Tcl_EventDeleteProc *deleteProc in
Procedure to invoke for each queued event in \fBTcl_DeleteEvents\fR.
.VS
.AP int mode in
Inidicates whether events should be serviced by \fBTcl_ServiceAll\fR.
Must be one of \fBTCL_SERVICE_NONE\fR or \fBTCL_SERVICE_ALL\fR.
.VE
.BE

.SH INTRODUCTION
.PP
.VS
The interfaces described here are used to customize the Tcl event
loop.  The two most common customizations are to add new sources of
events and to merge Tcl's event loop with some other event loop, such
as one provided by an application in which Tcl is embedded.  Each of
these tasks is described in a separate section below.
.VE
.PP
The procedures in this manual entry are the building blocks out of which
the Tcl event notifier is constructed.  The event notifier is the lowest
layer in the Tcl event mechanism.  It consists of three things:
.IP [1]
Event sources: these represent the ways in which events can be
generated.  For example, there is a timer event source that implements
the \fBTcl_CreateTimerHandler\fR procedure and the \fBafter\fR
command, and there is a file event source that implements the
\fBTcl_CreateFileHandler\fR procedure on Unix systems.  An event
source must work with the notifier to detect events at the right
times, record them on the event queue, and eventually notify
higher-level software that they have occurred.  The procedures
\fBTcl_CreateEventSource\fR, \fBTcl_DeleteEventSource\fR,
and \fBTcl_SetMaxBlockTime\fR, \fBTcl_QueueEvent\fR, and
\fBTcl_DeleteEvents\fR are used primarily by event sources.
.IP [2]
The event queue: there is a single queue for the whole application,
containing events that have been detected but not yet serviced.  Event
sources place events onto the queue so that they may be processed in
order at appropriate times during the event loop. The event queue
guarantees a fair discipline of event handling, so that no event
source can starve the others.  It also allows events to be saved for
servicing at a future time.
.VS
\fBTcl_QueueEvent\fR is used (primarily
by event sources) to add events to the event queue and 
\fBTcl_DeleteEvents\fR is used to remove events from the queue without
processing them.
.IP [3]
The event loop: in order to detect and process events, the application
enters a loop that waits for events to occur, places them on the event
queue, and then processes them.  Most applications will do this by
calling the procedure \fBTcl_DoOneEvent\fR, which is described in a
separate manual entry.
.PP
Most Tcl applications need not worry about any of the internals of
the Tcl notifier.  However, the notifier now has enough flexibility
to be retargeted either for a new platform or to use an external event
loop (such as the Motif event loop, when Tcl is embedded in a Motif
application).  The procedures \fBTcl_WaitForEvent\fR and
\fBTcl_SetTimer\fR are normally implemented by Tcl, but may be
replaced with new versions to retarget the notifier (the \fBTcl_Sleep\fR,
\fBTcl_CreateFileHandler\fR, and \fBTcl_DeleteFileHandler\fR must
also be replaced; see CREATING A NEW NOTIFIER below for details).
The procedures \fBTcl_ServiceAll\fR, \fBTcl_ServiceEvent\fR,
\fBTcl_GetServiceMode\fR, and \fBTcl_SetServiceMode\fR are provided
to help connect Tcl's event loop to an external event loop such as
Motif's.
.SH "NOTIFIER BASICS"
.VE
.PP
The easiest way to understand how the notifier works is to consider
what happens when \fBTcl_DoOneEvent\fR is called.
\fBTcl_DoOneEvent\fR is passed a \fIflags\fR argument that indicates
what sort of events it is OK to process and also whether or not to
block if no events are ready.  \fBTcl_DoOneEvent\fR does the following
things:
.IP [1]
Check the event queue to see if it contains any events that can
be serviced.  If so, service the first possible event, remove it
.VS
from the queue, and return.  It does this by calling
\fBTcl_ServiceEvent\fR and passing in the \fIflags\fR argument.
.VE
.IP [2]
Prepare to block for an event.  To do this, \fBTcl_DoOneEvent\fR
invokes a \fIsetup procedure\fR in each event source.
The event source will perform event-source specific initialization and
.VS
possibly call \fBTcl_SetMaxBlockTime\fR to limit how long
.VE
\fBTcl_WaitForEvent\fR will block if no new events occur.
.IP [3]
Call \fBTcl_WaitForEvent\fR.  This procedure is implemented differently
on different platforms;  it waits for an event to occur, based on the
information provided by the event sources.
It may cause the application to block if \fItimePtr\fR specifies
an interval other than 0.
\fBTcl_WaitForEvent\fR returns when something has happened,
such as a file becoming readable or the interval given by \fItimePtr\fR
expiring.  If there are no events for \fBTcl_WaitForEvent\fR to
wait for, so that it would block forever, then it returns immediately
and \fBTcl_DoOneEvent\fR returns 0.
.IP [4]
Call a \fIcheck procedure\fR in each event source.  The check
procedure determines whether any events of interest to this source
occurred.  If so, the events are added to the event queue.
.IP [5]
Check the event queue to see if it contains any events that can
be serviced.  If so, service the first possible event, remove it
from the queue, and return.
.IP [6]
See if there are idle callbacks pending. If so, invoke all of them and
return.
.IP [7]
Either return 0 to indicate that no events were ready, or go back to
step [2] if blocking was requested by the caller.

.SH "CREATING A NEW EVENT SOURCE"
.PP
An event source consists of three procedures invoked by the notifier,
plus additional C procedures that are invoked by higher-level code
to arrange for event-driven callbacks.  The three procedures called
by the notifier consist of the setup and check procedures described
above, plus an additional procedure that is invoked when an event
is removed from the event queue for servicing.
.PP
The procedure \fBTcl_CreateEventSource\fR creates a new event source.
Its arguments specify the setup procedure and check procedure for
the event source.
\fISetupProc\fR should match the following prototype:
.CS
typedef void Tcl_EventSetupProc(
	ClientData \fIclientData\fR,
	int \fIflags\fR);
.CE
The \fIclientData\fR argument will be the same as the \fIclientData\fR
argument to \fBTcl_CreateEventSource\fR;  it is typically used to
point to private information managed by the event source.
The \fIflags\fR argument will be the same as the \fIflags\fR
argument passed to \fBTcl_DoOneEvent\fR except that it will never
be 0 (\fBTcl_DoOneEvent\fR replaces 0 with \fBTCL_ALL_EVENTS\fR).
\fIFlags\fR indicates what kinds of events should be considered;
if the bit corresponding to this event source isn't set, the event
source should return immediately without doing anything.  For
example, the file event source checks for the \fBTCL_FILE_EVENTS\fR
bit.
.PP
\fISetupProc\fR's job is to make sure that the application wakes up
when events of the desired type occur.  This is typically done in a
platform-dependent fashion.  For example, under Unix an event source
might call \fBTcl_CreateFileHandler\fR; under Windows it might
request notification with a Windows event.  For timer-driven event
sources such as timer events or any polled event, the event source
can call \fBTcl_SetMaxBlockTime\fR to force the application to wake
up after a specified time even if no events have occurred.
.VS
If no event source calls \fBTcl_SetMaxBlockTime\fR
then \fBTcl_WaitForEvent\fR will wait as long as necessary for an
event to occur; otherwise, it will only wait as long as the shortest
interval passed to \fBTcl_SetMaxBlockTime\fR by one of the event
sources.  If an event source knows that it already has events ready to
report, it can request a zero maximum block time.  For example, the
setup procedure for the X event source looks to see if there are
events already queued.  If there are, it calls
\fBTcl_SetMaxBlockTime\fR with a 0 block time so that
\fBTcl_WaitForEvent\fR does not block if there is no new data on the X
connection.
.VE
The \fItimePtr\fR argument to \fBTcl_WaitForEvent\fR points to
a structure that describes a time interval in seconds and
microseconds:
.CS
typedef struct Tcl_Time {
	long \fIsec\fR;
	long \fIusec\fR;
} Tcl_Time;
.CE
The \fIusec\fR field should be less than 1000000.
.PP
.VS
Information provided to \fBTcl_SetMaxBlockTime\fR
is only used for the next call to \fBTcl_WaitForEvent\fR; it is
discarded after \fBTcl_WaitForEvent\fR returns.
.VE
The next time an event wait is done each of the event sources'
setup procedures will be called again, and they can specify new
information for that event wait.
.PP
.VS
If the application uses an external event loop rather than
\fBTcl_DoOneEvent\fR, the event sources may need to call
\fBTcl_SetMaxBlockTime\fR at other times.  For example, if a new event
handler is registered that needs to poll for events, the event source
may call \fBTcl_SetMaxBlockTime\fR to set the block time to zero to
force the external event loop to call Tcl.  In this case,
\fBTcl_SetMaxBlockTime\fR invokes \fBTcl_SetTimer\fR with the shortest
interval seen since the last call to \fBTcl_DoOneEvent\fR or
\fBTcl_ServiceAll\fR.
.PP
In addition to the generic procedure \fBTcl_SetMaxBlockTime\fR, other
platform-specific procedures may also be available for
\fIsetupProc\fR, if there is additional information needed by
\fBTcl_WaitForEvent\fR on that platform.  For example, on Unix systems
the \fBTcl_CreateFileHandler\fR interface can be used to wait for file events.
.VE
.PP
The second procedure provided by each event source is its check
procedure, indicated by the \fIcheckProc\fR argument to
\fBTcl_CreateEventSource\fR.  \fICheckProc\fR must match the
following prototype:
.CS
typedef void Tcl_EventCheckProc(
	ClientData \fIclientData\fR,
	int \fIflags\fR);
.CE
The arguments to this procedure are the same as those for \fIsetupProc\fR.
\fBCheckProc\fR is invoked by \fBTcl_DoOneEvent\fR after it has waited
for events.  Presumably at least one event source is now prepared to
queue an event.  \fBTcl_DoOneEvent\fR calls each of the event sources
in turn, so they all have a chance to queue any events that are ready.
The check procedure does two things.  First, it must see if any events
have triggered.  Different event sources do this in different ways.
.PP
If an event source's check procedure detects an interesting event, it
must add the event to Tcl's event queue.  To do this, the event source
calls \fBTcl_QueueEvent\fR.  The \fIevPtr\fR argument is a pointer to
a dynamically allocated structure containing the event (see below for
more information on memory management issues).  Each event source can
define its own event structure with whatever information is relevant
to that event source.  However, the first element of the structure
must be a structure of type \fBTcl_Event\fR, and the address of this
structure is used when communicating between the event source and the
rest of the notifier.  A \fBTcl_Event\fR has the following definition:
.CS
typedef struct Tcl_Event {
    Tcl_EventProc *\fIproc\fR;
    struct Tcl_Event *\fInextPtr\fR;
};
.CE
The event source must fill in the \fIproc\fR field of
the event before calling \fBTcl_QueueEvent\fR.
The \fInextPtr\fR is used to link together the events in the queue
and should not be modified by the event source.
.PP
An event may be added to the queue at any of three positions, depending
on the \fIposition\fR argument to \fBTcl_QueueEvent\fR:
.IP \fBTCL_QUEUE_TAIL\fR 24
Add the event at the back of the queue, so that all other pending
events will be serviced first.  This is almost always the right
place for new events.
.IP \fBTCL_QUEUE_HEAD\fR 24
Add the event at the front of the queue, so that it will be serviced
before all other queued events.
.IP \fBTCL_QUEUE_MARK\fR 24
Add the event at the front of the queue, unless there are other
events at the front whose position is \fBTCL_QUEUE_MARK\fR;  if so,
add the new event just after all other \fBTCL_QUEUE_MARK\fR events.
This value of \fIposition\fR is used to insert an ordered sequence of
events at the front of the queue, such as a series of
Enter and Leave events synthesized during a grab or ungrab operation
in Tk.
.PP
.VS
When it is time to handle an event from the queue (steps 1 and 4
above) \fBTcl_ServiceEvent\fR will invoke the \fIproc\fR specified
.VE
in the first queued \fBTcl_Event\fR structure.
\fIProc\fR must match the following prototype:
.CS
typedef int Tcl_EventProc(
	Tcl_Event *\fIevPtr\fR,
	int \fIflags\fR);
.CE
The first argument to \fIproc\fR is a pointer to the event, which will
be the same as the first argument to the \fBTcl_QueueEvent\fR call that
added the event to the queue.
The second argument to \fIproc\fR is the \fIflags\fR argument for the
.VS
current call to \fBTcl_ServiceEvent\fR;  this is used by the event source
.VE
to return immediately if its events are not relevant.
.PP
It is up to \fIproc\fR to handle the event, typically by invoking
one or more Tcl commands or C-level callbacks.
Once the event source has finished handling the event it returns 1
to indicate that the event can be removed from the queue.
If for some reason the event source decides that the event cannot
be handled at this time, it may return 0 to indicate that the event
.VS
should be deferred for processing later;  in this case \fBTcl_ServiceEvent\fR
.VE
will go on to the next event in the queue and attempt to service it.
There are several reasons why an event source might defer an event.
One possibility is that events of this type are excluded by the
\fIflags\fR argument.
For example, the file event source will always return 0 if the
\fBTCL_FILE_EVENTS\fR bit isn't set in \fIflags\fR.
Another example of deferring events happens in Tk if
\fBTk_RestrictEvents\fR has been invoked to defer certain kinds
of window events.
.PP
.VS
When \fIproc\fR returns 1, \fBTcl_ServiceEvent\fR will remove the
event from the event queue and free its storage.
Note that the storage for an event must be allocated by
the event source (using \fBTcl_Alloc\fR or the Tcl macro \fBckalloc\fR)
before calling \fBTcl_QueueEvent\fR, but it
will be freed by \fBTcl_ServiceEvent\fR, not by the event source.
.PP
\fBTcl_DeleteEvents\fR can be used to explicitly remove one or more
events from the event queue.  \fBTcl_DeleteEvents\fR calls \fIproc\fR
for each event in the queue, deleting those for with the procedure
returns 1.  Events for which the procedure returns 0 are left in the
queue.  \fIProc\fR should match the following prototype:
.CS
typedef int Tcl_EventDeleteProc(
	Tcl_Event *\fIevPtr\fR,
	ClientData \fIclientData\fR);
.CE
The \fIclientData\fR argument will be the same as the \fIclientData\fR
argument to \fBTcl_DeleteEvents\fR; it is typically used to point to
private information managed by the event source.  The \fIevPtr\fR will
point to the next event in the queue.
.VE

.SH "CREATING A NEW NOTIFIER"
.PP
The notifier consists of all the procedures described in this manual
entry, plus \fBTcl_DoOneEvent\fR and \fBTcl_Sleep\fR, which are
.VS
available on all platforms, and \fBTcl_CreateFileHandler\fR and
\fBTcl_DeleteFileHandler\fR, which are Unix-specific.  Most of these
procedures are generic, in that they are the same for all notifiers.
However, five of the procedures are notifier-dependent:
\fBTcl_SetTimer\fR, \fBTcl_Sleep\fR, \fBTcl_WaitForEvent\fR,
\fBTcl_CreateFileHandler\fR and \fBTcl_DeleteFileHandler\fR.  To
support a new platform or to integrate Tcl with an
application-specific event loop, you must write new versions of these
procedures.
.PP
\fBTcl_WaitForEvent\fR is the lowest-level procedure in the notifier;
it is responsible for waiting for an ``interesting'' event to occur or
for a given time to elapse.  Before \fBTcl_WaitForEvent\fR is invoked,
each of the event sources' setup procedure will have been invoked.
The \fItimePtr\fR argument to
\fBTcl_WaitForEvent\fR gives the maximum time to block for an event,
based on calls to \fBTcl_SetMaxBlockTime\fR made by setup procedures
and on other information (such as the \fBTCL_DONT_WAIT\fR bit in
\fIflags\fR).
.PP
Ideally, \fBTcl_WaitForEvent\fR should only wait for an event
to occur; it should not actually process the event in any way.
Later on, the
event sources will process the raw events and create Tcl_Events on
the event queue in their \fIcheckProc\fR procedures.
However, on some platforms (such as Windows) this isn't possible;
events may be processed in \fBTcl_WaitForEvent\fR, including queuing
Tcl_Events and more (for example, callbacks for native widgets may be
invoked).  The return value from \fBTcl_WaitForEvent\fR must be either
0, 1, or \-1.  On platforms such as Windows where events get processed in
\fBTcl_WaitForEvent\fR, a return value of 1 means that there may be more
events still pending that haven't been processed.  This is a sign to the
caller that it must call \fBTcl_WaitForEvent\fR again if it wants all
pending events to be processed. A 0 return value means that calling
\fBTcl_WaitForEvent\fR again will not have any effect: either this is a
platform where \fBTcl_WaitForEvent\fR only waits without doing any event
processing, or \fBTcl_WaitForEvent\fR knows for sure that there are no
additional events to process (e.g. it returned because the time
elapsed).  Finally, a return value of \-1 means that the event loop is
no longer operational and the application should probably unwind and
terminate.  Under Windows this happens when a WM_QUIT message is received;
under Unix it happens when \fBTcl_WaitForEvent\fR would have waited
forever because there were no active event sources and the timeout was
infinite.
.PP
If the notifier will be used with an external event loop, then it must
also support the \fBTcl_SetTimer\fR interface.  \fBTcl_SetTimer\fR is
invoked by \fBTcl_SetMaxBlockTime\fR whenever the maximum blocking
time has been reduced.  \fBTcl_SetTimer\fR should arrange for the
external event loop to invoke \fBTcl_ServiceAll\fR after the specified
interval even if no events have occurred.  This interface is needed
because \fBTcl_WaitForEvent\fR isn't invoked when there is an external
event loop.  If the
notifier will only be used from \fBTcl_DoOneEvent\fR, then
\fBTcl_SetTimer\fR need not do anything.
.PP
On Unix systems, the file event source also needs support from the
notifier.  The file event source consists of the
\fBTcl_CreateFileHandler\fR and \fBTcl_DeleteFileHandler\fR
procedures, which are described elsewhere.
.PP
The \fBTcl_Sleep\fR and \fBTcl_DoOneEvent\fR interfaces are described
elsewhere.
.PP
The easiest way to create a new notifier is to look at the code
for an existing notifier, such as the files \fBunix/tclUnixNotfy.c\fR
or \fBwin/tclWinNotify.c\fR in the Tcl source distribution.

.SH "EXTERNAL EVENT LOOPS"
.PP
The notifier interfaces are designed so that Tcl can be embedded into
applications that have their own private event loops.  In this case,
the application does not call \fBTcl_DoOneEvent\fR except in the case
of recursive event loops such as calls to the Tcl commands \fBupdate\fR
or \fBvwait\fR.  Most of the time is spent in the external event loop
of the application.  In this case the notifier must arrange for the
external event loop to call back into Tcl when something
happens on the various Tcl event sources.  These callbacks should
arrange for appropriate Tcl events to be placed on the Tcl event queue.
.PP
Because the external event loop is not calling \fBTcl_DoOneEvent\fR on
a regular basis, it is up to the notifier to arrange for
\fBTcl_ServiceEvent\fR to be called whenever events are pending on the
Tcl event queue.  The easiest way to do this is to invoke
\fBTcl_ServiceAll\fR at the end of each callback from the external
event loop.  This will ensure that all of the event sources are
polled, any queued events are serviced, and any pending idle handlers
are processed before returning control to the application.  In
addition, event sources that need to poll for events can call
\fBTcl_SetMaxBlockTime\fR to force the external event loop to call
Tcl even if no events are available on the system event queue.
.PP
As a side effect of processing events detected in the main external
event loop, Tcl may invoke \fBTcl_DoOneEvent\fR to start a recursive event
loop in commands like \fBvwait\fR.  \fBTcl_DoOneEvent\fR will invoke
the external event loop, which will result in callbacks as described
in the preceding paragraph, which will result in calls to
\fBTcl_ServiceAll\fR.  However, in these cases it is undesirable to
service events in \fBTcl_ServiceAll\fR.  Servicing events there is
unnecessary because control will immediately return to the
external event loop and hence to \fBTcl_DoOneEvent\fR, which can
service the events itself.  Furthermore, \fBTcl_DoOneEvent\fR is
supposed to service only a single event, whereas \fBTcl_ServiceAll\fR
normally services all pending events.  To handle this situation,
\fBTcl_DoOneEvent\fR sets a flag for \fBTcl_ServiceAll\fR
that causes it to return without servicing any events.
This flag is called the \fIservice mode\fR;
\fBTcl_DoOneEvent\fR restores it to its previous value before it returns.
.PP
In some cases, however, it may be necessary for \fBTcl_ServiceAll\fR
to service events
even when it has been invoked from \fBTcl_DoOneEvent\fR.  This happens
when there is yet another recursive event loop invoked via an
event handler called by \fBTcl_DoOneEvent\fR (such as one that is
part of a native widget).  In this case, \fBTcl_DoOneEvent\fR may not
have a chance to service events so \fBTcl_ServiceAll\fR must service
them all.  Any recursive event loop that calls an external event
loop rather than \fBTcl_DoOneEvent\fR must reset the service mode so
that all events get processed in \fBTcl_ServiceAll\fR.  This is done
by invoking the \fBTcl_SetServiceMode\fR procedure.  If
\fBTcl_SetServiceMode\fR is passed \fBTCL_SERVICE_NONE\fR, then calls
to \fBTcl_ServiceAll\fR will return immediately without processing any
events.  If \fBTcl_SetServiceMode\fR is passed \fBTCL_SERVICE_ALL\fR,
then calls to \fBTcl_ServiceAll\fR will behave normally.
\fBTcl_SetServiceMode\fR returns the previous value of the service
mode, which should be restored when the recursive loop exits.
\fBTcl_GetServiceMode\fR returns the current value of the service
mode.
.VE

.SH KEYWORDS
event, notifier, event queue, event sources, file events, timer, idle, service mode
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted doc/OpenFileChnl.3.

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
'\"
'\" Copyright (c) 1996-1997 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: OpenFileChnl.3,v 1.2 1998/09/14 18:39:49 stanton Exp $
.so man.macros
.TH Tcl_OpenFileChannel 3 8.0 Tcl "Tcl Library Procedures"
.BS
'\" Note:  do not modify the .SH NAME line immediately below!
.SH NAME
Tcl_OpenFileChannel, Tcl_OpenCommandChannel, Tcl_MakeFileChannel, Tcl_GetChannel, Tcl_RegisterChannel, Tcl_UnregisterChannel, Tcl_Close, Tcl_Read, Tcl_Gets, Tcl_Write, Tcl_Flush, Tcl_Seek, Tcl_Tell, Tcl_Eof, Tcl_InputBlocked, Tcl_InputBuffered, Tcl_GetChannelOption, Tcl_SetChannelOption \- buffered I/O facilities using channels
.SH SYNOPSIS
.nf
\fB#include <tcl.h>\fR
.sp
typedef ... Tcl_Channel;
.sp
Tcl_Channel
\fBTcl_OpenFileChannel\fR(\fIinterp, fileName, mode, permissions\fR)
.sp
Tcl_Channel
\fBTcl_OpenCommandChannel\fR(\fIinterp, argc, argv, flags\fR)
.VS
.sp
Tcl_Channel
\fBTcl_MakeFileChannel\fR(\fIhandle, readOrWrite\fR)
.VE
.sp
Tcl_Channel
\fBTcl_GetChannel\fR(\fIinterp, channelName, modePtr\fR)
.sp
void
\fBTcl_RegisterChannel\fR(\fIinterp, channel\fR)
.sp
int
\fBTcl_UnregisterChannel\fR(\fIinterp, channel\fR)
.sp
int
\fBTcl_Close\fR(\fIinterp, channel\fR)
.sp
int
\fBTcl_Read\fR(\fIchannel, buf, toRead\fR)
.sp
int
\fBTcl_Gets\fR(\fIchannel, lineRead\fR)
.sp
int
\fBTcl_GetsObj\fR(\fIchannel, lineObjPtr\fR)
.sp
int
\fBTcl_Write\fR(\fIchannel, buf, toWrite\fR)
.sp
int
\fBTcl_Flush\fR(\fIchannel\fR)
.sp
int
\fBTcl_Seek\fR(\fIchannel, offset, seekMode\fR)
.sp
int
\fBTcl_Tell\fR(\fIchannel\fR)
.sp
int
\fBTcl_GetChannelOption\fR(\fIinterp, channel, optionName, optionValue\fR)
.sp
int
\fBTcl_SetChannelOption\fR(\fIinterp, channel, optionName, newValue\fR)
.sp
int
\fBTcl_Eof\fR(\fIchannel\fR)
.sp
int
\fBTcl_InputBlocked\fR(\fIchannel\fR)
.sp
int
\fBTcl_InputBuffered\fR(\fIchannel\fR)
.sp
.SH ARGUMENTS
.AS Tcl_ChannelType newClientProcPtr in
.AP Tcl_Interp *interp in
Used for error reporting and to look up a channel registered in it.
.AP char *fileName in
The name of a local or network file.
.AP char *mode in
Specifies how the file is to be accessed.  May have any of the
values allowed for the \fImode\fR argument to the Tcl
\fBopen\fR command.
For \fBTcl_OpenCommandChannel\fR, may be NULL.
.AP int permissions in
POSIX-style permission flags such as 0644.
If a new file is created, these permissions will be set on the
created file.
.AP int argc in
The number of elements in \fIargv\fR.
.AP char **argv in
Arguments for constructing a command pipeline.
These values have the same meaning as the non-switch arguments
to the Tcl \fBexec\fR command.
.AP int flags in
Specifies the disposition of the stdio handles in pipeline: OR-ed
combination of \fBTCL_STDIN\fR, \fBTCL_STDOUT\fR, \fBTCL_STDERR\fR,
and \fBTCL_ENFORCE_MODE\fR. If \fBTCL_STDIN\fR is set, stdin for
the first child in the pipe is the pipe channel, otherwise it is the same
as the standard input of the invoking process; likewise for
\fBTCL_STDOUT\fR and \fBTCL_STDERR\fR. If \fBTCL_ENFORCE_MODE\fR is not set,
then the pipe can redirect stdio handles to override the stdio handles for
which \fBTCL_STDIN\fR, \fBTCL_STDOUT\fR and \fBTCL_STDERR\fR have been set.
If it is set, then such redirections cause an error.
.VS
.AP ClientData handle in
Operating system specific handle for I/O to a file. For Unix this is a
file descriptor, for Windows it is a HANDLE.
.AP int readOrWrite in
OR-ed combination of \fBTCL_READABLE\fR and \fBTCL_WRITABLE\fR to indicate
what operations are valid on \fIhandle\fR.
.VE
.AP int *modePtr out
Points at an integer variable that will receive an OR-ed combination of
\fBTCL_READABLE\fR and \fBTCL_WRITABLE\fR denoting whether the channel is
open for reading and writing.
.AP Tcl_Channel channel in
A Tcl channel for input or output.  Must have been the return value
from a procedure such as \fBTcl_OpenFileChannel\fR.
.AP char *buf in
An array of bytes in which to store channel input, or from which
to read channel output.
.AP int len in
The length of the input or output.
.AP int atEnd in
If nonzero, store the input at the end of the input queue, otherwise store
it at the head of the input queue.
.AP int toRead in
The number of bytes to read from the channel.
.AP Tcl_DString *lineRead in
A pointer to a Tcl dynamic string in which to store the line read from the
channel.  Must have been initialized by the caller.  The line read
will be appended to any data already in the dynamic string.
.AP Tcl_Obj *linePtrObj in
A pointer to a Tcl object in which to store the line read from the
channel.  The line read will be appended to the current value of the
object. 
.AP int toWrite in
The number of bytes to read from \fIbuf\fR and output to the channel.
.AP int offset in
How far to move the access point in the channel at which the next input or
output operation will be applied, measured in bytes from the position
given by \fIseekMode\fR.  May be either positive or negative.
.AP int seekMode in
Relative to which point to seek; used with \fIoffset\fR to calculate the new
access point for the channel. Legal values are \fBSEEK_SET\fR,
\fBSEEK_CUR\fR, and \fBSEEK_END\fR.
.AP char *optionName in
The name of an option applicable to this channel, such as \fB\-blocking\fR.
May have any of the values accepted by the \fBfconfigure\fR command.
.AP Tcl_DString *optionValue in
Where to store the value of an option or a list of all options and their
values. Must have been initialized by the caller.
.AP char *newValue in
New value for the option given by \fIoptionName\fR.
.BE

.SH DESCRIPTION
.PP
The Tcl channel mechanism provides a device-independent and
platform-independent mechanism for performing buffered input
and output operations on a variety of file, socket, and device
types.
The channel mechanism is extensible to new channel types, by
providing a low level channel driver for the new type; the channel driver
interface is described in the manual entry for \fBTcl_CreateChannel\fR. The
channel mechanism provides a buffering scheme modelled after
Unix's standard I/O, and it also allows for nonblocking I/O on
channels.
.PP
The procedures described in this manual entry comprise the C APIs of the
generic layer of the channel architecture. For a description of the channel
driver architecture and how to implement channel drivers for new types of
channels, see the manual entry for \fBTcl_CreateChannel\fR.

.SH TCL_OPENFILECHANNEL
.PP
\fBTcl_OpenFileChannel\fR opens a file specified by \fIfileName\fR and
returns a channel handle that can be used to perform input and output on
the file. This API is modelled after the \fBfopen\fR procedure of
the Unix standard I/O library.
The syntax and meaning of all arguments is similar to those
given in the Tcl \fBopen\fR command when opening a file.
If an error occurs while opening the channel, \fBTcl_OpenFileChannel\fR
returns NULL and records a POSIX error code that can be
retrieved with \fBTcl_GetErrno\fR.
In addition, if \fIinterp\fR is non-NULL, \fBTcl_OpenFileChannel\fR
leaves an error message in \fIinterp->result\fR after any error.
.PP
The newly created channel is not registered in the supplied interpreter; to
register it, use \fBTcl_RegisterChannel\fR, described below.
If one of the standard channels, \fBstdin, stdout\fR or \fBstderr\fR was
previously closed, the act of creating the new channel also assigns it as a
replacement for the standard channel.

.SH TCL_OPENCOMMANDCHANNEL
.PP
\fBTcl_OpenCommandChannel\fR provides a C-level interface to the
functions of the \fBexec\fR and \fBopen\fR commands.
It creates a sequence of subprocesses specified
by the \fIargv\fR and \fIargc\fR arguments and returns a channel that can
be used to communicate with these subprocesses.
The \fIflags\fR argument indicates what sort of communication will
exist with the command pipeline.
.PP
If the \fBTCL_STDIN\fR flag is set then the standard input for the
first subprocess will be tied to the channel: writing to the channel
will provide input to the subprocess.  If \fBTCL_STDIN\fR is not set,
then standard input for the first subprocess will be the same as this
application's standard input.  If \fBTCL_STDOUT\fR is set then
standard output from the last subprocess can be read from the channel;
otherwise it goes to this application's standard output.  If
\fBTCL_STDERR\fR is set, standard error output for all subprocesses is
returned to the channel and results in an error when the channel is
closed; otherwise it goes to this application's standard error.  If
\fBTCL_ENFORCE_MODE\fR is not set, then \fIargc\fR and \fIargv\fR can
redirect the stdio handles to override \fBTCL_STDIN\fR,
\fBTCL_STDOUT\fR, and \fBTCL_STDERR\fR; if it is set, then it is an
error for argc and argv to override stdio channels for which
\fBTCL_STDIN\fR, \fBTCL_STDOUT\fR, and \fBTCL_STDERR\fR have been set.
.PP
If an error occurs while opening the channel, \fBTcl_OpenCommandChannel\fR
returns NULL and records a POSIX error code that can be retrieved with
\fBTcl_GetErrno\fR.
In addition, \fBTcl_OpenCommandChannel\fR leaves an error message in
\fIinterp->result\fR if \fIinterp\fR is not NULL.
.PP
The newly created channel is not registered in the supplied interpreter; to
register it, use \fBTcl_RegisterChannel\fR, described below.
If one of the standard channels, \fBstdin, stdout\fR or \fBstderr\fR was
previously closed, the act of creating the new channel also assigns it as a
replacement for the standard channel.

.SH TCL_MAKEFILECHANNEL
.PP
\fBTcl_MakeFileChannel\fR makes a \fBTcl_Channel\fR from an existing,
platform-specific, file handle.
The newly created channel is not registered in the supplied interpreter; to
register it, use \fBTcl_RegisterChannel\fR, described below.
If one of the standard channels, \fBstdin, stdout\fR or \fBstderr\fR was
previously closed, the act of creating the new channel also assigns it as a
replacement for the standard channel.

.SH TCL_GETCHANNEL
.PP
\fBTcl_GetChannel\fR returns a channel given the \fIchannelName\fR used to
create it with \fBTcl_CreateChannel\fR and a pointer to a Tcl interpreter in
\fIinterp\fR. If a channel by that name is not registered in that interpreter,
the procedure returns NULL. If the \fImode\fR argument is not NULL, it
points at an integer variable that will receive an OR-ed combination of
\fBTCL_READABLE\fR and \fBTCL_WRITABLE\fR describing whether the channel is
open for reading and writing.

.SH TCL_REGISTERCHANNEL
.PP
\fBTcl_RegisterChannel\fR adds a channel to the set of channels accessible
in \fIinterp\fR. After this call, Tcl programs executing in that
interpreter can refer to the channel in input or output operations using
the name given in the call to \fBTcl_CreateChannel\fR.  After this call,
the channel becomes the property of the interpreter, and the caller should
not call \fBTcl_Close\fR for the channel; the channel will be closed
automatically when it is unregistered from the interpreter.
.PP
Code executing outside of any Tcl interpreter can call
\fBTcl_RegisterChannel\fR with \fIinterp\fR as NULL, to indicate that it
wishes to hold a reference to this channel. Subsequently, the channel can
be registered in a Tcl interpreter and it will only be closed when the
matching number of calls to \fBTcl_UnregisterChannel\fR have been made.
This allows code executing outside of any interpreter to safely hold a
reference to a channel that is also registered in a Tcl interpreter.

.SH TCL_UNREGISTERCHANNEL
.PP
\fBTcl_UnregisterChannel\fR removes a channel from the set of channels
accessible in \fIinterp\fR. After this call, Tcl programs will no longer be
able to use the channel's name to refer to the channel in that interpreter.
If this operation removed the last registration of the channel in any
interpreter, the channel is also closed and destroyed.
.PP
Code not associated with a Tcl interpreter can call
\fBTcl_UnregisterChannel\fR with \fIinterp\fR as NULL, to indicate to Tcl
that it no longer holds a reference to that channel. If this is the last
reference to the channel, it will now be closed.

.SH TCL_CLOSE
.PP
\fBTcl_Close\fR destroys the channel \fIchannel\fR, which must denote a
currently open channel. The channel should not be registered in any
interpreter when \fBTcl_Close\fR is called. Buffered output is flushed to
the channel's output device prior to destroying the channel, and any
buffered input is discarded.  If this is a blocking channel, the call does
not return until all buffered data is successfully sent to the channel's
output device.  If this is a nonblocking channel and there is buffered
output that cannot be written without blocking, the call returns
immediately; output is flushed in the background and the channel will be
closed once all of the buffered data has been output.  In this case errors
during flushing are not reported.
.PP
If the channel was closed successfully, \fBTcl_Close\fR returns \fBTCL_OK\fR.
If an error occurs, \fBTcl_Close\fR returns \fBTCL_ERROR\fR and records a
POSIX error code that can be retrieved with \fBTcl_GetErrno\fR.
If the channel is being closed synchronously and an error occurs during
closing of the channel and \fIinterp\fR is not NULL, an error message is
left in \fIinterp->result\fR.
.PP
Note: it is not safe to call \fBTcl_Close\fR on a channel that has been
registered using \fBTcl_RegisterChannel\fR; see the documentation for
\fBTcl_RegisterChannel\fR, above, for details. If the channel has ever been
given as the \fBchan\fR argument in a call to \fBTcl_RegisterChannel\fR,
you should instead use \fBTcl_UnregisterChannel\fR, which will internally
call \fBTcl_Close\fR when all calls to \fBTcl_RegisterChannel\fR have been
matched by corresponding calls to \fBTcl_UnregisterChannel\fR.

.SH TCL_READ
.PP
\fBTcl_Read\fR consumes up to \fItoRead\fR bytes of data from
\fIchannel\fR and stores it at \fIbuf\fR.
The return value of \fBTcl_Read\fR is the number of characters written
at \fIbuf\fR.
The buffer produced by \fBTcl_Read\fR is not NULL terminated. Its contents
are valid from the zeroth position up to and excluding the position
indicated by the return value.
If an error occurs, the return value is -1 and \fBTcl_Read\fR records
a POSIX error code that can be retrieved with \fBTcl_GetErrno\fR.
.PP
The return value may be smaller than the value of \fItoRead\fR, indicating
that less data than requested was available, also called a \fIshort
read\fR.
In blocking mode, this can only happen on an end-of-file.
In nonblocking mode, a short read can also occur if there is not
enough input currently available:  \fBTcl_Read\fR returns a short
count rather than waiting for more data.
.PP
If the channel is in blocking mode, a return value of zero indicates an end
of file condition. If the channel is in nonblocking mode, a return value of
zero indicates either that no input is currently available or an end of
file condition. Use \fBTcl_Eof\fR and \fBTcl_InputBlocked\fR
to tell which of these conditions actually occurred.
.PP
\fBTcl_Read\fR translates platform-specific end-of-line representations
into the canonical \fB\en\fR internal representation according to the
current end-of-line recognition mode. End-of-line recognition and the
various platform-specific modes are described in the manual entry for the
Tcl \fBfconfigure\fR command.

.SH TCL_GETS AND TCL_GETSOBJ
.PP
\fBTcl_Gets\fR reads a line of input from a channel and appends all of
the characters of the line except for the terminating end-of-line character(s)
to the dynamic string given by \fIdsPtr\fR.
The end-of-line character(s) are read and discarded.
.PP
If a line was successfully read, the return value is greater than or
equal to zero, and it indicates the number of characters stored
in the dynamic string.
If an error occurs, \fBTcl_Gets\fR returns -1 and records a POSIX error
code that can be retrieved with \fBTcl_GetErrno\fR.
\fBTcl_Gets\fR also returns -1 if the end of the file is reached;
the \fBTcl_Eof\fR procedure can be used to distinguish an error
from an end-of-file condition.
.PP
If the channel is in nonblocking mode, the return value can also
be -1 if no data was available or the data that was available
did not contain an end-of-line character.
When -1 is returned, the \fBTcl_InputBlocked\fR procedure may be
invoked to determine if the channel is blocked because of input
unavailability.
.PP
\fBTcl_GetsObj\fR is the same as \fBTcl_Gets\fR except the resulting
characters are appended to a Tcl object \fBlineObjPtr\fR rather than a
dynamic string.
.SH TCL_WRITE
.PP
\fBTcl_Write\fR accepts \fItoWrite\fR bytes of data at \fIbuf\fR for output
on \fIchannel\fR. This data may not appear on the output device
immediately. If the data should appear immediately, call \fBTcl_Flush\fR
after the call to \fBTcl_Write\fR, or set the \fB-buffering\fR option on
the channel to \fBnone\fR. If you wish the data to appear as soon as an end
of line is accepted for output, set the \fB\-buffering\fR option on the
channel to \fBline\fR mode.
.PP
The \fItoWrite\fR argument specifies how many bytes of data are provided in
the \fIbuf\fR argument. If it is negative, \fBTcl_Write\fR expects the data
to be NULL terminated and it outputs everything up to the NULL.
.PP
The return value of \fBTcl_Write\fR is a count of how many
characters were accepted for output to the channel. This is either equal to
\fItoWrite\fR or -1 to indicate that an error occurred.
If an error occurs, \fBTcl_Write\fR also records a POSIX error code
that may be retrieved with \fBTcl_GetErrno\fR.
.PP
Newline characters in the output data are translated to platform-specific
end-of-line sequences according to the \fB\-translation\fR option for
the channel.

.SH TCL_FLUSH
.PP
\fBTcl_Flush\fR causes all of the buffered output data for \fIchannel\fR
to be written to its underlying file or device as soon as possible.
If the channel is in blocking mode, the call does not return until
all the buffered data has been sent to the channel or some error occurred.
The call returns immediately if the channel is nonblocking; it starts
a background flush that will write the buffered data to the channel
eventually, as fast as the channel is able to absorb it.
.PP
The return value is normally \fBTCL_OK\fR.
If an error occurs, \fBTcl_Flush\fR returns \fBTCL_ERROR\fR and
records a POSIX error code that can be retrieved with \fBTcl_GetErrno\fR.

.SH TCL_SEEK
.PP
\fBTcl_Seek\fR moves the access point in \fIchannel\fR where subsequent
data will be read or written. Buffered output is flushed to the channel and
buffered input is discarded, prior to the seek operation.
.PP
\fBTcl_Seek\fR normally returns the new access point.
If an error occurs, \fBTcl_Seek\fR returns -1 and records a POSIX error
code that can be retrieved with \fBTcl_GetErrno\fR.
After an error, the access point may or may not have been moved.

.SH TCL_TELL
.PP
\fBTcl_Tell\fR returns the current access point for a channel. The returned
value is -1 if the channel does not support seeking.

.SH TCL_GETCHANNELOPTION
.PP
\fBTcl_GetChannelOption\fR retrieves, in \fIdsPtr\fR, the value of one of
the options currently in effect for a channel, or a list of all options and
their values.  The \fIchannel\fR argument identifies the channel for which
to query an option or retrieve all options and their values.
If \fIoptionName\fR is not NULL, it is the name of the
option to query; the option's value is copied to the Tcl dynamic string
denoted by \fIoptionValue\fR. If
\fIoptionName\fR is NULL, the function stores an alternating list of option
names and their values in \fIoptionValue\fR, using a series of calls to
\fBTcl_DStringAppendElement\fR. The various preexisting options and
their possible values are described in the manual entry for the Tcl
\fBfconfigure\fR command. Other options can be added by each channel type.
These channel type specific options are described in the manual entry for
the Tcl command that creates a channel of that type; for example, the
additional options for TCP based channels are described in the manual entry
for the Tcl \fBsocket\fR command.
The procedure normally returns \fBTCL_OK\fR. If an error occurs, it returns
\fBTCL_ERROR\fR and calls \fBTcl_SetErrno\fR to store an appropriate POSIX
error code.

.SH TCL_SETCHANNELOPTION
.PP
\fBTcl_SetChannelOption\fR sets a new value for an option on \fIchannel\fR.
\fIOptionName\fR is the option to set and \fInewValue\fR is the value to
set.
The procedure normally returns \fBTCL_OK\fR.  If an error occurs,
it returns \fBTCL_ERROR\fR;  in addition, if \fIinterp\fR is non-NULL,
\fBTcl_SetChannelOption\fR leaves an error message in \fIinterp->result\fR.

.SH TCL_EOF
.PP
\fBTcl_Eof\fR returns a nonzero value if \fIchannel\fR encountered
an end of file during the last input operation.

.SH TCL_INPUTBLOCKED
.PP
\fBTcl_InputBlocked\fR returns a nonzero value if \fIchannel\fR is in
nonblocking mode and the last input operation returned less data than
requested because there was insufficient data available.
The call always returns zero if the channel is in blocking mode.

.SH TCL_INPUTBUFFERED
.PP
\fBTcl_InputBuffered\fR returns the number of bytes of input currently
buffered in the internal buffers for a channel. If the channel is not open
for reading, this function always returns zero.

.VS
.SH "PLATFORM ISSUES"
.PP
The handles returned from \fBTcl_GetChannelHandle\fR depend on the
platform and the channel type.  On Unix platforms, the handle is
always a Unix file descriptor as returned from the \fBopen\fR system
call.  On Windows platforms, the handle is a file \fBHANDLE\fR when
the channel was created with \fBTcl_OpenFileChannel\fR,
\fBTcl_OpenCommandChannel\fR, or \fBTcl_MakeFileChannel\fR.  Other
channel types may return a different type of handle on Windows
platforms.  On the Macintosh platform, the handle is a file reference
number as returned from \fBHOpenDF\fR.
.VE

.SH "SEE ALSO"
DString(3), fconfigure(n), filename(n), fopen(2), Tcl_CreateChannel(3)

.SH KEYWORDS
access point, blocking, buffered I/O, channel, channel driver, end of file,
flush, input, nonblocking, output, read, seek, write
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted doc/regexp.n.

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
'\"
'\" Copyright (c) 1993 The Regents of the University of California.
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\" 
'\" RCS: @(#) $Id: regexp.n,v 1.2 1998/09/14 18:39:54 stanton Exp $
'\" 
.so man.macros
.TH regexp n "" Tcl "Tcl Built-In Commands"
.BS
'\" Note:  do not modify the .SH NAME line immediately below!
.SH NAME
regexp \- Match a regular expression against a string
.SH SYNOPSIS
\fBregexp \fR?\fIswitches\fR? \fIexp string \fR?\fImatchVar\fR? ?\fIsubMatchVar subMatchVar ...\fR?
.BE

.SH DESCRIPTION
.PP
Determines whether the regular expression \fIexp\fR matches part or
all of \fIstring\fR and returns 1 if it does, 0 if it doesn't.
.LP
If additional arguments are specified after \fIstring\fR then they
are treated as the names of variables in which to return
information about which part(s) of \fIstring\fR matched \fIexp\fR.
\fIMatchVar\fR will be set to the range of \fIstring\fR that
matched all of \fIexp\fR.  The first \fIsubMatchVar\fR will contain
the characters in \fIstring\fR that matched the leftmost parenthesized
subexpression within \fIexp\fR, the next \fIsubMatchVar\fR will
contain the characters that matched the next parenthesized
subexpression to the right in \fIexp\fR, and so on.
.LP
If the initial arguments to \fBregexp\fR start with \fB\-\fR then
they are treated as switches.  The following switches are
currently supported:
.TP 10
\fB\-nocase\fR
Causes upper-case characters in \fIstring\fR to be treated as
lower case during the matching process.
.TP 10
\fB\-indices\fR
Changes what is stored in the \fIsubMatchVar\fRs. 
Instead of storing the matching characters from \fBstring\fR,
each variable
will contain a list of two decimal strings giving the indices
in \fIstring\fR of the first and last characters in the matching
range of characters.
.TP 10
\fB\-\|\-\fR
Marks the end of switches.  The argument following this one will
be treated as \fIexp\fR even if it starts with a \fB\-\fR.
.LP
If there are more \fIsubMatchVar\fR's than parenthesized
subexpressions within \fIexp\fR, or if a particular subexpression
in \fIexp\fR doesn't match the string (e.g. because it was in a
portion of the expression that wasn't matched), then the corresponding
\fIsubMatchVar\fR will be set to ``\fB\-1 \-1\fR'' if \fB\-indices\fR
has been specified or to an empty string otherwise.

.SH "REGULAR EXPRESSIONS"
.PP
Regular expressions are implemented using Henry Spencer's package
(thanks, Henry!),
and much of the description of regular expressions below is copied verbatim
from his manual entry.
.PP
A regular expression is zero or more \fIbranches\fR, separated by ``|''.
It matches anything that matches one of the branches.
.PP
A branch is zero or more \fIpieces\fR, concatenated.
It matches a match for the first, followed by a match for the second, etc.
.PP
A piece is an \fIatom\fR possibly followed by ``*'', ``+'', or ``?''.
An atom followed by ``*'' matches a sequence of 0 or more matches of the atom.
An atom followed by ``+'' matches a sequence of 1 or more matches of the atom.
An atom followed by ``?'' matches a match of the atom, or the null string.
.PP
An atom is a regular expression in parentheses (matching a match for the
regular expression), a \fIrange\fR (see below), ``.''
(matching any single character), ``^'' (matching the null string at the
beginning of the input string), ``$'' (matching the null string at the
end of the input string), a ``\e'' followed by a single character (matching
that character), or a single character with no other significance
(matching that character).
.PP
A \fIrange\fR is a sequence of characters enclosed in ``[]''.
It normally matches any single character from the sequence.
If the sequence begins with ``^'',
it matches any single character \fInot\fR from the rest of the sequence.
If two characters in the sequence are separated by ``\-'', this is shorthand
for the full list of ASCII characters between them
(e.g. ``[0-9]'' matches any decimal digit).
To include a literal ``]'' in the sequence, make it the first character
(following a possible ``^'').
To include a literal ``\-'', make it the first or last character.

.SH "CHOOSING AMONG ALTERNATIVE MATCHES"
.PP
In general there may be more than one way to match a regular expression
to an input string.  For example, consider the command
.CS
\fBregexp  (a*)b*  aabaaabb  x  y\fR
.CE
Considering only the rules given so far, \fBx\fR and \fBy\fR could
end up with the values \fBaabb\fR and \fBaa\fR, \fBaaab\fR and \fBaaa\fR,
\fBab\fR and \fBa\fR, or any of several other combinations.
To resolve this potential ambiguity \fBregexp\fR chooses among
alternatives using the rule ``first then longest''.
In other words, it considers the possible matches in order working
from left to right across the input string and the pattern, and it
attempts to match longer pieces of the input string before shorter
ones.  More specifically, the following rules apply in decreasing
order of priority:
.IP [1]
If a regular expression could match two different parts of an input string
then it will match the one that begins earliest.
.IP [2]
If a regular expression contains \fB|\fR operators then the leftmost
matching sub-expression is chosen.
.IP [3]
In \fB*\fR, \fB+\fR, and \fB?\fR constructs, longer matches are chosen
in preference to shorter ones.
.IP [4]
In sequences of expression components the components are considered
from left to right.
.LP
In the example from above, \fB(a*)b*\fR matches \fBaab\fR:  the \fB(a*)\fR
portion of the pattern is matched first and it consumes the leading
\fBaa\fR; then the \fBb*\fR portion of the pattern consumes the
next \fBb\fR.  Or, consider the following example:
.CS
\fBregexp  (ab|a)(b*)c  abc  x  y  z\fR
.CE
After this command \fBx\fR will be \fBabc\fR, \fBy\fR will be
\fBab\fR, and \fBz\fR will be an empty string.
Rule 4 specifies that \fB(ab|a)\fR gets first shot at the input
string and Rule 2 specifies that the \fBab\fR sub-expression
is checked before the \fBa\fR sub-expression.
Thus the \fBb\fR has already been claimed before the \fB(b*)\fR
component is checked and \fB(b*)\fR must match an empty string.

.SH KEYWORDS
match, regular expression, string
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































Deleted generic/tcl.h.

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
/*
 * tcl.h --
 *
 *	This header file describes the externally-visible facilities
 *	of the Tcl interpreter.
 *
 * Copyright (c) 1987-1994 The Regents of the University of California.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 * Copyright (c) 1993-1996 Lucent Technologies.
 * Copyright (c) 1998-1999 Scriptics Corporation.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: tcl.h,v 1.33 1999/02/03 02:58:25 stanton Exp $
 */

#ifndef _TCL
#define _TCL

/*
 * When version numbers change here, must also go into the following files
 * and update the version numbers:
 *
 * README
 * library/init.tcl	(only if major.minor changes, not patchlevel)
 * unix/configure.in
 * win/makefile.bc	(only if major.minor changes, not patchlevel)
 * win/makefile.vc	(only if major.minor changes, not patchlevel)
 * win/README
 * win/README.binary
 * mac/README
 *
 * The release level should be  0 for alpha, 1 for beta, and 2 for
 * final/patch.  The release serial value is the number that follows the
 * "a", "b", or "p" in the patch level; for example, if the patch level
 * is 7.6b2, TCL_RELEASE_SERIAL is 2.  It restarts at 1 whenever the
 * release level is changed, except for the final release which is 0
 * (the first patch will start at 1).
 */

#define TCL_MAJOR_VERSION   8
#define TCL_MINOR_VERSION   0
#define TCL_RELEASE_LEVEL   2
#define TCL_RELEASE_SERIAL  5

#define TCL_VERSION	    "8.0"
#define TCL_PATCH_LEVEL	    "8.0.5"

/*
 * The following definitions set up the proper options for Windows
 * compilers.  We use this method because there is no autoconf equivalent.
 */

#ifndef __WIN32__
#   if defined(_WIN32) || defined(WIN32)
#	define __WIN32__
#   endif
#endif

#ifdef __WIN32__
#   ifndef STRICT
#	define STRICT
#   endif
#   ifndef USE_PROTOTYPE
#	define USE_PROTOTYPE 1
#   endif
#   ifndef HAS_STDARG
#	define HAS_STDARG 1
#   endif
#   ifndef USE_PROTOTYPE
#	define USE_PROTOTYPE 1
#   endif

/*
 * Under Windows we need to call Tcl_Alloc in all cases to avoid competing
 * C run-time library issues.
 */

#   ifndef USE_TCLALLOC
#	define USE_TCLALLOC 1
#   endif
#endif /* __WIN32__ */

/*
 * The following definitions set up the proper options for Macintosh
 * compilers.  We use this method because there is no autoconf equivalent.
 */

#ifdef MAC_TCL
#   ifndef HAS_STDARG
#	define HAS_STDARG 1
#   endif
#   ifndef USE_TCLALLOC
#	define USE_TCLALLOC 1
#   endif
#   ifndef NO_STRERROR
#	define NO_STRERROR 1
#   endif
#endif

/*
 * Utility macros: STRINGIFY takes an argument and wraps it in "" (double
 * quotation marks), JOIN joins two arguments.
 */

#define VERBATIM(x) x
#ifdef _MSC_VER
# define STRINGIFY(x) STRINGIFY1(x)
# define STRINGIFY1(x) #x
# define JOIN(a,b) JOIN1(a,b)
# define JOIN1(a,b) a##b
#else
# ifdef RESOURCE_INCLUDED
#  define STRINGIFY(x) STRINGIFY1(x)
#  define STRINGIFY1(x) #x
#  define JOIN(a,b) JOIN1(a,b)
#  define JOIN1(a,b) a##b
# else
#  ifdef __STDC__
#   define STRINGIFY(x) #x
#   define JOIN(a,b) a##b
#  else
#   define STRINGIFY(x) "x"
#   define JOIN(a,b) VERBATIM(a)VERBATIM(b)
#  endif
# endif
#endif

/* 
 * A special definition used to allow this header file to be included 
 * in resource files so that they can get obtain version information from
 * this file.  Resource compilers don't like all the C stuff, like typedefs
 * and procedure declarations, that occur below.
 */

#ifndef RESOURCE_INCLUDED

#ifndef BUFSIZ
#include <stdio.h>
#endif

/*
 * Definitions that allow Tcl functions with variable numbers of
 * arguments to be used with either varargs.h or stdarg.h.  TCL_VARARGS
 * is used in procedure prototypes.  TCL_VARARGS_DEF is used to declare
 * the arguments in a function definiton: it takes the type and name of
 * the first argument and supplies the appropriate argument declaration
 * string for use in the function definition.  TCL_VARARGS_START
 * initializes the va_list data structure and returns the first argument.
 */

#if defined(__STDC__) || defined(HAS_STDARG)
#   define TCL_VARARGS(type, name) (type name, ...)
#   define TCL_VARARGS_DEF(type, name) (type name, ...)
#   define TCL_VARARGS_START(type, name, list) (va_start(list, name), name)
#else
#   ifdef __cplusplus
#	define TCL_VARARGS(type, name) (type name, ...)
#	define TCL_VARARGS_DEF(type, name) (type va_alist, ...)
#   else
#	define TCL_VARARGS(type, name) ()
#	define TCL_VARARGS_DEF(type, name) (va_alist)
#   endif
#   define TCL_VARARGS_START(type, name, list) \
	(va_start(list), va_arg(list, type))
#endif

/*
 * Macros used to declare a function to be exported by a DLL.
 * Used by Windows, maps to no-op declarations on non-Windows systems.
 * The default build on windows is for a DLL, which causes the DLLIMPORT
 * and DLLEXPORT macros to be nonempty. To build a static library, the
 * macro STATIC_BUILD should be defined.
 * The support follows the convention that a macro called BUILD_xxxx, where
 * xxxx is the name of a library we are building, is set on the compile line
 * for sources that are to be placed in the library. See BUILD_tcl in this
 * file for an example of how the macro is to be used.
 */

#ifdef __WIN32__
# ifdef STATIC_BUILD
#  define DLLIMPORT
#  define DLLEXPORT
# else
#  if defined(_MSC_VER) || (defined(__GNUC__) && defined(__declspec))
#   define DLLIMPORT __declspec(dllimport)
#   define DLLEXPORT __declspec(dllexport)
#  else
#   define DLLIMPORT
#   define DLLEXPORT
#  endif
# endif
#else
# define DLLIMPORT
# define DLLEXPORT
#endif

#ifdef TCL_STORAGE_CLASS
# undef TCL_STORAGE_CLASS
#endif
#ifdef BUILD_tcl
# define TCL_STORAGE_CLASS DLLEXPORT
#else
# define TCL_STORAGE_CLASS DLLIMPORT
#endif

/*
 * Definitions that allow this header file to be used either with or
 * without ANSI C features like function prototypes.
 */

#undef _ANSI_ARGS_
#undef CONST

#if ((defined(__STDC__) || defined(SABER)) && !defined(NO_PROTOTYPE)) || defined(__cplusplus) || defined(USE_PROTOTYPE)
#   define _USING_PROTOTYPES_ 1
#   define _ANSI_ARGS_(x)	x
#   define CONST const
#else
#   define _ANSI_ARGS_(x)	()
#   define CONST
#endif

#ifdef __cplusplus
#   define EXTERN extern "C" TCL_STORAGE_CLASS
#else
#   define EXTERN extern TCL_STORAGE_CLASS
#endif

/*
 * Macro to use instead of "void" for arguments that must have
 * type "void *" in ANSI C;  maps them to type "char *" in
 * non-ANSI systems.
 */
#ifndef __WIN32__
#ifndef VOID
#   ifdef __STDC__
#       define VOID void
#   else
#       define VOID char
#   endif
#endif
#else /* __WIN32__ */
/*
 * The following code is copied from winnt.h
 */
#ifndef VOID
#define VOID void
typedef char CHAR;
typedef short SHORT;
typedef long LONG;
#endif
#endif /* __WIN32__ */

/*
 * Miscellaneous declarations.
 */

#ifndef NULL
#define NULL 0
#endif

#ifndef _CLIENTDATA
#   if defined(__STDC__) || defined(__cplusplus)
    typedef void *ClientData;
#   else
    typedef int *ClientData;
#   endif /* __STDC__ */
#define _CLIENTDATA
#endif

/*
 * Data structures defined opaquely in this module. The definitions below
 * just provide dummy types. A few fields are made visible in Tcl_Interp
 * structures, namely those used for returning a string result from
 * commands. Direct access to the result field is discouraged in Tcl 8.0.
 * The interpreter result is either an object or a string, and the two
 * values are kept consistent unless some C code sets interp->result
 * directly. Programmers should use either the procedure Tcl_GetObjResult()
 * or Tcl_GetStringResult() to read the interpreter's result. See the
 * SetResult man page for details.
 * 
 * Note: any change to the Tcl_Interp definition below must be mirrored
 * in the "real" definition in tclInt.h.
 *
 * Note: Tcl_ObjCmdProc procedures do not directly set result and freeProc.
 * Instead, they set a Tcl_Obj member in the "real" structure that can be
 * accessed with Tcl_GetObjResult() and Tcl_SetObjResult().
 */

typedef struct Tcl_Interp {
    char *result;		/* If the last command returned a string
				 * result, this points to it. */
    void (*freeProc) _ANSI_ARGS_((char *blockPtr));
				/* Zero means the string result is
				 * statically allocated. TCL_DYNAMIC means
				 * it was allocated with ckalloc and should
				 * be freed with ckfree. Other values give
				 * the address of procedure to invoke to
				 * free the result. Tcl_Eval must free it
				 * before executing next command. */
    int errorLine;              /* When TCL_ERROR is returned, this gives
                                 * the line number within the command where
                                 * the error occurred (1 if first line). */
} Tcl_Interp;

typedef struct Tcl_AsyncHandler_ *Tcl_AsyncHandler;
typedef struct Tcl_Channel_ *Tcl_Channel;
typedef struct Tcl_Command_ *Tcl_Command;
typedef struct Tcl_Event Tcl_Event;
typedef struct Tcl_Pid_ *Tcl_Pid;
typedef struct Tcl_RegExp_ *Tcl_RegExp;
typedef struct Tcl_TimerToken_ *Tcl_TimerToken;
typedef struct Tcl_Trace_ *Tcl_Trace;
typedef struct Tcl_Var_ *Tcl_Var;

/*
 * When a TCL command returns, the interpreter contains a result from the
 * command. Programmers are strongly encouraged to use one of the
 * procedures Tcl_GetObjResult() or Tcl_GetStringResult() to read the
 * interpreter's result. See the SetResult man page for details. Besides
 * this result, the command procedure returns an integer code, which is 
 * one of the following:
 *
 * TCL_OK		Command completed normally; the interpreter's
 *			result contains	the command's result.
 * TCL_ERROR		The command couldn't be completed successfully;
 *			the interpreter's result describes what went wrong.
 * TCL_RETURN		The command requests that the current procedure
 *			return; the interpreter's result contains the
 *			procedure's return value.
 * TCL_BREAK		The command requests that the innermost loop
 *			be exited; the interpreter's result is meaningless.
 * TCL_CONTINUE		Go on to the next iteration of the current loop;
 *			the interpreter's result is meaningless.
 */

#define TCL_OK		0
#define TCL_ERROR	1
#define TCL_RETURN	2
#define TCL_BREAK	3
#define TCL_CONTINUE	4

#define TCL_RESULT_SIZE 200

/*
 * Argument descriptors for math function callbacks in expressions:
 */

typedef enum {TCL_INT, TCL_DOUBLE, TCL_EITHER} Tcl_ValueType;
typedef struct Tcl_Value {
    Tcl_ValueType type;		/* Indicates intValue or doubleValue is
				 * valid, or both. */
    long intValue;		/* Integer value. */
    double doubleValue;		/* Double-precision floating value. */
} Tcl_Value;

/*
 * Forward declaration of Tcl_Obj to prevent an error when the forward
 * reference to Tcl_Obj is encountered in the procedure types declared 
 * below.
 */

struct Tcl_Obj;

/*
 * Procedure types defined by Tcl:
 */

typedef int (Tcl_AppInitProc) _ANSI_ARGS_((Tcl_Interp *interp));
typedef int (Tcl_AsyncProc) _ANSI_ARGS_((ClientData clientData,
	Tcl_Interp *interp, int code));
typedef void (Tcl_ChannelProc) _ANSI_ARGS_((ClientData clientData, int mask));
typedef void (Tcl_CloseProc) _ANSI_ARGS_((ClientData data));
typedef void (Tcl_CmdDeleteProc) _ANSI_ARGS_((ClientData clientData));
typedef int (Tcl_CmdProc) _ANSI_ARGS_((ClientData clientData,
	Tcl_Interp *interp, int argc, char *argv[]));
typedef void (Tcl_CmdTraceProc) _ANSI_ARGS_((ClientData clientData,
	Tcl_Interp *interp, int level, char *command, Tcl_CmdProc *proc,
	ClientData cmdClientData, int argc, char *argv[]));
typedef void (Tcl_DupInternalRepProc) _ANSI_ARGS_((struct Tcl_Obj *srcPtr, 
        struct Tcl_Obj *dupPtr));
typedef int (Tcl_EventProc) _ANSI_ARGS_((Tcl_Event *evPtr, int flags));
typedef void (Tcl_EventCheckProc) _ANSI_ARGS_((ClientData clientData,
	int flags));
typedef int (Tcl_EventDeleteProc) _ANSI_ARGS_((Tcl_Event *evPtr,
        ClientData clientData));
typedef void (Tcl_EventSetupProc) _ANSI_ARGS_((ClientData clientData,
	int flags));
typedef void (Tcl_ExitProc) _ANSI_ARGS_((ClientData clientData));
typedef void (Tcl_FileProc) _ANSI_ARGS_((ClientData clientData, int mask));
typedef void (Tcl_FileFreeProc) _ANSI_ARGS_((ClientData clientData));
typedef void (Tcl_FreeInternalRepProc) _ANSI_ARGS_((struct Tcl_Obj *objPtr));
typedef void (Tcl_FreeProc) _ANSI_ARGS_((char *blockPtr));
typedef void (Tcl_IdleProc) _ANSI_ARGS_((ClientData clientData));
typedef void (Tcl_InterpDeleteProc) _ANSI_ARGS_((ClientData clientData,
	Tcl_Interp *interp));
typedef int (Tcl_MathProc) _ANSI_ARGS_((ClientData clientData,
	Tcl_Interp *interp, Tcl_Value *args, Tcl_Value *resultPtr));
typedef void (Tcl_NamespaceDeleteProc) _ANSI_ARGS_((ClientData clientData));
typedef int (Tcl_ObjCmdProc) _ANSI_ARGS_((ClientData clientData,
	Tcl_Interp *interp, int objc, struct Tcl_Obj * CONST objv[]));
typedef int (Tcl_PackageInitProc) _ANSI_ARGS_((Tcl_Interp *interp));
typedef void (Tcl_TcpAcceptProc) _ANSI_ARGS_((ClientData callbackData,
        Tcl_Channel chan, char *address, int port));
typedef void (Tcl_TimerProc) _ANSI_ARGS_((ClientData clientData));
typedef int (Tcl_SetFromAnyProc) _ANSI_ARGS_((Tcl_Interp *interp,
	struct Tcl_Obj *objPtr));
typedef void (Tcl_UpdateStringProc) _ANSI_ARGS_((struct Tcl_Obj *objPtr));
typedef char *(Tcl_VarTraceProc) _ANSI_ARGS_((ClientData clientData,
	Tcl_Interp *interp, char *part1, char *part2, int flags));

/*
 * The following structure represents a type of object, which is a
 * particular internal representation for an object plus a set of
 * procedures that provide standard operations on objects of that type.
 */

typedef struct Tcl_ObjType {
    char *name;			/* Name of the type, e.g. "int". */
    Tcl_FreeInternalRepProc *freeIntRepProc;
				/* Called to free any storage for the type's
				 * internal rep. NULL if the internal rep
				 * does not need freeing. */
    Tcl_DupInternalRepProc *dupIntRepProc;
    				/* Called to create a new object as a copy
				 * of an existing object. */
    Tcl_UpdateStringProc *updateStringProc;
    				/* Called to update the string rep from the
				 * type's internal representation. */
    Tcl_SetFromAnyProc *setFromAnyProc;
    				/* Called to convert the object's internal
				 * rep to this type. Frees the internal rep
				 * of the old type. Returns TCL_ERROR on
				 * failure. */
} Tcl_ObjType;

/*
 * One of the following structures exists for each object in the Tcl
 * system. An object stores a value as either a string, some internal
 * representation, or both.
 */

typedef struct Tcl_Obj {
    int refCount;		/* When 0 the object will be freed. */
    char *bytes;		/* This points to the first byte of the
				 * object's string representation. The array
				 * must be followed by a null byte (i.e., at
				 * offset length) but may also contain
				 * embedded null characters. The array's
				 * storage is allocated by ckalloc. NULL
				 * means the string rep is invalid and must
				 * be regenerated from the internal rep.
				 * Clients should use Tcl_GetStringFromObj
				 * to get a pointer to the byte array as a
				 * readonly value. */
    int length;			/* The number of bytes at *bytes, not
				 * including the terminating null. */
    Tcl_ObjType *typePtr;	/* Denotes the object's type. Always
				 * corresponds to the type of the object's
				 * internal rep. NULL indicates the object
				 * has no internal rep (has no type). */
    union {			/* The internal representation: */
	long longValue;		/*   - an long integer value */
	double doubleValue;	/*   - a double-precision floating value */
	VOID *otherValuePtr;	/*   - another, type-specific value */
	struct {		/*   - internal rep as two pointers */
	    VOID *ptr1;
	    VOID *ptr2;
	} twoPtrValue;
    } internalRep;
} Tcl_Obj;

/*
 * Macros to increment and decrement a Tcl_Obj's reference count, and to
 * test whether an object is shared (i.e. has reference count > 1).
 * Note: clients should use Tcl_DecrRefCount() when they are finished using
 * an object, and should never call TclFreeObj() directly. TclFreeObj() is
 * only defined and made public in tcl.h to support Tcl_DecrRefCount's macro
 * definition. Note also that Tcl_DecrRefCount() refers to the parameter
 * "obj" twice. This means that you should avoid calling it with an
 * expression that is expensive to compute or has side effects.
 */

EXTERN void		Tcl_IncrRefCount _ANSI_ARGS_((Tcl_Obj *objPtr));
EXTERN void		Tcl_DecrRefCount _ANSI_ARGS_((Tcl_Obj *objPtr));
EXTERN int		Tcl_IsShared _ANSI_ARGS_((Tcl_Obj *objPtr));

#ifdef TCL_MEM_DEBUG
#   define Tcl_IncrRefCount(objPtr) \
	Tcl_DbIncrRefCount(objPtr, __FILE__, __LINE__)
#   define Tcl_DecrRefCount(objPtr) \
	Tcl_DbDecrRefCount(objPtr, __FILE__, __LINE__)
#   define Tcl_IsShared(objPtr) \
	Tcl_DbIsShared(objPtr, __FILE__, __LINE__)
#else
#   define Tcl_IncrRefCount(objPtr) \
	++(objPtr)->refCount
#   define Tcl_DecrRefCount(objPtr) \
	if (--(objPtr)->refCount <= 0) TclFreeObj(objPtr)
#   define Tcl_IsShared(objPtr) \
	((objPtr)->refCount > 1)
#endif

/*
 * Macros and definitions that help to debug the use of Tcl objects.
 * When TCL_MEM_DEBUG is defined, the Tcl_New* declarations are 
 * overridden to call debugging versions of the object creation procedures.
 */

EXTERN Tcl_Obj *	Tcl_NewBooleanObj _ANSI_ARGS_((int boolValue));
EXTERN Tcl_Obj *	Tcl_NewDoubleObj _ANSI_ARGS_((double doubleValue));
EXTERN Tcl_Obj *	Tcl_NewIntObj _ANSI_ARGS_((int intValue));
EXTERN Tcl_Obj *	Tcl_NewListObj _ANSI_ARGS_((int objc,
			    Tcl_Obj *CONST objv[]));
EXTERN Tcl_Obj *	Tcl_NewLongObj _ANSI_ARGS_((long longValue));
EXTERN Tcl_Obj *	Tcl_NewObj _ANSI_ARGS_((void));
EXTERN Tcl_Obj *	Tcl_NewStringObj _ANSI_ARGS_((char *bytes,
			    int length));

#ifdef TCL_MEM_DEBUG
#  define Tcl_NewBooleanObj(val) \
     Tcl_DbNewBooleanObj(val, __FILE__, __LINE__)
#  define Tcl_NewDoubleObj(val) \
     Tcl_DbNewDoubleObj(val, __FILE__, __LINE__)
#  define Tcl_NewIntObj(val) \
     Tcl_DbNewLongObj(val, __FILE__, __LINE__)
#  define Tcl_NewListObj(objc, objv) \
     Tcl_DbNewListObj(objc, objv, __FILE__, __LINE__)
#  define Tcl_NewLongObj(val) \
     Tcl_DbNewLongObj(val, __FILE__, __LINE__)
#  define Tcl_NewObj() \
     Tcl_DbNewObj(__FILE__, __LINE__)
#  define Tcl_NewStringObj(bytes, len) \
     Tcl_DbNewStringObj(bytes, len, __FILE__, __LINE__)
#endif /* TCL_MEM_DEBUG */

/*
 * The following definitions support Tcl's namespace facility.
 * Note: the first five fields must match exactly the fields in a
 * Namespace structure (see tcl.h). 
 */

typedef struct Tcl_Namespace {
    char *name;                 /* The namespace's name within its parent
				 * namespace. This contains no ::'s. The
				 * name of the global namespace is ""
				 * although "::" is an synonym. */
    char *fullName;             /* The namespace's fully qualified name.
				 * This starts with ::. */
    ClientData clientData;      /* Arbitrary value associated with this
				 * namespace. */
    Tcl_NamespaceDeleteProc* deleteProc;
                                /* Procedure invoked when deleting the
				 * namespace to, e.g., free clientData. */
    struct Tcl_Namespace* parentPtr;
                                /* Points to the namespace that contains
				 * this one. NULL if this is the global
				 * namespace. */
} Tcl_Namespace;

/*
 * The following structure represents a call frame, or activation record.
 * A call frame defines a naming context for a procedure call: its local
 * scope (for local variables) and its namespace scope (used for non-local
 * variables; often the global :: namespace). A call frame can also define
 * the naming context for a namespace eval or namespace inscope command:
 * the namespace in which the command's code should execute. The
 * Tcl_CallFrame structures exist only while procedures or namespace
 * eval/inscope's are being executed, and provide a Tcl call stack.
 * 
 * A call frame is initialized and pushed using Tcl_PushCallFrame and
 * popped using Tcl_PopCallFrame. Storage for a Tcl_CallFrame must be
 * provided by the Tcl_PushCallFrame caller, and callers typically allocate
 * them on the C call stack for efficiency. For this reason, Tcl_CallFrame
 * is defined as a structure and not as an opaque token. However, most
 * Tcl_CallFrame fields are hidden since applications should not access
 * them directly; others are declared as "dummyX".
 *
 * WARNING!! The structure definition must be kept consistent with the
 * CallFrame structure in tclInt.h. If you change one, change the other.
 */

typedef struct Tcl_CallFrame {
    Tcl_Namespace *nsPtr;
    int dummy1;
    int dummy2;
    char *dummy3;
    char *dummy4;
    char *dummy5;
    int dummy6;
    char *dummy7;
    char *dummy8;
    int dummy9;
    char* dummy10;
} Tcl_CallFrame;

/*
 * Information about commands that is returned by Tcl_GetCommandInfo and
 * passed to Tcl_SetCommandInfo. objProc is an objc/objv object-based
 * command procedure while proc is a traditional Tcl argc/argv
 * string-based procedure. Tcl_CreateObjCommand and Tcl_CreateCommand
 * ensure that both objProc and proc are non-NULL and can be called to
 * execute the command. However, it may be faster to call one instead of
 * the other. The member isNativeObjectProc is set to 1 if an
 * object-based procedure was registered by Tcl_CreateObjCommand, and to
 * 0 if a string-based procedure was registered by Tcl_CreateCommand.
 * The other procedure is typically set to a compatibility wrapper that
 * does string-to-object or object-to-string argument conversions then
 * calls the other procedure.
 */
     
typedef struct Tcl_CmdInfo {
    int isNativeObjectProc;	 /* 1 if objProc was registered by a call to
				  * Tcl_CreateObjCommand; 0 otherwise.
				  * Tcl_SetCmdInfo does not modify this
				  * field. */
    Tcl_ObjCmdProc *objProc;	 /* Command's object-based procedure. */
    ClientData objClientData;	 /* ClientData for object proc. */
    Tcl_CmdProc *proc;		 /* Command's string-based procedure. */
    ClientData clientData;	 /* ClientData for string proc. */
    Tcl_CmdDeleteProc *deleteProc;
                                 /* Procedure to call when command is
                                  * deleted. */
    ClientData deleteData;	 /* Value to pass to deleteProc (usually
				  * the same as clientData). */
    Tcl_Namespace *namespacePtr; /* Points to the namespace that contains
				  * this command. Note that Tcl_SetCmdInfo
				  * will not change a command's namespace;
				  * use Tcl_RenameCommand to do that. */

} Tcl_CmdInfo;

/*
 * The structure defined below is used to hold dynamic strings.  The only
 * field that clients should use is the string field, and they should
 * never modify it.
 */

#define TCL_DSTRING_STATIC_SIZE 200
typedef struct Tcl_DString {
    char *string;		/* Points to beginning of string:  either
				 * staticSpace below or a malloced array. */
    int length;			/* Number of non-NULL characters in the
				 * string. */
    int spaceAvl;		/* Total number of bytes available for the
				 * string and its terminating NULL char. */
    char staticSpace[TCL_DSTRING_STATIC_SIZE];
				/* Space to use in common case where string
				 * is small. */
} Tcl_DString;

#define Tcl_DStringLength(dsPtr) ((dsPtr)->length)
#define Tcl_DStringValue(dsPtr) ((dsPtr)->string)
#define Tcl_DStringTrunc Tcl_DStringSetLength

/*
 * Definitions for the maximum number of digits of precision that may
 * be specified in the "tcl_precision" variable, and the number of
 * characters of buffer space required by Tcl_PrintDouble.
 */
 
#define TCL_MAX_PREC 17
#define TCL_DOUBLE_SPACE (TCL_MAX_PREC+10)

/*
 * Flag that may be passed to Tcl_ConvertElement to force it not to
 * output braces (careful!  if you change this flag be sure to change
 * the definitions at the front of tclUtil.c).
 */

#define TCL_DONT_USE_BRACES	1

/*
 * Flag that may be passed to Tcl_GetIndexFromObj to force it to disallow
 * abbreviated strings.
 */

#define TCL_EXACT	1

/*
 * Flag values passed to Tcl_RecordAndEval.
 * WARNING: these bit choices must not conflict with the bit choices
 * for evalFlag bits in tclInt.h!!
 */

#define TCL_NO_EVAL		0x10000
#define TCL_EVAL_GLOBAL		0x20000

/*
 * Special freeProc values that may be passed to Tcl_SetResult (see
 * the man page for details):
 */

#define TCL_VOLATILE	((Tcl_FreeProc *) 1)
#define TCL_STATIC	((Tcl_FreeProc *) 0)
#define TCL_DYNAMIC	((Tcl_FreeProc *) 3)

/*
 * Flag values passed to variable-related procedures.
 */

#define TCL_GLOBAL_ONLY		 1
#define TCL_NAMESPACE_ONLY	 2
#define TCL_APPEND_VALUE	 4
#define TCL_LIST_ELEMENT	 8
#define TCL_TRACE_READS		 0x10
#define TCL_TRACE_WRITES	 0x20
#define TCL_TRACE_UNSETS	 0x40
#define TCL_TRACE_DESTROYED	 0x80
#define TCL_INTERP_DESTROYED	 0x100
#define TCL_LEAVE_ERR_MSG	 0x200
#define TCL_PARSE_PART1		 0x400

/*
 * Types for linked variables:
 */

#define TCL_LINK_INT		1
#define TCL_LINK_DOUBLE		2
#define TCL_LINK_BOOLEAN	3
#define TCL_LINK_STRING		4
#define TCL_LINK_READ_ONLY	0x80

/*
 * The following declarations either map ckalloc and ckfree to
 * malloc and free, or they map them to procedures with all sorts
 * of debugging hooks defined in tclCkalloc.c.
 */

EXTERN char *		Tcl_Alloc _ANSI_ARGS_((unsigned int size));
EXTERN void		Tcl_Free _ANSI_ARGS_((char *ptr));
EXTERN char *		Tcl_Realloc _ANSI_ARGS_((char *ptr,
			    unsigned int size));

#ifdef TCL_MEM_DEBUG

#  define Tcl_Alloc(x) Tcl_DbCkalloc(x, __FILE__, __LINE__)
#  define Tcl_Free(x)  Tcl_DbCkfree(x, __FILE__, __LINE__)
#  define Tcl_Realloc(x,y) Tcl_DbCkrealloc((x), (y),__FILE__, __LINE__)
#  define ckalloc(x) Tcl_DbCkalloc(x, __FILE__, __LINE__)
#  define ckfree(x)  Tcl_DbCkfree(x, __FILE__, __LINE__)
#  define ckrealloc(x,y) Tcl_DbCkrealloc((x), (y),__FILE__, __LINE__)

EXTERN int		Tcl_DumpActiveMemory _ANSI_ARGS_((char *fileName));
EXTERN void		Tcl_ValidateAllMemory _ANSI_ARGS_((char *file,
			    int line));

#else

/*
 * If USE_TCLALLOC is true, then we need to call Tcl_Alloc instead of
 * the native malloc/free.  The only time USE_TCLALLOC should not be
 * true is when compiling the Tcl/Tk libraries on Unix systems.  In this
 * case we can safely call the native malloc/free directly as a performance
 * optimization.
 */

#  if USE_TCLALLOC
#     define ckalloc(x) Tcl_Alloc(x)
#     define ckfree(x) Tcl_Free(x)
#     define ckrealloc(x,y) Tcl_Realloc(x,y)
#  else
#     define ckalloc(x) malloc(x)
#     define ckfree(x)  free(x)
#     define ckrealloc(x,y) realloc(x,y)
#  endif
#  define Tcl_DumpActiveMemory(x)
#  define Tcl_ValidateAllMemory(x,y)

#endif /* TCL_MEM_DEBUG */

/*
 * Forward declaration of Tcl_HashTable.  Needed by some C++ compilers
 * to prevent errors when the forward reference to Tcl_HashTable is
 * encountered in the Tcl_HashEntry structure.
 */

#ifdef __cplusplus
struct Tcl_HashTable;
#endif

/*
 * Structure definition for an entry in a hash table.  No-one outside
 * Tcl should access any of these fields directly;  use the macros
 * defined below.
 */

typedef struct Tcl_HashEntry {
    struct Tcl_HashEntry *nextPtr;	/* Pointer to next entry in this
					 * hash bucket, or NULL for end of
					 * chain. */
    struct Tcl_HashTable *tablePtr;	/* Pointer to table containing entry. */
    struct Tcl_HashEntry **bucketPtr;	/* Pointer to bucket that points to
					 * first entry in this entry's chain:
					 * used for deleting the entry. */
    ClientData clientData;		/* Application stores something here
					 * with Tcl_SetHashValue. */
    union {				/* Key has one of these forms: */
	char *oneWordValue;		/* One-word value for key. */
	int words[1];			/* Multiple integer words for key.
					 * The actual size will be as large
					 * as necessary for this table's
					 * keys. */
	char string[4];			/* String for key.  The actual size
					 * will be as large as needed to hold
					 * the key. */
    } key;				/* MUST BE LAST FIELD IN RECORD!! */
} Tcl_HashEntry;

/*
 * Structure definition for a hash table.  Must be in tcl.h so clients
 * can allocate space for these structures, but clients should never
 * access any fields in this structure.
 */

#define TCL_SMALL_HASH_TABLE 4
typedef struct Tcl_HashTable {
    Tcl_HashEntry **buckets;		/* Pointer to bucket array.  Each
					 * element points to first entry in
					 * bucket's hash chain, or NULL. */
    Tcl_HashEntry *staticBuckets[TCL_SMALL_HASH_TABLE];
					/* Bucket array used for small tables
					 * (to avoid mallocs and frees). */
    int numBuckets;			/* Total number of buckets allocated
					 * at **bucketPtr. */
    int numEntries;			/* Total number of entries present
					 * in table. */
    int rebuildSize;			/* Enlarge table when numEntries gets
					 * to be this large. */
    int downShift;			/* Shift count used in hashing
					 * function.  Designed to use high-
					 * order bits of randomized keys. */
    int mask;				/* Mask value used in hashing
					 * function. */
    int keyType;			/* Type of keys used in this table. 
					 * It's either TCL_STRING_KEYS,
					 * TCL_ONE_WORD_KEYS, or an integer
					 * giving the number of ints that
                                         * is the size of the key.
					 */
    Tcl_HashEntry *(*findProc) _ANSI_ARGS_((struct Tcl_HashTable *tablePtr,
	    CONST char *key));
    Tcl_HashEntry *(*createProc) _ANSI_ARGS_((struct Tcl_HashTable *tablePtr,
	    CONST char *key, int *newPtr));
} Tcl_HashTable;

/*
 * Structure definition for information used to keep track of searches
 * through hash tables:
 */

typedef struct Tcl_HashSearch {
    Tcl_HashTable *tablePtr;		/* Table being searched. */
    int nextIndex;			/* Index of next bucket to be
					 * enumerated after present one. */
    Tcl_HashEntry *nextEntryPtr;	/* Next entry to be enumerated in the
					 * the current bucket. */
} Tcl_HashSearch;

/*
 * Acceptable key types for hash tables:
 */

#define TCL_STRING_KEYS		0
#define TCL_ONE_WORD_KEYS	1

/*
 * Macros for clients to use to access fields of hash entries:
 */

#define Tcl_GetHashValue(h) ((h)->clientData)
#define Tcl_SetHashValue(h, value) ((h)->clientData = (ClientData) (value))
#define Tcl_GetHashKey(tablePtr, h) \
    ((char *) (((tablePtr)->keyType == TCL_ONE_WORD_KEYS) ? (h)->key.oneWordValue \
						: (h)->key.string))

/*
 * Macros to use for clients to use to invoke find and create procedures
 * for hash tables:
 */

#define Tcl_FindHashEntry(tablePtr, key) \
	(*((tablePtr)->findProc))(tablePtr, key)
#define Tcl_CreateHashEntry(tablePtr, key, newPtr) \
	(*((tablePtr)->createProc))(tablePtr, key, newPtr)

/*
 * Flag values to pass to Tcl_DoOneEvent to disable searches
 * for some kinds of events:
 */

#define TCL_DONT_WAIT		(1<<1)
#define TCL_WINDOW_EVENTS	(1<<2)
#define TCL_FILE_EVENTS		(1<<3)
#define TCL_TIMER_EVENTS	(1<<4)
#define TCL_IDLE_EVENTS		(1<<5)	/* WAS 0x10 ???? */
#define TCL_ALL_EVENTS		(~TCL_DONT_WAIT)

/*
 * The following structure defines a generic event for the Tcl event
 * system.  These are the things that are queued in calls to Tcl_QueueEvent
 * and serviced later by Tcl_DoOneEvent.  There can be many different
 * kinds of events with different fields, corresponding to window events,
 * timer events, etc.  The structure for a particular event consists of
 * a Tcl_Event header followed by additional information specific to that
 * event.
 */

struct Tcl_Event {
    Tcl_EventProc *proc;	/* Procedure to call to service this event. */
    struct Tcl_Event *nextPtr;	/* Next in list of pending events, or NULL. */
};

/*
 * Positions to pass to Tcl_QueueEvent:
 */

typedef enum {
    TCL_QUEUE_TAIL, TCL_QUEUE_HEAD, TCL_QUEUE_MARK
} Tcl_QueuePosition;

/*
 * Values to pass to Tcl_SetServiceMode to specify the behavior of notifier
 * event routines.
 */

#define TCL_SERVICE_NONE 0
#define TCL_SERVICE_ALL 1

/*
 * The following structure keeps is used to hold a time value, either as
 * an absolute time (the number of seconds from the epoch) or as an
 * elapsed time. On Unix systems the epoch is Midnight Jan 1, 1970 GMT.
 * On Macintosh systems the epoch is Midnight Jan 1, 1904 GMT.
 */

typedef struct Tcl_Time {
    long sec;			/* Seconds. */
    long usec;			/* Microseconds. */
} Tcl_Time;

/*
 * Bits to pass to Tcl_CreateFileHandler and Tcl_CreateChannelHandler
 * to indicate what sorts of events are of interest:
 */

#define TCL_READABLE	(1<<1)
#define TCL_WRITABLE	(1<<2)
#define TCL_EXCEPTION	(1<<3)

/*
 * Flag values to pass to Tcl_OpenCommandChannel to indicate the
 * disposition of the stdio handles.  TCL_STDIN, TCL_STDOUT, TCL_STDERR,
 * are also used in Tcl_GetStdChannel.
 */

#define TCL_STDIN		(1<<1)	
#define TCL_STDOUT		(1<<2)
#define TCL_STDERR		(1<<3)
#define TCL_ENFORCE_MODE	(1<<4)

/*
 * Typedefs for the various operations in a channel type:
 */

typedef int	(Tcl_DriverBlockModeProc) _ANSI_ARGS_((
		    ClientData instanceData, int mode));
typedef int	(Tcl_DriverCloseProc) _ANSI_ARGS_((ClientData instanceData,
		    Tcl_Interp *interp));
typedef int	(Tcl_DriverInputProc) _ANSI_ARGS_((ClientData instanceData,
		    char *buf, int toRead, int *errorCodePtr));
typedef int	(Tcl_DriverOutputProc) _ANSI_ARGS_((ClientData instanceData,
		    char *buf, int toWrite, int *errorCodePtr));
typedef int	(Tcl_DriverSeekProc) _ANSI_ARGS_((ClientData instanceData,
		    long offset, int mode, int *errorCodePtr));
typedef int	(Tcl_DriverSetOptionProc) _ANSI_ARGS_((
		    ClientData instanceData, Tcl_Interp *interp,
	            char *optionName, char *value));
typedef int	(Tcl_DriverGetOptionProc) _ANSI_ARGS_((
		    ClientData instanceData, Tcl_Interp *interp,
		    char *optionName, Tcl_DString *dsPtr));
typedef void	(Tcl_DriverWatchProc) _ANSI_ARGS_((
		    ClientData instanceData, int mask));
typedef int	(Tcl_DriverGetHandleProc) _ANSI_ARGS_((
		    ClientData instanceData, int direction,
		    ClientData *handlePtr));

/*
 * Enum for different end of line translation and recognition modes.
 */

typedef enum Tcl_EolTranslation {
    TCL_TRANSLATE_AUTO,			/* Eol == \r, \n and \r\n. */
    TCL_TRANSLATE_CR,			/* Eol == \r. */
    TCL_TRANSLATE_LF,			/* Eol == \n. */
    TCL_TRANSLATE_CRLF			/* Eol == \r\n. */
} Tcl_EolTranslation;

/*
 * struct Tcl_ChannelType:
 *
 * One such structure exists for each type (kind) of channel.
 * It collects together in one place all the functions that are
 * part of the specific channel type.
 */

typedef struct Tcl_ChannelType {
    char *typeName;			/* The name of the channel type in Tcl
                                         * commands. This storage is owned by
                                         * channel type. */
    Tcl_DriverBlockModeProc *blockModeProc;
    					/* Set blocking mode for the
                                         * raw channel. May be NULL. */
    Tcl_DriverCloseProc *closeProc;	/* Procedure to call to close
                                         * the channel. */
    Tcl_DriverInputProc *inputProc;	/* Procedure to call for input
                                         * on channel. */
    Tcl_DriverOutputProc *outputProc;	/* Procedure to call for output
                                         * on channel. */
    Tcl_DriverSeekProc *seekProc;	/* Procedure to call to seek
                                         * on the channel. May be NULL. */
    Tcl_DriverSetOptionProc *setOptionProc;
    					/* Set an option on a channel. */
    Tcl_DriverGetOptionProc *getOptionProc;
    					/* Get an option from a channel. */
    Tcl_DriverWatchProc *watchProc;	/* Set up the notifier to watch
                                         * for events on this channel. */
    Tcl_DriverGetHandleProc *getHandleProc;
					/* Get an OS handle from the channel
                                         * or NULL if not supported. */
    VOID *reserved;			/* reserved for future expansion */
} Tcl_ChannelType;

/*
 * The following flags determine whether the blockModeProc above should
 * set the channel into blocking or nonblocking mode. They are passed
 * as arguments to the blockModeProc procedure in the above structure.
 */

#define TCL_MODE_BLOCKING 0		/* Put channel into blocking mode. */
#define TCL_MODE_NONBLOCKING 1		/* Put channel into nonblocking
					 * mode. */

/*
 * Enum for different types of file paths.
 */

typedef enum Tcl_PathType {
    TCL_PATH_ABSOLUTE,
    TCL_PATH_RELATIVE,
    TCL_PATH_VOLUME_RELATIVE
} Tcl_PathType;

/*
 * Exported Tcl procedures:
 */

EXTERN void		Tcl_AddErrorInfo _ANSI_ARGS_((Tcl_Interp *interp,
			    char *message));
EXTERN void		Tcl_AddObjErrorInfo _ANSI_ARGS_((Tcl_Interp *interp,
			    char *message, int length));
EXTERN void		Tcl_AllowExceptions _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN int		Tcl_AppendAllObjTypes _ANSI_ARGS_((
			    Tcl_Interp *interp, Tcl_Obj *objPtr));
EXTERN void		Tcl_AppendElement _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string));
EXTERN void		Tcl_AppendResult _ANSI_ARGS_(
			    TCL_VARARGS(Tcl_Interp *,interp));
EXTERN void		Tcl_AppendToObj _ANSI_ARGS_((Tcl_Obj *objPtr,
			    char *bytes, int length));
EXTERN void		Tcl_AppendStringsToObj _ANSI_ARGS_(
			    TCL_VARARGS(Tcl_Obj *,interp));
EXTERN Tcl_AsyncHandler	Tcl_AsyncCreate _ANSI_ARGS_((Tcl_AsyncProc *proc,
			    ClientData clientData));
EXTERN void		Tcl_AsyncDelete _ANSI_ARGS_((Tcl_AsyncHandler async));
EXTERN int		Tcl_AsyncInvoke _ANSI_ARGS_((Tcl_Interp *interp,
			    int code));
EXTERN void		Tcl_AsyncMark _ANSI_ARGS_((Tcl_AsyncHandler async));
EXTERN int		Tcl_AsyncReady _ANSI_ARGS_((void));
EXTERN void		Tcl_BackgroundError _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN char		Tcl_Backslash _ANSI_ARGS_((CONST char *src,
			    int *readPtr));
EXTERN int		Tcl_BadChannelOption _ANSI_ARGS_((Tcl_Interp *interp,
			    char *optionName, char *optionList));
EXTERN void		Tcl_CallWhenDeleted _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_InterpDeleteProc *proc,
			    ClientData clientData));
EXTERN void		Tcl_CancelIdleCall _ANSI_ARGS_((Tcl_IdleProc *idleProc,
			    ClientData clientData));
#define Tcl_Ckalloc Tcl_Alloc
#define Tcl_Ckfree Tcl_Free
#define Tcl_Ckrealloc Tcl_Realloc
EXTERN int		Tcl_Close _ANSI_ARGS_((Tcl_Interp *interp,
        		    Tcl_Channel chan));
EXTERN int		Tcl_CommandComplete _ANSI_ARGS_((char *cmd));
EXTERN char *		Tcl_Concat _ANSI_ARGS_((int argc, char **argv));
EXTERN Tcl_Obj *	Tcl_ConcatObj _ANSI_ARGS_((int objc,
			    Tcl_Obj *CONST objv[]));
EXTERN int		Tcl_ConvertCountedElement _ANSI_ARGS_((CONST char *src,
			    int length, char *dst, int flags));
EXTERN int		Tcl_ConvertElement _ANSI_ARGS_((CONST char *src,
			    char *dst, int flags));
EXTERN int		Tcl_ConvertToType _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *objPtr, Tcl_ObjType *typePtr));
EXTERN int		Tcl_CreateAlias _ANSI_ARGS_((Tcl_Interp *slave,
			    char *slaveCmd, Tcl_Interp *target,
        		    char *targetCmd, int argc, char **argv));
EXTERN int		Tcl_CreateAliasObj _ANSI_ARGS_((Tcl_Interp *slave,
			    char *slaveCmd, Tcl_Interp *target,
        		    char *targetCmd, int objc,
		            Tcl_Obj *CONST objv[]));
EXTERN Tcl_Channel	Tcl_CreateChannel _ANSI_ARGS_((
    			    Tcl_ChannelType *typePtr, char *chanName,
                            ClientData instanceData, int mask));
EXTERN void		Tcl_CreateChannelHandler _ANSI_ARGS_((
			    Tcl_Channel chan, int mask,
                            Tcl_ChannelProc *proc, ClientData clientData));
EXTERN void		Tcl_CreateCloseHandler _ANSI_ARGS_((
			    Tcl_Channel chan, Tcl_CloseProc *proc,
                            ClientData clientData));
EXTERN Tcl_Command	Tcl_CreateCommand _ANSI_ARGS_((Tcl_Interp *interp,
			    char *cmdName, Tcl_CmdProc *proc,
			    ClientData clientData,
			    Tcl_CmdDeleteProc *deleteProc));
EXTERN void		Tcl_CreateEventSource _ANSI_ARGS_((
			    Tcl_EventSetupProc *setupProc,
			    Tcl_EventCheckProc *checkProc,
			    ClientData clientData));
EXTERN void		Tcl_CreateExitHandler _ANSI_ARGS_((Tcl_ExitProc *proc,
			    ClientData clientData));
EXTERN void		Tcl_CreateFileHandler _ANSI_ARGS_((
    			    int fd, int mask, Tcl_FileProc *proc,
			    ClientData clientData));
EXTERN Tcl_Interp *	Tcl_CreateInterp _ANSI_ARGS_((void));
EXTERN void		Tcl_CreateMathFunc _ANSI_ARGS_((Tcl_Interp *interp,
			    char *name, int numArgs, Tcl_ValueType *argTypes,
			    Tcl_MathProc *proc, ClientData clientData));
EXTERN Tcl_Command	Tcl_CreateObjCommand _ANSI_ARGS_((
			    Tcl_Interp *interp, char *cmdName,
			    Tcl_ObjCmdProc *proc, ClientData clientData,
			    Tcl_CmdDeleteProc *deleteProc));
EXTERN Tcl_Interp *	Tcl_CreateSlave _ANSI_ARGS_((Tcl_Interp *interp,
		            char *slaveName, int isSafe));
EXTERN Tcl_TimerToken	Tcl_CreateTimerHandler _ANSI_ARGS_((int milliseconds,
			    Tcl_TimerProc *proc, ClientData clientData));
EXTERN Tcl_Trace	Tcl_CreateTrace _ANSI_ARGS_((Tcl_Interp *interp,
			    int level, Tcl_CmdTraceProc *proc,
			    ClientData clientData));
EXTERN char *		Tcl_DbCkalloc _ANSI_ARGS_((unsigned int size,
			    char *file, int line));
EXTERN int		Tcl_DbCkfree _ANSI_ARGS_((char *ptr,
			    char *file, int line));
EXTERN char *		Tcl_DbCkrealloc _ANSI_ARGS_((char *ptr,
			    unsigned int size, char *file, int line));
EXTERN void		Tcl_DbDecrRefCount _ANSI_ARGS_((Tcl_Obj *objPtr,
			    char *file, int line));
EXTERN void		Tcl_DbIncrRefCount _ANSI_ARGS_((Tcl_Obj *objPtr,
			    char *file, int line));
EXTERN int		Tcl_DbIsShared _ANSI_ARGS_((Tcl_Obj *objPtr,
			    char *file, int line));
EXTERN Tcl_Obj *	Tcl_DbNewBooleanObj _ANSI_ARGS_((int boolValue,
                            char *file, int line));
EXTERN Tcl_Obj *	Tcl_DbNewDoubleObj _ANSI_ARGS_((double doubleValue,
                            char *file, int line));
EXTERN Tcl_Obj *	Tcl_DbNewListObj _ANSI_ARGS_((int objc,
			    Tcl_Obj *CONST objv[], char *file, int line));
EXTERN Tcl_Obj *	Tcl_DbNewLongObj _ANSI_ARGS_((long longValue,
                            char *file, int line));
EXTERN Tcl_Obj *	Tcl_DbNewObj _ANSI_ARGS_((char *file, int line));
EXTERN Tcl_Obj *	Tcl_DbNewStringObj _ANSI_ARGS_((char *bytes,
			    int length, char *file, int line));
EXTERN void		Tcl_DeleteAssocData _ANSI_ARGS_((Tcl_Interp *interp,
                            char *name));
EXTERN int		Tcl_DeleteCommand _ANSI_ARGS_((Tcl_Interp *interp,
			    char *cmdName));
EXTERN int		Tcl_DeleteCommandFromToken _ANSI_ARGS_((
			    Tcl_Interp *interp, Tcl_Command command));
EXTERN void		Tcl_DeleteChannelHandler _ANSI_ARGS_((
    			    Tcl_Channel chan, Tcl_ChannelProc *proc,
                            ClientData clientData));
EXTERN void		Tcl_DeleteCloseHandler _ANSI_ARGS_((
			    Tcl_Channel chan, Tcl_CloseProc *proc,
                            ClientData clientData));
EXTERN void		Tcl_DeleteEvents _ANSI_ARGS_((
			    Tcl_EventDeleteProc *proc,
                            ClientData clientData));
EXTERN void		Tcl_DeleteEventSource _ANSI_ARGS_((
			    Tcl_EventSetupProc *setupProc,
			    Tcl_EventCheckProc *checkProc,
			    ClientData clientData));
EXTERN void		Tcl_DeleteExitHandler _ANSI_ARGS_((Tcl_ExitProc *proc,
			    ClientData clientData));
EXTERN void		Tcl_DeleteFileHandler _ANSI_ARGS_((int fd));
EXTERN void		Tcl_DeleteHashEntry _ANSI_ARGS_((
			    Tcl_HashEntry *entryPtr));
EXTERN void		Tcl_DeleteHashTable _ANSI_ARGS_((
			    Tcl_HashTable *tablePtr));
EXTERN void		Tcl_DeleteInterp _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN void		Tcl_DeleteTimerHandler _ANSI_ARGS_((
			    Tcl_TimerToken token));
EXTERN void		Tcl_DeleteTrace _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Trace trace));
EXTERN void		Tcl_DetachPids _ANSI_ARGS_((int numPids, Tcl_Pid *pidPtr));
EXTERN void		Tcl_DontCallWhenDeleted _ANSI_ARGS_((
			    Tcl_Interp *interp, Tcl_InterpDeleteProc *proc,
			    ClientData clientData));
EXTERN int		Tcl_DoOneEvent _ANSI_ARGS_((int flags));
EXTERN void		Tcl_DoWhenIdle _ANSI_ARGS_((Tcl_IdleProc *proc,
			    ClientData clientData));
EXTERN char *		Tcl_DStringAppend _ANSI_ARGS_((Tcl_DString *dsPtr,
			    CONST char *string, int length));
EXTERN char *		Tcl_DStringAppendElement _ANSI_ARGS_((
			    Tcl_DString *dsPtr, CONST char *string));
EXTERN void		Tcl_DStringEndSublist _ANSI_ARGS_((Tcl_DString *dsPtr));
EXTERN void		Tcl_DStringFree _ANSI_ARGS_((Tcl_DString *dsPtr));
EXTERN void		Tcl_DStringGetResult _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_DString *dsPtr));
EXTERN void		Tcl_DStringInit _ANSI_ARGS_((Tcl_DString *dsPtr));
EXTERN void		Tcl_DStringResult _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_DString *dsPtr));
EXTERN void		Tcl_DStringSetLength _ANSI_ARGS_((Tcl_DString *dsPtr,
			    int length));
EXTERN void		Tcl_DStringStartSublist _ANSI_ARGS_((
			    Tcl_DString *dsPtr));
EXTERN Tcl_Obj *	Tcl_DuplicateObj _ANSI_ARGS_((Tcl_Obj *objPtr));
EXTERN int		Tcl_Eof _ANSI_ARGS_((Tcl_Channel chan));
EXTERN char *		Tcl_ErrnoId _ANSI_ARGS_((void));
EXTERN char *		Tcl_ErrnoMsg _ANSI_ARGS_((int err));
EXTERN int		Tcl_Eval _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string));
EXTERN int		Tcl_EvalFile _ANSI_ARGS_((Tcl_Interp *interp,
			    char *fileName));
EXTERN void		Tcl_EventuallyFree _ANSI_ARGS_((ClientData clientData,
			    Tcl_FreeProc *freeProc));
EXTERN int		Tcl_EvalObj _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *objPtr));
EXTERN void		Tcl_Exit _ANSI_ARGS_((int status));
EXTERN int		Tcl_ExposeCommand _ANSI_ARGS_((Tcl_Interp *interp,
        		    char *hiddenCmdToken, char *cmdName));
EXTERN int		Tcl_ExprBoolean _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string, int *ptr));
EXTERN int		Tcl_ExprBooleanObj _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *objPtr, int *ptr));
EXTERN int		Tcl_ExprDouble _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string, double *ptr));
EXTERN int		Tcl_ExprDoubleObj _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *objPtr, double *ptr));
EXTERN int		Tcl_ExprLong _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string, long *ptr));
EXTERN int		Tcl_ExprLongObj _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *objPtr, long *ptr));
EXTERN int		Tcl_ExprObj _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *objPtr, Tcl_Obj **resultPtrPtr));
EXTERN int		Tcl_ExprString _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string));
EXTERN void		Tcl_Finalize _ANSI_ARGS_((void));
EXTERN void		Tcl_FindExecutable _ANSI_ARGS_((char *argv0));
EXTERN Tcl_HashEntry *	Tcl_FirstHashEntry _ANSI_ARGS_((
			    Tcl_HashTable *tablePtr,
			    Tcl_HashSearch *searchPtr));
EXTERN int		Tcl_Flush _ANSI_ARGS_((Tcl_Channel chan));
EXTERN void		TclFreeObj _ANSI_ARGS_((Tcl_Obj *objPtr));
EXTERN void		Tcl_FreeResult _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN int		Tcl_GetAlias _ANSI_ARGS_((Tcl_Interp *interp,
       			    char *slaveCmd, Tcl_Interp **targetInterpPtr,
                            char **targetCmdPtr, int *argcPtr,
			    char ***argvPtr));
EXTERN int		Tcl_GetAliasObj _ANSI_ARGS_((Tcl_Interp *interp,
       			    char *slaveCmd, Tcl_Interp **targetInterpPtr,
                            char **targetCmdPtr, int *objcPtr,
			    Tcl_Obj ***objv));
EXTERN ClientData	Tcl_GetAssocData _ANSI_ARGS_((Tcl_Interp *interp,
                            char *name, Tcl_InterpDeleteProc **procPtr));
EXTERN int		Tcl_GetBoolean _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string, int *boolPtr));
EXTERN int		Tcl_GetBooleanFromObj _ANSI_ARGS_((
			    Tcl_Interp *interp, Tcl_Obj *objPtr,
			    int *boolPtr));
EXTERN Tcl_Channel	Tcl_GetChannel _ANSI_ARGS_((Tcl_Interp *interp,
	        	    char *chanName, int *modePtr));
EXTERN int		Tcl_GetChannelBufferSize _ANSI_ARGS_((
    			    Tcl_Channel chan));
EXTERN int		Tcl_GetChannelHandle _ANSI_ARGS_((Tcl_Channel chan,
	        	    int direction, ClientData *handlePtr));
EXTERN ClientData	Tcl_GetChannelInstanceData _ANSI_ARGS_((
    			    Tcl_Channel chan));
EXTERN int		Tcl_GetChannelMode _ANSI_ARGS_((Tcl_Channel chan));
EXTERN char *		Tcl_GetChannelName _ANSI_ARGS_((Tcl_Channel chan));
EXTERN int		Tcl_GetChannelOption _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Channel chan, char *optionName,
			    Tcl_DString *dsPtr));
EXTERN Tcl_ChannelType * Tcl_GetChannelType _ANSI_ARGS_((Tcl_Channel chan));
EXTERN int		Tcl_GetCommandInfo _ANSI_ARGS_((Tcl_Interp *interp,
			    char *cmdName, Tcl_CmdInfo *infoPtr));
EXTERN char *		Tcl_GetCommandName _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Command command));
EXTERN int		Tcl_GetDouble _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string, double *doublePtr));
EXTERN int		Tcl_GetDoubleFromObj _ANSI_ARGS_((
			    Tcl_Interp *interp, Tcl_Obj *objPtr,
			    double *doublePtr));
EXTERN int		Tcl_GetErrno _ANSI_ARGS_((void));
EXTERN char *		Tcl_GetHostName _ANSI_ARGS_((void));
EXTERN int		Tcl_GetIndexFromObj _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *objPtr, char **tablePtr, char *msg,
			    int flags, int *indexPtr));
EXTERN int		Tcl_GetInt _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string, int *intPtr));
EXTERN int		Tcl_GetInterpPath _ANSI_ARGS_((Tcl_Interp *askInterp,
			    Tcl_Interp *slaveInterp));
EXTERN int		Tcl_GetIntFromObj _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *objPtr, int *intPtr));
EXTERN int		Tcl_GetLongFromObj _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *objPtr, long *longPtr));
EXTERN Tcl_Interp *	Tcl_GetMaster _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN CONST char *	Tcl_GetNameOfExecutable _ANSI_ARGS_((void));
EXTERN Tcl_Obj *	Tcl_GetObjResult _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN Tcl_ObjType *	Tcl_GetObjType _ANSI_ARGS_((char *typeName));
EXTERN int		Tcl_GetOpenFile _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string, int write, int checkUsage,
			    ClientData *filePtr));
EXTERN Tcl_PathType	Tcl_GetPathType _ANSI_ARGS_((char *path));
EXTERN int		Tcl_Gets _ANSI_ARGS_((Tcl_Channel chan,
        		    Tcl_DString *dsPtr));
EXTERN int		Tcl_GetsObj _ANSI_ARGS_((Tcl_Channel chan,
        		    Tcl_Obj *objPtr));
EXTERN int		Tcl_GetServiceMode _ANSI_ARGS_((void));
EXTERN Tcl_Interp *	Tcl_GetSlave _ANSI_ARGS_((Tcl_Interp *interp,
			    char *slaveName));
EXTERN Tcl_Channel	Tcl_GetStdChannel _ANSI_ARGS_((int type));
EXTERN char *		Tcl_GetStringFromObj _ANSI_ARGS_((Tcl_Obj *objPtr,
			    int *lengthPtr));
EXTERN char *		Tcl_GetStringResult _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN char *		Tcl_GetVar _ANSI_ARGS_((Tcl_Interp *interp,
			    char *varName, int flags));
EXTERN char *		Tcl_GetVar2 _ANSI_ARGS_((Tcl_Interp *interp,
			    char *part1, char *part2, int flags));
EXTERN int		Tcl_GlobalEval _ANSI_ARGS_((Tcl_Interp *interp,
			    char *command));
EXTERN int		Tcl_GlobalEvalObj _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *objPtr));
EXTERN char *		Tcl_HashStats _ANSI_ARGS_((Tcl_HashTable *tablePtr));
EXTERN int		Tcl_HideCommand _ANSI_ARGS_((Tcl_Interp *interp,
		            char *cmdName, char *hiddenCmdToken));
EXTERN int		Tcl_Init _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN void		Tcl_InitHashTable _ANSI_ARGS_((Tcl_HashTable *tablePtr,
			    int keyType));
EXTERN void		Tcl_InitMemory _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN int		Tcl_InputBlocked _ANSI_ARGS_((Tcl_Channel chan));
EXTERN int		Tcl_InputBuffered _ANSI_ARGS_((Tcl_Channel chan));
EXTERN int		Tcl_InterpDeleted _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN int		Tcl_IsSafe _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN void		Tcl_InvalidateStringRep _ANSI_ARGS_((
			    Tcl_Obj *objPtr));
EXTERN char *		Tcl_JoinPath _ANSI_ARGS_((int argc, char **argv,
			    Tcl_DString *resultPtr));
EXTERN int		Tcl_LinkVar _ANSI_ARGS_((Tcl_Interp *interp,
			    char *varName, char *addr, int type));
EXTERN int		Tcl_ListObjAppendList _ANSI_ARGS_((
			    Tcl_Interp *interp, Tcl_Obj *listPtr, 
			    Tcl_Obj *elemListPtr));
EXTERN int		Tcl_ListObjAppendElement _ANSI_ARGS_((
			    Tcl_Interp *interp, Tcl_Obj *listPtr,
			    Tcl_Obj *objPtr));
EXTERN int		Tcl_ListObjGetElements _ANSI_ARGS_((
			    Tcl_Interp *interp, Tcl_Obj *listPtr,
			    int *objcPtr, Tcl_Obj ***objvPtr));
EXTERN int		Tcl_ListObjIndex _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *listPtr, int index, 
			    Tcl_Obj **objPtrPtr));
EXTERN int		Tcl_ListObjLength _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *listPtr, int *intPtr));
EXTERN int		Tcl_ListObjReplace _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *listPtr, int first, int count,
			    int objc, Tcl_Obj *CONST objv[]));
EXTERN void		Tcl_Main _ANSI_ARGS_((int argc, char **argv,
			    Tcl_AppInitProc *appInitProc));
EXTERN Tcl_Channel	Tcl_MakeFileChannel _ANSI_ARGS_((ClientData handle,
			    int mode));
EXTERN int		Tcl_MakeSafe _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN Tcl_Channel	Tcl_MakeTcpClientChannel _ANSI_ARGS_((
    			    ClientData tcpSocket));
EXTERN char *		Tcl_Merge _ANSI_ARGS_((int argc, char **argv));
EXTERN Tcl_HashEntry *	Tcl_NextHashEntry _ANSI_ARGS_((
			    Tcl_HashSearch *searchPtr));
EXTERN void		Tcl_NotifyChannel _ANSI_ARGS_((Tcl_Channel channel,
			    int mask));
EXTERN Tcl_Obj *	Tcl_ObjGetVar2 _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *part1Ptr, Tcl_Obj *part2Ptr,
			    int flags));
EXTERN Tcl_Obj *	Tcl_ObjSetVar2 _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *part1Ptr, Tcl_Obj *part2Ptr,
			    Tcl_Obj *newValuePtr, int flags));
EXTERN Tcl_Channel	Tcl_OpenCommandChannel _ANSI_ARGS_((
    			    Tcl_Interp *interp, int argc, char **argv,
			    int flags));
EXTERN Tcl_Channel	Tcl_OpenFileChannel _ANSI_ARGS_((Tcl_Interp *interp,
        		    char *fileName, char *modeString,
                            int permissions));
EXTERN Tcl_Channel	Tcl_OpenTcpClient _ANSI_ARGS_((Tcl_Interp *interp,
			    int port, char *address, char *myaddr,
		            int myport, int async));
EXTERN Tcl_Channel	Tcl_OpenTcpServer _ANSI_ARGS_((Tcl_Interp *interp,
		            int port, char *host,
        		    Tcl_TcpAcceptProc *acceptProc,
			    ClientData callbackData));
EXTERN char *		Tcl_ParseVar _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string, char **termPtr));
EXTERN int		Tcl_PkgProvide _ANSI_ARGS_((Tcl_Interp *interp,
			    char *name, char *version));
EXTERN char *		Tcl_PkgRequire _ANSI_ARGS_((Tcl_Interp *interp,
			    char *name, char *version, int exact));
EXTERN char *		Tcl_PosixError _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN void		Tcl_Preserve _ANSI_ARGS_((ClientData data));
EXTERN void		Tcl_PrintDouble _ANSI_ARGS_((Tcl_Interp *interp,
			    double value, char *dst));
EXTERN int		Tcl_PutEnv _ANSI_ARGS_((CONST char *string));
EXTERN void		Tcl_QueueEvent _ANSI_ARGS_((Tcl_Event *evPtr,
			    Tcl_QueuePosition position));
EXTERN int		Tcl_Read _ANSI_ARGS_((Tcl_Channel chan,
	        	    char *bufPtr, int toRead));
EXTERN void		Tcl_ReapDetachedProcs _ANSI_ARGS_((void));
EXTERN int		Tcl_RecordAndEval _ANSI_ARGS_((Tcl_Interp *interp,
			    char *cmd, int flags));
EXTERN int		Tcl_RecordAndEvalObj _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *cmdPtr, int flags));
EXTERN Tcl_RegExp	Tcl_RegExpCompile _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string));
EXTERN int		Tcl_RegExpExec _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_RegExp regexp, char *string, char *start));
EXTERN int		Tcl_RegExpMatch _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string, char *pattern));
EXTERN void		Tcl_RegExpRange _ANSI_ARGS_((Tcl_RegExp regexp,
			    int index, char **startPtr, char **endPtr));
EXTERN void		Tcl_RegisterChannel _ANSI_ARGS_((Tcl_Interp *interp,
	        	    Tcl_Channel chan));
EXTERN void		Tcl_RegisterObjType _ANSI_ARGS_((
			    Tcl_ObjType *typePtr));
EXTERN void		Tcl_Release _ANSI_ARGS_((ClientData clientData));
EXTERN void		Tcl_ResetResult _ANSI_ARGS_((Tcl_Interp *interp));
#define Tcl_Return Tcl_SetResult
EXTERN int		Tcl_ScanCountedElement _ANSI_ARGS_((CONST char *string,
			    int length, int *flagPtr));
EXTERN int		Tcl_ScanElement _ANSI_ARGS_((CONST char *string,
			    int *flagPtr));
EXTERN int		Tcl_Seek _ANSI_ARGS_((Tcl_Channel chan,
        		    int offset, int mode));
EXTERN int		Tcl_ServiceAll _ANSI_ARGS_((void));
EXTERN int		Tcl_ServiceEvent _ANSI_ARGS_((int flags));
EXTERN void		Tcl_SetAssocData _ANSI_ARGS_((Tcl_Interp *interp,
                            char *name, Tcl_InterpDeleteProc *proc,
                            ClientData clientData));
EXTERN void		Tcl_SetBooleanObj _ANSI_ARGS_((Tcl_Obj *objPtr, 
			    int boolValue));
EXTERN void		Tcl_SetChannelBufferSize _ANSI_ARGS_((
			    Tcl_Channel chan, int sz));
EXTERN int		Tcl_SetChannelOption _ANSI_ARGS_((
			    Tcl_Interp *interp, Tcl_Channel chan,
	        	    char *optionName, char *newValue));
EXTERN int		Tcl_SetCommandInfo _ANSI_ARGS_((Tcl_Interp *interp,
			    char *cmdName, Tcl_CmdInfo *infoPtr));
EXTERN void		Tcl_SetDoubleObj _ANSI_ARGS_((Tcl_Obj *objPtr, 
			    double doubleValue));
EXTERN void		Tcl_SetErrno _ANSI_ARGS_((int err));
EXTERN void		Tcl_SetErrorCode _ANSI_ARGS_(
    			    TCL_VARARGS(Tcl_Interp *,arg1));
EXTERN void		Tcl_SetIntObj _ANSI_ARGS_((Tcl_Obj *objPtr, 
			    int intValue));
EXTERN void		Tcl_SetListObj _ANSI_ARGS_((Tcl_Obj *objPtr, 
			    int objc, Tcl_Obj *CONST objv[]));
EXTERN void		Tcl_SetLongObj _ANSI_ARGS_((Tcl_Obj *objPtr, 
			    long longValue));
EXTERN void		Tcl_SetMaxBlockTime _ANSI_ARGS_((Tcl_Time *timePtr));
EXTERN void		Tcl_SetObjErrorCode _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *errorObjPtr));
EXTERN void		Tcl_SetObjLength _ANSI_ARGS_((Tcl_Obj *objPtr,
			    int length));
EXTERN void		Tcl_SetObjResult _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Obj *resultObjPtr));
EXTERN void		Tcl_SetPanicProc _ANSI_ARGS_((void (*proc)
			    _ANSI_ARGS_(TCL_VARARGS(char *, format))));
EXTERN int		Tcl_SetRecursionLimit _ANSI_ARGS_((Tcl_Interp *interp,
			    int depth));
EXTERN void		Tcl_SetResult _ANSI_ARGS_((Tcl_Interp *interp,
			    char *string, Tcl_FreeProc *freeProc));
EXTERN int		Tcl_SetServiceMode _ANSI_ARGS_((int mode));
EXTERN void		Tcl_SetStdChannel _ANSI_ARGS_((Tcl_Channel channel,
			    int type));
EXTERN void		Tcl_SetStringObj _ANSI_ARGS_((Tcl_Obj *objPtr, 
			    char *bytes, int length));
EXTERN void		Tcl_SetTimer _ANSI_ARGS_((Tcl_Time *timePtr));
EXTERN char *		Tcl_SetVar _ANSI_ARGS_((Tcl_Interp *interp,
			    char *varName, char *newValue, int flags));
EXTERN char *		Tcl_SetVar2 _ANSI_ARGS_((Tcl_Interp *interp,
			    char *part1, char *part2, char *newValue,
			    int flags));
EXTERN char *		Tcl_SignalId _ANSI_ARGS_((int sig));
EXTERN char *		Tcl_SignalMsg _ANSI_ARGS_((int sig));
EXTERN void		Tcl_Sleep _ANSI_ARGS_((int ms));
EXTERN void		Tcl_SourceRCFile _ANSI_ARGS_((Tcl_Interp *interp));
EXTERN int		Tcl_SplitList _ANSI_ARGS_((Tcl_Interp *interp,
			    char *list, int *argcPtr, char ***argvPtr));
EXTERN void		Tcl_SplitPath _ANSI_ARGS_((char *path,
			    int *argcPtr, char ***argvPtr));
EXTERN void		Tcl_StaticPackage _ANSI_ARGS_((Tcl_Interp *interp,
			    char *pkgName, Tcl_PackageInitProc *initProc,
			    Tcl_PackageInitProc *safeInitProc));
EXTERN int		Tcl_StringMatch _ANSI_ARGS_((char *string,
			    char *pattern));
EXTERN int		Tcl_Tell _ANSI_ARGS_((Tcl_Channel chan));
#define Tcl_TildeSubst Tcl_TranslateFileName
EXTERN int		Tcl_TraceVar _ANSI_ARGS_((Tcl_Interp *interp,
			    char *varName, int flags, Tcl_VarTraceProc *proc,
			    ClientData clientData));
EXTERN int		Tcl_TraceVar2 _ANSI_ARGS_((Tcl_Interp *interp,
			    char *part1, char *part2, int flags,
			    Tcl_VarTraceProc *proc, ClientData clientData));
EXTERN char *		Tcl_TranslateFileName _ANSI_ARGS_((Tcl_Interp *interp,
			    char *name, Tcl_DString *bufferPtr));
EXTERN int		Tcl_Ungets _ANSI_ARGS_((Tcl_Channel chan, char *str,
			    int len, int atHead));
EXTERN void		Tcl_UnlinkVar _ANSI_ARGS_((Tcl_Interp *interp,
			    char *varName));
EXTERN int		Tcl_UnregisterChannel _ANSI_ARGS_((Tcl_Interp *interp,
			    Tcl_Channel chan));
EXTERN int		Tcl_UnsetVar _ANSI_ARGS_((Tcl_Interp *interp,
			    char *varName, int flags));
EXTERN int		Tcl_UnsetVar2 _ANSI_ARGS_((Tcl_Interp *interp,
			    char *part1, char *part2, int flags));
EXTERN void		Tcl_UntraceVar _ANSI_ARGS_((Tcl_Interp *interp,
			    char *varName, int flags, Tcl_VarTraceProc *proc,
			    ClientData clientData));
EXTERN void		Tcl_UntraceVar2 _ANSI_ARGS_((Tcl_Interp *interp,
			    char *part1, char *part2, int flags,
			    Tcl_VarTraceProc *proc, ClientData clientData));
EXTERN void		Tcl_UpdateLinkedVar _ANSI_ARGS_((Tcl_Interp *interp,
			    char *varName));
EXTERN int		Tcl_UpVar _ANSI_ARGS_((Tcl_Interp *interp,
			    char *frameName, char *varName,
			    char *localName, int flags));
EXTERN int		Tcl_UpVar2 _ANSI_ARGS_((Tcl_Interp *interp,
			    char *frameName, char *part1, char *part2,
			    char *localName, int flags));
EXTERN int		Tcl_VarEval _ANSI_ARGS_(
    			    TCL_VARARGS(Tcl_Interp *,interp));
EXTERN ClientData	Tcl_VarTraceInfo _ANSI_ARGS_((Tcl_Interp *interp,
			    char *varName, int flags,
			    Tcl_VarTraceProc *procPtr,
			    ClientData prevClientData));
EXTERN ClientData	Tcl_VarTraceInfo2 _ANSI_ARGS_((Tcl_Interp *interp,
			    char *part1, char *part2, int flags,
			    Tcl_VarTraceProc *procPtr,
			    ClientData prevClientData));
EXTERN int		Tcl_WaitForEvent _ANSI_ARGS_((Tcl_Time *timePtr));
EXTERN Tcl_Pid		Tcl_WaitPid _ANSI_ARGS_((Tcl_Pid pid, int *statPtr, 
			    int options));
EXTERN int		Tcl_Write _ANSI_ARGS_((Tcl_Channel chan,
			    char *s, int slen));
EXTERN void		Tcl_WrongNumArgs _ANSI_ARGS_((Tcl_Interp *interp,
			    int objc, Tcl_Obj *CONST objv[], char *message));

#undef TCL_STORAGE_CLASS
#define TCL_STORAGE_CLASS

/*
 * Convenience declaration of Tcl_AppInit for backwards compatibility.
 * This function is not *implemented* by the tcl library, so the storage
 * class is neither DLLEXPORT nor DLLIMPORT
 */

EXTERN int             Tcl_AppInit _ANSI_ARGS_((Tcl_Interp *interp));

#endif /* RESOURCE_INCLUDED */

#undef TCL_STORAGE_CLASS
#define TCL_STORAGE_CLASS DLLIMPORT

#endif /* _TCL */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted generic/tclFCmd.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
/*
 * tclFCmd.c
 *
 *      This file implements the generic portion of file manipulation 
 *      subcommands of the "file" command. 
 *
 * Copyright (c) 1996-1997 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: tclFCmd.c,v 1.3 1998/09/14 18:39:59 stanton Exp $
 */

#include "tclInt.h"
#include "tclPort.h"

/*
 * Declarations for local procedures defined in this file:
 */

static int		CopyRenameOneFile _ANSI_ARGS_((Tcl_Interp *interp,
			    char *source, char *dest, int copyFlag,
			    int force));
static char *		FileBasename _ANSI_ARGS_((Tcl_Interp *interp,
			    char *path, Tcl_DString *bufferPtr));
static int		FileCopyRename _ANSI_ARGS_((Tcl_Interp *interp,
			    int argc, char **argv, int copyFlag));
static int		FileForceOption _ANSI_ARGS_((Tcl_Interp *interp,
			    int argc, char **argv, int *forcePtr));
 
/*
 *---------------------------------------------------------------------------
 *
 * TclFileRenameCmd
 *
 *	This procedure implements the "rename" subcommand of the "file"
 *      command.  Filename arguments need to be translated to native
 *	format before being passed to platform-specific code that
 *	implements rename functionality.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *---------------------------------------------------------------------------
 */

int
TclFileRenameCmd(interp, argc, argv)
    Tcl_Interp *interp;		/* Interp for error reporting. */
    int argc;			/* Number of arguments. */
    char **argv;		/* Argument strings passed to Tcl_FileCmd. */
{
    return FileCopyRename(interp, argc, argv, 0);
}
 
/*
 *---------------------------------------------------------------------------
 *
 * TclFileCopyCmd
 *
 *	This procedure implements the "copy" subcommand of the "file"
 *	command.  Filename arguments need to be translated to native
 *	format before being passed to platform-specific code that
 *	implements copy functionality.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *---------------------------------------------------------------------------
 */

int
TclFileCopyCmd(interp, argc, argv)
    Tcl_Interp *interp;		/* Used for error reporting */
    int argc;			/* Number of arguments. */
    char **argv;		/* Argument strings passed to Tcl_FileCmd. */
{
    return FileCopyRename(interp, argc, argv, 1);
}
 
/*
 *---------------------------------------------------------------------------
 *
 * FileCopyRename --
 *
 *	Performs the work of TclFileRenameCmd and TclFileCopyCmd.
 *	See comments for those procedures.
 *
 * Results:
 *	See above.
 *
 * Side effects:
 *	See above.
 *
 *---------------------------------------------------------------------------
 */

static int
FileCopyRename(interp, argc, argv, copyFlag)
    Tcl_Interp *interp;		/* Used for error reporting. */
    int argc;			/* Number of arguments. */
    char **argv;		/* Argument strings passed to Tcl_FileCmd. */
    int copyFlag;		/* If non-zero, copy source(s).  Otherwise,
				 * rename them. */
{
    int i, result, force;
    struct stat statBuf; 
    Tcl_DString targetBuffer;
    char *target;

    i = FileForceOption(interp, argc - 2, argv + 2, &force);
    if (i < 0) {
	return TCL_ERROR;
    }
    i += 2;
    if ((argc - i) < 2) {
	Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
		" ", argv[1], " ?options? source ?source ...? target\"", 
		(char *) NULL);
	return TCL_ERROR;
    }

    /*
     * If target doesn't exist or isn't a directory, try the copy/rename.
     * More than 2 arguments is only valid if the target is an existing
     * directory.
     */

    target = Tcl_TranslateFileName(interp, argv[argc - 1], &targetBuffer);
    if (target == NULL) {
	return TCL_ERROR;
    }

    result = TCL_OK;

    /*
     * Call TclStat() so that if target is a symlink that points to a
     * directory we will put the sources in that directory instead of
     * overwriting the symlink.
     */

    if ((TclStat(target, &statBuf) != 0) || !S_ISDIR(statBuf.st_mode)) {
	if ((argc - i) > 2) {
	    errno = ENOTDIR;
	    Tcl_PosixError(interp);
	    Tcl_AppendResult(interp, "error ",
		    ((copyFlag) ? "copying" : "renaming"), ": target \"",
		    argv[argc - 1], "\" is not a directory", (char *) NULL);
	    result = TCL_ERROR;
	} else {
	    /*
	     * Even though already have target == translated(argv[i+1]),
	     * pass the original argument down, so if there's an error, the
	     * error message will reflect the original arguments.
	     */

	    result = CopyRenameOneFile(interp, argv[i], argv[i + 1], copyFlag,
		    force);
	}
	Tcl_DStringFree(&targetBuffer);
	return result;
    }
    
    /*
     * Move each source file into target directory.  Extract the basename
     * from each source, and append it to the end of the target path.
     */
    
    for ( ; i < argc - 1; i++) {
	char *jargv[2];
	char *source, *newFileName;
	Tcl_DString sourceBuffer, newFileNameBuffer;

	source = FileBasename(interp, argv[i], &sourceBuffer);
	if (source == NULL) {
	    result = TCL_ERROR;
	    break;
	}
	jargv[0] = argv[argc - 1];
	jargv[1] = source;
	Tcl_DStringInit(&newFileNameBuffer);
	newFileName = Tcl_JoinPath(2, jargv, &newFileNameBuffer);
	result = CopyRenameOneFile(interp, argv[i], newFileName, copyFlag,
		force);
	Tcl_DStringFree(&sourceBuffer);
	Tcl_DStringFree(&newFileNameBuffer);

	if (result == TCL_ERROR) {
	    break;
	}
    }
    Tcl_DStringFree(&targetBuffer);
    return result;
}
 
/*
 *---------------------------------------------------------------------------
 *
 * TclFileMakeDirsCmd
 *
 *	This procedure implements the "mkdir" subcommand of the "file"
 *      command.  Filename arguments need to be translated to native
 *	format before being passed to platform-specific code that
 *	implements mkdir functionality.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *----------------------------------------------------------------------
 */
int
TclFileMakeDirsCmd(interp, argc, argv)
    Tcl_Interp *interp;		/* Used for error reporting. */
    int argc;			/* Number of arguments */
    char **argv;		/* Argument strings passed to Tcl_FileCmd. */
{
    Tcl_DString nameBuffer, targetBuffer;
    char *errfile;
    int result, i, j, pargc;
    char **pargv;
    struct stat statBuf;

    pargv = NULL;
    errfile = NULL;
    Tcl_DStringInit(&nameBuffer);
    Tcl_DStringInit(&targetBuffer);

    result = TCL_OK;
    for (i = 2; i < argc; i++) {
	char *name = Tcl_TranslateFileName(interp, argv[i], &nameBuffer);
	if (name == NULL) {
	    result = TCL_ERROR;
	    break;
	}

	Tcl_SplitPath(name, &pargc, &pargv);
	if (pargc == 0) {
	    errno = ENOENT;
	    errfile = argv[i];
	    break;
	}
	for (j = 0; j < pargc; j++) {
	    char *target = Tcl_JoinPath(j + 1, pargv, &targetBuffer);

	    /*
	     * Call TclStat() so that if target is a symlink that points
	     * to a directory we will create subdirectories in that
	     * directory.
	     */

	    if (TclStat(target, &statBuf) == 0) {
		if (!S_ISDIR(statBuf.st_mode)) {
		    errno = EEXIST;
		    errfile = target;
		    goto done;
		}
	    } else if ((errno != ENOENT)
		    || (TclpCreateDirectory(target) != TCL_OK)) {
		errfile = target;
		goto done;
	    }
	    Tcl_DStringFree(&targetBuffer);
	}
	ckfree((char *) pargv);
	pargv = NULL;
	Tcl_DStringFree(&nameBuffer);
    }
	
    done:
    if (errfile != NULL) {
	Tcl_AppendResult(interp, "can't create directory \"",
		errfile, "\": ", Tcl_PosixError(interp), (char *) NULL);
	result = TCL_ERROR;
    }

    Tcl_DStringFree(&nameBuffer);
    Tcl_DStringFree(&targetBuffer);
    if (pargv != NULL) {
	ckfree((char *) pargv);
    }
    return result;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TclFileDeleteCmd
 *
 *	This procedure implements the "delete" subcommand of the "file"
 *      command.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *----------------------------------------------------------------------
 */

int
TclFileDeleteCmd(interp, argc, argv)
    Tcl_Interp *interp;		/* Used for error reporting */
    int argc;			/* Number of arguments */
    char **argv;		/* Argument strings passed to Tcl_FileCmd. */
{
    Tcl_DString nameBuffer, errorBuffer;
    int i, force, result;
    char *errfile;
    
    i = FileForceOption(interp, argc - 2, argv + 2, &force);
    if (i < 0) {
	return TCL_ERROR;
    }
    i += 2;
    if ((argc - i) < 1) {
	Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
		" ", argv[1], " ?options? file ?file ...?\"", (char *) NULL);
	return TCL_ERROR;
    }

    errfile = NULL;
    result = TCL_OK;
    Tcl_DStringInit(&errorBuffer);
    Tcl_DStringInit(&nameBuffer);

    for ( ; i < argc; i++) {
	struct stat statBuf;
	char *name;

	errfile = argv[i];
	Tcl_DStringSetLength(&nameBuffer, 0);
	name = Tcl_TranslateFileName(interp, argv[i], &nameBuffer);
	if (name == NULL) {
	    result = TCL_ERROR;
	    goto done;
	}

	/*
	 * Call lstat() to get info so can delete symbolic link itself.
	 */

	if (lstat(name, &statBuf) != 0) {
	    /*
	     * Trying to delete a file that does not exist is not
	     * considered an error, just a no-op
	     */

	    if (errno != ENOENT) {
		result = TCL_ERROR;
	    }
	} else if (S_ISDIR(statBuf.st_mode)) {
	    result = TclpRemoveDirectory(name, force, &errorBuffer);
	    if (result != TCL_OK) {
		if ((force == 0) && (errno == EEXIST)) {
		    Tcl_AppendResult(interp, "error deleting \"", argv[i],
			    "\": directory not empty", (char *) NULL);
		    Tcl_PosixError(interp);
		    goto done;
		}

		/* 
		 * If possible, use the untranslated name for the file.
		 */
		 
		errfile = Tcl_DStringValue(&errorBuffer);
		if (strcmp(name, errfile) == 0) {
		    errfile = argv[i];
		}
	    }
	} else {
	    result = TclpDeleteFile(name);
	}
	
	if (result == TCL_ERROR) {
	    break;
	}
    }
    if (result != TCL_OK) {
	Tcl_AppendResult(interp, "error deleting \"", errfile,
		"\": ", Tcl_PosixError(interp), (char *) NULL);
    } 
    done:
    Tcl_DStringFree(&errorBuffer);
    Tcl_DStringFree(&nameBuffer);
    return result;
}
 
/*
 *---------------------------------------------------------------------------
 *
 * CopyRenameOneFile
 *
 *	Copies or renames specified source file or directory hierarchy
 *	to the specified target.  
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	Target is overwritten if the force flag is set.  Attempting to
 *	copy/rename a file onto a directory or a directory onto a file
 *	will always result in an error.  
 *
 *----------------------------------------------------------------------
 */

static int
CopyRenameOneFile(interp, source, target, copyFlag, force) 
    Tcl_Interp *interp;		/* Used for error reporting. */
    char *source;		/* Pathname of file to copy.  May need to
				 * be translated. */
    char *target;		/* Pathname of file to create/overwrite.
				 * May need to be translated. */
    int copyFlag;		/* If non-zero, copy files.  Otherwise,
				 * rename them. */
    int force;			/* If non-zero, overwrite target file if it
				 * exists.  Otherwise, error if target already
				 * exists. */
{
    int result;
    Tcl_DString sourcePath, targetPath, errorBuffer;
    char *targetName, *sourceName, *errfile;
    struct stat sourceStatBuf, targetStatBuf;
	
    sourceName = Tcl_TranslateFileName(interp, source, &sourcePath);
    if (sourceName == NULL) {
	return TCL_ERROR;
    }
    targetName = Tcl_TranslateFileName(interp, target, &targetPath);
    if (targetName == NULL) {
	Tcl_DStringFree(&sourcePath);
	return TCL_ERROR;
    }
    
    errfile = NULL;
    result = TCL_ERROR;
    Tcl_DStringInit(&errorBuffer);
    
    /*
     * We want to copy/rename links and not the files they point to, so we
     * use lstat(). If target is a link, we also want to replace the 
     * link and not the file it points to, so we also use lstat() on the
     * target.
     */

    if (lstat(sourceName, &sourceStatBuf) != 0) {
	errfile = source;
	goto done;
    }
    if (lstat(targetName, &targetStatBuf) != 0) {
	if (errno != ENOENT) {
	    errfile = target;
	    goto done;
	}
    } else {
	if (force == 0) {
	    errno = EEXIST;
	    errfile = target;
	    goto done;
	}

        /* 
         * Prevent copying or renaming a file onto itself.  Under Windows, 
         * stat always returns 0 for st_ino.  However, the Windows-specific 
         * code knows how to deal with copying or renaming a file on top of
         * itself.  It might be a good idea to write a stat that worked.
         */
     
        if ((sourceStatBuf.st_ino != 0) && (targetStatBuf.st_ino != 0)) {
            if ((sourceStatBuf.st_ino == targetStatBuf.st_ino) &&
            	    (sourceStatBuf.st_dev == targetStatBuf.st_dev)) {
            	result = TCL_OK;
            	goto done;
            }
        }

	/*
	 * Prevent copying/renaming a file onto a directory and
	 * vice-versa.  This is a policy decision based on the fact that
	 * existing implementations of copy and rename on all platforms
	 * also prevent this.
	 */

	if (S_ISDIR(sourceStatBuf.st_mode)
                && !S_ISDIR(targetStatBuf.st_mode)) {
	    errno = EISDIR;
	    Tcl_AppendResult(interp, "can't overwrite file \"", target,
		    "\" with directory \"", source, "\"", (char *) NULL);
	    goto done;
	}
	if (!S_ISDIR(sourceStatBuf.st_mode)
	        && S_ISDIR(targetStatBuf.st_mode)) {
	    errno = EISDIR;
	    Tcl_AppendResult(interp, "can't overwrite directory \"", target, 
	            "\" with file \"", source, "\"", (char *) NULL);
	    goto done;
	}
    }

    if (copyFlag == 0) {
	result = TclpRenameFile(sourceName, targetName);
	if (result == TCL_OK) {
	    goto done;
	}
	    
	if (errno == EINVAL) {
	    Tcl_AppendResult(interp, "error renaming \"", source, "\" to \"",
		    target, "\": trying to rename a volume or ",
		    "move a directory into itself", (char *) NULL);
	    goto done;
	} else if (errno != EXDEV) {
	    errfile = target;
	    goto done;
	}
	
	/*
	 * The rename failed because the move was across file systems.
	 * Fall through to copy file and then remove original.  Note that
	 * the low-level TclpRenameFile is allowed to implement
	 * cross-filesystem moves itself.
	 */
    }

    if (S_ISDIR(sourceStatBuf.st_mode)) {
	result = TclpCopyDirectory(sourceName, targetName, &errorBuffer);
	if (result != TCL_OK) {
	    errfile = Tcl_DStringValue(&errorBuffer);
	    if (strcmp(errfile, sourceName) == 0) {
		errfile = source;
	    } else if (strcmp(errfile, targetName) == 0) {
		errfile = target;
	    }
	}
    } else {
	result = TclpCopyFile(sourceName, targetName);
	if (result != TCL_OK) {
	    /*
	     * Well, there really shouldn't be a problem with source,
	     * because up there we checked to see if it was ok to copy it.
	     */

	    errfile = target;
	}
    }
    if ((copyFlag == 0) && (result == TCL_OK)) {
	if (S_ISDIR(sourceStatBuf.st_mode)) {
	    result = TclpRemoveDirectory(sourceName, 1, &errorBuffer);
	    if (result != TCL_OK) {
		errfile = Tcl_DStringValue(&errorBuffer);
		if (strcmp(errfile, sourceName) == 0) {
		    errfile = source;
		}
	    }
	} else {
	    result = TclpDeleteFile(sourceName);
	    if (result != TCL_OK) {
		errfile = source;
	    }
	}
	if (result != TCL_OK) {
	    Tcl_AppendResult(interp, "can't unlink \"", errfile, "\": ",
		    Tcl_PosixError(interp), (char *) NULL);
	    errfile = NULL;
	}
    }
    
    done:
    if (errfile != NULL) {
	Tcl_AppendResult(interp, 
		((copyFlag) ? "error copying \"" : "error renaming \""),
		source, (char *) NULL);
	if (errfile != source) {
	    Tcl_AppendResult(interp, "\" to \"", target, (char *) NULL);
	    if (errfile != target) {
		Tcl_AppendResult(interp, "\": \"", errfile, (char *) NULL);
	    }
	}
	Tcl_AppendResult(interp, "\": ", Tcl_PosixError(interp),
		(char *) NULL);
    }
    Tcl_DStringFree(&errorBuffer);
    Tcl_DStringFree(&sourcePath);
    Tcl_DStringFree(&targetPath);
    return result;
}
 
/*
 *---------------------------------------------------------------------------
 *
 * FileForceOption --
 *
 *	Helps parse command line options for file commands that take
 *	the "-force" and "--" options.
 *
 * Results:
 *	The return value is how many arguments from argv were consumed
 *	by this function, or -1 if there was an error parsing the
 *	options.  If an error occurred, an error message is left in
 *	interp->result.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

static int
FileForceOption(interp, argc, argv, forcePtr)
    Tcl_Interp *interp;		/* Interp, for error return. */
    int argc;			/* Number of arguments. */
    char **argv;		/* Argument strings.  First command line
    option, if it exists, begins at */
    int *forcePtr;		/* If the "-force" was specified, *forcePtr
				 * is filled with 1, otherwise with 0. */
{
    int force, i;
    
    force = 0;
    for (i = 0; i < argc; i++) {
	if (argv[i][0] != '-') {
	    break;
	}
	if (strcmp(argv[i], "-force") == 0) {
	    force = 1;
	} else if (strcmp(argv[i], "--") == 0) {
	    i++;
	    break;
	} else {
	    Tcl_AppendResult(interp, "bad option \"", argv[i], 
		    "\": should be -force or --", (char *)NULL);
	    return -1;
	}
    }
    *forcePtr = force;
    return i;
}
/*
 *---------------------------------------------------------------------------
 *
 * FileBasename --
 *
 *	Given a path in either tcl format (with / separators), or in the
 *	platform-specific format for the current platform, return all the
 *	characters in the path after the last directory separator.  But,
 *	if path is the root directory, returns no characters.
 *
 * Results:
 *	Appends the string that represents the basename to the end of
 *	the specified initialized DString, returning a pointer to the
 *	resulting string.  If there is an error, an error message is left
 *	in interp, NULL is returned, and the Tcl_DString is unmodified.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

static char *
FileBasename(interp, path, bufferPtr)
    Tcl_Interp *interp;		/* Interp, for error return. */
    char *path;			/* Path whose basename to extract. */
    Tcl_DString *bufferPtr;	/* Initialized DString that receives
				 * basename. */
{
    int argc;
    char **argv;
    
    Tcl_SplitPath(path, &argc, &argv);
    if (argc == 0) {
	Tcl_DStringInit(bufferPtr);
    } else {
	if ((argc == 1) && (*path == '~')) {
	    Tcl_DString buffer;
	    
	    ckfree((char *) argv);
	    path = Tcl_TranslateFileName(interp, path, &buffer);
	    if (path == NULL) {
		return NULL;
	    }
	    Tcl_SplitPath(path, &argc, &argv);
	    Tcl_DStringFree(&buffer);
	}
	Tcl_DStringInit(bufferPtr);

	/*
	 * Return the last component, unless it is the only component, and it
	 * is the root of an absolute path.
	 */

	if (argc > 0) {
	    if ((argc > 1)
		    || (Tcl_GetPathType(argv[0]) == TCL_PATH_RELATIVE)) {
		Tcl_DStringAppend(bufferPtr, argv[argc - 1], -1);
	    }
	}
    }
    ckfree((char *) argv);
    return Tcl_DStringValue(bufferPtr);
}
 
/*
 *----------------------------------------------------------------------
 *
 * TclFileAttrsCmd --
 *
 *      Sets or gets the platform-specific attributes of a file. The objc-objv
 *	points to the file name with the rest of the command line following.
 *	This routine uses platform-specific tables of option strings
 *	and callbacks. The callback to get the attributes take three
 *	parameters:
 *	    Tcl_Interp *interp;	    The interp to report errors with.
 *				    Since this is an object-based API,
 *				    the object form of the result should be
 *				    used.
 *	    CONST char *fileName;   This is extracted using
 *				    Tcl_TranslateFileName.
 *	    TclObj **attrObjPtrPtr; A new object to hold the attribute
 *				    is allocated and put here.
 *	The first two parameters of the callback used to write out the
 *	attributes are the same. The third parameter is:
 *	    CONST *attrObjPtr;	    A pointer to the object that has
 *				    the new attribute.
 *	They both return standard TCL errors; if the routine to get
 *	an attribute fails, no object is allocated and *attrObjPtrPtr
 *	is unchanged.
 *
 * Results:
 *      Standard TCL error.
 *
 * Side effects:
 *      May set file attributes for the file name.
 *      
 *----------------------------------------------------------------------
 */

int
TclFileAttrsCmd(interp, objc, objv)
    Tcl_Interp *interp;		/* The interpreter for error reporting. */
    int objc;			/* Number of command line arguments. */
    Tcl_Obj *CONST objv[];	/* The command line objects. */
{
    Tcl_Obj *resultPtr = Tcl_GetObjResult(interp);
    char *fileName;
    int length, index;
    Tcl_Obj *listObjPtr;
    Tcl_Obj *elementObjPtr;
    Tcl_DString buffer;

    if ((objc > 2) && ((objc % 2) == 0)) {
	Tcl_AppendStringsToObj(resultPtr, 
		"wrong # args: must be \"file attributes name ?option? ?value? ?option value? ...\"",
		(char *) NULL);
	return TCL_ERROR;
    }

    fileName = Tcl_GetStringFromObj(objv[0], &length);
    if (Tcl_TranslateFileName(interp, fileName, &buffer) == NULL) {
    	return TCL_ERROR;
    }
    fileName = Tcl_DStringValue(&buffer);
    
    if (objc == 1) {
    	listObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
    	
    	for (index = 0; tclpFileAttrStrings[index] != NULL; index++) {
    	    elementObjPtr = Tcl_NewStringObj(tclpFileAttrStrings[index], -1);
	    Tcl_ListObjAppendElement(interp, listObjPtr, elementObjPtr);
	    if ((*tclpFileAttrProcs[index].getProc)(interp, index, fileName,
	    	    &elementObjPtr) != TCL_OK) {
	    	Tcl_DecrRefCount(listObjPtr);
	    	return TCL_ERROR;
	    }
	    Tcl_ListObjAppendElement(interp, listObjPtr, elementObjPtr);
    	}
    	Tcl_SetObjResult(interp, listObjPtr);
    } else if (objc == 2) {
    	if (Tcl_GetIndexFromObj(interp, objv[1], tclpFileAttrStrings, "option",
    		0, &index) != TCL_OK) {
    	    return TCL_ERROR;
    	}
	if ((*tclpFileAttrProcs[index].getProc)(interp, index, fileName,
		&elementObjPtr) != TCL_OK) {
	    return TCL_ERROR;
	}
	Tcl_SetObjResult(interp, elementObjPtr);
    } else {
        int i;
        
    	for (i = 1; i < objc ; i += 2) {
    	    if (Tcl_GetIndexFromObj(interp, objv[i], tclpFileAttrStrings, "option",
    	    	    0, &index) != TCL_OK) {
    	    	return TCL_ERROR;
    	    }
    	    if ((*tclpFileAttrProcs[index].setProc)(interp, index, fileName,
    	    	    objv[i + 1]) != TCL_OK) {
    	    	return TCL_ERROR;
    	    }
    	}
    }
    
    Tcl_DStringFree(&buffer);
    
    return TCL_OK;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted generic/tclIO.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
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
/* 
 * tclIO.c --
 *
 *	This file provides the generic portions (those that are the same on
 *	all platforms and for all channel types) of Tcl's IO facilities.
 *
 * Copyright (c) 1998 Scriptics Corporation
 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: tclIO.c,v 1.5 1998/10/30 00:38:38 welch Exp $
 */

#include	"tclInt.h"
#include	"tclPort.h"

/*
 * Make sure that both EAGAIN and EWOULDBLOCK are defined. This does not
 * compile on systems where neither is defined. We want both defined so
 * that we can test safely for both. In the code we still have to test for
 * both because there may be systems on which both are defined and have
 * different values.
 */

#if ((!defined(EWOULDBLOCK)) && (defined(EAGAIN)))
#   define EWOULDBLOCK EAGAIN
#endif
#if ((!defined(EAGAIN)) && (defined(EWOULDBLOCK)))
#   define EAGAIN EWOULDBLOCK
#endif
#if ((!defined(EAGAIN)) && (!defined(EWOULDBLOCK)))
    error one of EWOULDBLOCK or EAGAIN must be defined
#endif

/*
 * The following structure encapsulates the state for a background channel
 * copy.  Note that the data buffer for the copy will be appended to this
 * structure.
 */

typedef struct CopyState {
    struct Channel *readPtr;	/* Pointer to input channel. */
    struct Channel *writePtr;	/* Pointer to output channel. */
    int readFlags;		/* Original read channel flags. */
    int writeFlags;		/* Original write channel flags. */
    int toRead;			/* Number of bytes to copy, or -1. */
    int total;			/* Total bytes transferred (written). */
    Tcl_Interp *interp;		/* Interp that started the copy. */
    Tcl_Obj *cmdPtr;		/* Command to be invoked at completion. */
    int bufSize;		/* Size of appended buffer. */
    char buffer[1];		/* Copy buffer, this must be the last
				 * field. */
} CopyState;

/*
 * struct ChannelBuffer:
 *
 * Buffers data being sent to or from a channel.
 */

typedef struct ChannelBuffer {
    int nextAdded;		/* The next position into which a character
                                 * will be put in the buffer. */
    int nextRemoved;		/* Position of next byte to be removed
                                 * from the buffer. */
    int bufSize;		/* How big is the buffer? */
    struct ChannelBuffer *nextPtr;
    				/* Next buffer in chain. */
    char buf[4];		/* Placeholder for real buffer. The real
                                 * buffer occuppies this space + bufSize-4
                                 * bytes. This must be the last field in
                                 * the structure. */
} ChannelBuffer;

#define CHANNELBUFFER_HEADER_SIZE	(sizeof(ChannelBuffer) - 4)

/*
 * The following defines the *default* buffer size for channels.
 */

#define CHANNELBUFFER_DEFAULT_SIZE	(1024 * 4)

/*
 * Structure to record a close callback. One such record exists for
 * each close callback registered for a channel.
 */

typedef struct CloseCallback {
    Tcl_CloseProc *proc;		/* The procedure to call. */
    ClientData clientData;		/* Arbitrary one-word data to pass
                                         * to the callback. */
    struct CloseCallback *nextPtr;	/* For chaining close callbacks. */
} CloseCallback;

/*
 * The following structure describes the information saved from a call to
 * "fileevent". This is used later when the event being waited for to
 * invoke the saved script in the interpreter designed in this record.
 */

typedef struct EventScriptRecord {
    struct Channel *chanPtr;	/* The channel for which this script is
                                 * registered. This is used only when an
                                 * error occurs during evaluation of the
                                 * script, to delete the handler. */
    char *script;		/* Script to invoke. */
    Tcl_Interp *interp;		/* In what interpreter to invoke script? */
    int mask;			/* Events must overlap current mask for the
                                 * stored script to be invoked. */
    struct EventScriptRecord *nextPtr;
    				/* Next in chain of records. */
} EventScriptRecord;

/*
 * struct Channel:
 *
 * One of these structures is allocated for each open channel. It contains data
 * specific to the channel but which belongs to the generic part of the Tcl
 * channel mechanism, and it points at an instance specific (and type
 * specific) * instance data, and at a channel type structure.
 */

typedef struct Channel {
    char *channelName;		/* The name of the channel instance in Tcl
                                 * commands. Storage is owned by the generic IO
                                 * code,  is dynamically allocated. */
    int	flags;			/* ORed combination of the flags defined
                                 * below. */
    Tcl_EolTranslation inputTranslation;
				/* What translation to apply for end of line
                                 * sequences on input? */    
    Tcl_EolTranslation outputTranslation;
    				/* What translation to use for generating
                                 * end of line sequences in output? */
    int inEofChar;		/* If nonzero, use this as a signal of EOF
                                 * on input. */
    int outEofChar;             /* If nonzero, append this to the channel
                                 * when it is closed if it is open for
                                 * writing. */
    int unreportedError;	/* Non-zero if an error report was deferred
                                 * because it happened in the background. The
                                 * value is the POSIX error code. */
    ClientData instanceData;	/* Instance specific data. */
    Tcl_ChannelType *typePtr;	/* Pointer to channel type structure. */
    int refCount;		/* How many interpreters hold references to
                                 * this IO channel? */
    CloseCallback *closeCbPtr;	/* Callbacks registered to be called when the
                                 * channel is closed. */
    ChannelBuffer *curOutPtr;	/* Current output buffer being filled. */
    ChannelBuffer *outQueueHead;/* Points at first buffer in output queue. */
    ChannelBuffer *outQueueTail;/* Points at last buffer in output queue. */

    ChannelBuffer *saveInBufPtr;/* Buffer saved for input queue - eliminates
                                 * need to allocate a new buffer for "gets"
                                 * that crosses buffer boundaries. */
    ChannelBuffer *inQueueHead;	/* Points at first buffer in input queue. */
    ChannelBuffer *inQueueTail;	/* Points at last buffer in input queue. */

    struct ChannelHandler *chPtr;/* List of channel handlers registered
                                  * for this channel. */
    int interestMask;		/* Mask of all events this channel has
                                 * handlers for. */
    struct Channel *nextChanPtr;/* Next in list of channels currently open. */
    EventScriptRecord *scriptRecordPtr;
    				/* Chain of all scripts registered for
                                 * event handlers ("fileevent") on this
                                 * channel. */
    int bufSize;		/* What size buffers to allocate? */
    Tcl_TimerToken timer;	/* Handle to wakeup timer for this channel. */
    CopyState *csPtr;		/* State of background copy, or NULL. */
} Channel;
    
/*
 * Values for the flags field in Channel. Any ORed combination of the
 * following flags can be stored in the field. These flags record various
 * options and state bits about the channel. In addition to the flags below,
 * the channel can also have TCL_READABLE (1<<1) and TCL_WRITABLE (1<<2) set.
 */

#define CHANNEL_NONBLOCKING	(1<<3)	/* Channel is currently in
					 * nonblocking mode. */
#define CHANNEL_LINEBUFFERED	(1<<4)	/* Output to the channel must be
					 * flushed after every newline. */
#define CHANNEL_UNBUFFERED	(1<<5)	/* Output to the channel must always
					 * be flushed immediately. */
#define BUFFER_READY		(1<<6)	/* Current output buffer (the
					 * curOutPtr field in the
                                         * channel structure) should be
                                         * output as soon as possible even
                                         * though it may not be full. */
#define BG_FLUSH_SCHEDULED	(1<<7)	/* A background flush of the
					 * queued output buffers has been
                                         * scheduled. */
#define CHANNEL_CLOSED		(1<<8)	/* Channel has been closed. No
					 * further Tcl-level IO on the
                                         * channel is allowed. */
#define CHANNEL_EOF		(1<<9)	/* EOF occurred on this channel.
					 * This bit is cleared before every
                                         * input operation. */
#define CHANNEL_STICKY_EOF	(1<<10)	/* EOF occurred on this channel because
					 * we saw the input eofChar. This bit
                                         * prevents clearing of the EOF bit
                                         * before every input operation. */
#define CHANNEL_BLOCKED	(1<<11)	/* EWOULDBLOCK or EAGAIN occurred
					 * on this channel. This bit is
                                         * cleared before every input or
                                         * output operation. */
#define INPUT_SAW_CR		(1<<12)	/* Channel is in CRLF eol input
					 * translation mode and the last
                                         * byte seen was a "\r". */
#define CHANNEL_DEAD		(1<<13)	/* The channel has been closed by
					 * the exit handler (on exit) but
                                         * not deallocated. When any IO
                                         * operation sees this flag on a
                                         * channel, it does not call driver
                                         * level functions to avoid referring
                                         * to deallocated data. */
#define CHANNEL_GETS_BLOCKED	(1<<14)	/* The last input operation was a gets
					 * that failed to get a comlete line.
					 * When set, file events will not be
					 * delivered for buffered data unless
					 * an EOL is present. */

/*
 * For each channel handler registered in a call to Tcl_CreateChannelHandler,
 * there is one record of the following type. All of records for a specific
 * channel are chained together in a singly linked list which is stored in
 * the channel structure.
 */

typedef struct ChannelHandler {
    Channel *chanPtr;		/* The channel structure for this channel. */
    int mask;			/* Mask of desired events. */
    Tcl_ChannelProc *proc;	/* Procedure to call in the type of
                                 * Tcl_CreateChannelHandler. */
    ClientData clientData;	/* Argument to pass to procedure. */
    struct ChannelHandler *nextPtr;
    				/* Next one in list of registered handlers. */
} ChannelHandler;

/*
 * This structure keeps track of the current ChannelHandler being invoked in
 * the current invocation of ChannelHandlerEventProc. There is a potential
 * problem if a ChannelHandler is deleted while it is the current one, since
 * ChannelHandlerEventProc needs to look at the nextPtr field. To handle this
 * problem, structures of the type below indicate the next handler to be
 * processed for any (recursively nested) dispatches in progress. The
 * nextHandlerPtr field is updated if the handler being pointed to is deleted.
 * The nextPtr field is used to chain together all recursive invocations, so
 * that Tcl_DeleteChannelHandler can find all the recursively nested
 * invocations of ChannelHandlerEventProc and compare the handler being
 * deleted against the NEXT handler to be invoked in that invocation; when it
 * finds such a situation, Tcl_DeleteChannelHandler updates the nextHandlerPtr
 * field of the structure to the next handler.
 */

typedef struct NextChannelHandler {
    ChannelHandler *nextHandlerPtr;	/* The next handler to be invoked in
                                         * this invocation. */
    struct NextChannelHandler *nestedHandlerPtr;
					/* Next nested invocation of
                                         * ChannelHandlerEventProc. */
} NextChannelHandler;

/*
 * This variable holds the list of nested ChannelHandlerEventProc invocations.
 */

static NextChannelHandler *nestedHandlerPtr = (NextChannelHandler *) NULL;

/*
 * List of all channels currently open.
 */

static Channel *firstChanPtr = (Channel *) NULL;

/*
 * Has a channel exit handler been created yet?
 */

static int channelExitHandlerCreated = 0;

/*
 * The following structure describes the event that is added to the Tcl
 * event queue by the channel handler check procedure.
 */

typedef struct ChannelHandlerEvent {
    Tcl_Event header;		/* Standard header for all events. */
    Channel *chanPtr;		/* The channel that is ready. */
    int readyMask;		/* Events that have occurred. */
} ChannelHandlerEvent;

/*
 * Static variables to hold channels for stdin, stdout and stderr.
 */

static Tcl_Channel stdinChannel = NULL;
static int stdinInitialized = 0;
static Tcl_Channel stdoutChannel = NULL;
static int stdoutInitialized = 0;
static Tcl_Channel stderrChannel = NULL;
static int stderrInitialized = 0;

/*
 * Static functions in this file:
 */

static void		ChannelEventScriptInvoker _ANSI_ARGS_((
			    ClientData clientData, int flags));
static void		ChannelTimerProc _ANSI_ARGS_((
			    ClientData clientData));
static void		CheckForStdChannelsBeingClosed _ANSI_ARGS_((
			    Tcl_Channel chan));
static void		CleanupChannelHandlers _ANSI_ARGS_((
			    Tcl_Interp *interp, Channel *chanPtr));
static int		CloseChannel _ANSI_ARGS_((Tcl_Interp *interp,
                            Channel *chanPtr, int errorCode));
static void		CloseChannelsOnExit _ANSI_ARGS_((ClientData data));
static int		CopyAndTranslateBuffer _ANSI_ARGS_((
			    Channel *chanPtr, char *result, int space));
static int		CopyData _ANSI_ARGS_((CopyState *csPtr, int mask));
static void		CopyEventProc _ANSI_ARGS_((ClientData clientData,
			    int mask));
static void		CreateScriptRecord _ANSI_ARGS_((
			    Tcl_Interp *interp, Channel *chanPtr,
                            int mask, char *script));
static void		DeleteChannelTable _ANSI_ARGS_((
			    ClientData clientData, Tcl_Interp *interp));
static void		DeleteScriptRecord _ANSI_ARGS_((Tcl_Interp *interp,
        		    Channel *chanPtr, int mask));
static void		DiscardInputQueued _ANSI_ARGS_((
			    Channel *chanPtr, int discardSavedBuffers));
static void		DiscardOutputQueued _ANSI_ARGS_((
    			    Channel *chanPtr));
static int		DoRead _ANSI_ARGS_((Channel *chanPtr, char *srcPtr,
			    int slen));
static int		DoWrite _ANSI_ARGS_((Channel *chanPtr, char *srcPtr,
			    int slen));
static int		FlushChannel _ANSI_ARGS_((Tcl_Interp *interp,
                            Channel *chanPtr, int calledFromAsyncFlush));
static Tcl_HashTable	*GetChannelTable _ANSI_ARGS_((Tcl_Interp *interp));
static int		GetEOL _ANSI_ARGS_((Channel *chanPtr));
static int		GetInput _ANSI_ARGS_((Channel *chanPtr));
static void		RecycleBuffer _ANSI_ARGS_((Channel *chanPtr,
		            ChannelBuffer *bufPtr, int mustDiscard));
static int		ScanBufferForEOL _ANSI_ARGS_((Channel *chanPtr,
                            ChannelBuffer *bufPtr,
                            Tcl_EolTranslation translation, int eofChar,
		            int *bytesToEOLPtr, int *crSeenPtr));
static int		ScanInputForEOL _ANSI_ARGS_((Channel *chanPtr,
		            int *bytesQueuedPtr));
static int		SetBlockMode _ANSI_ARGS_((Tcl_Interp *interp,
		            Channel *chanPtr, int mode));
static void		StopCopy _ANSI_ARGS_((CopyState *csPtr));
static void		UpdateInterest _ANSI_ARGS_((Channel *chanPtr));
static int		CheckForDeadChannel _ANSI_ARGS_((Tcl_Interp *interp,
							Channel *chan));
 
/*
 *----------------------------------------------------------------------
 *
 * SetBlockMode --
 *
 *	This function sets the blocking mode for a channel and updates
 *	the state flags.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	Modifies the blocking mode of the channel and possibly generates
 *	an error.
 *
 *----------------------------------------------------------------------
 */

static int
SetBlockMode(interp, chanPtr, mode)
    Tcl_Interp *interp;		/* Interp for error reporting. */
    Channel *chanPtr;		/* Channel to modify. */
    int mode;			/* One of TCL_MODE_BLOCKING or
				 * TCL_MODE_NONBLOCKING. */
{
    int result = 0;
    if (chanPtr->typePtr->blockModeProc != NULL) {
	result = (chanPtr->typePtr->blockModeProc) (chanPtr->instanceData,
		mode);
    }
    if (result != 0) {
	Tcl_SetErrno(result);
	if (interp != (Tcl_Interp *) NULL) {
	    Tcl_AppendResult(interp, "error setting blocking mode: ",
		    Tcl_PosixError(interp), (char *) NULL);
	}
	return TCL_ERROR;
    }
    if (mode == TCL_MODE_BLOCKING) {
	chanPtr->flags &= (~(CHANNEL_NONBLOCKING | BG_FLUSH_SCHEDULED));
    } else {
	chanPtr->flags |= CHANNEL_NONBLOCKING;
    }
    return TCL_OK;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_SetStdChannel --
 *
 *	This function is used to change the channels that are used
 *	for stdin/stdout/stderr in new interpreters.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
Tcl_SetStdChannel(channel, type)
    Tcl_Channel channel;
    int type;			/* One of TCL_STDIN, TCL_STDOUT, TCL_STDERR. */
{
    switch (type) {
	case TCL_STDIN:
            stdinInitialized = 1;
	    stdinChannel = channel;
	    break;
	case TCL_STDOUT:
	    stdoutInitialized = 1;
	    stdoutChannel = channel;
	    break;
	case TCL_STDERR:
	    stderrInitialized = 1;
	    stderrChannel = channel;
	    break;
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_GetStdChannel --
 *
 *	Returns the specified standard channel.
 *
 * Results:
 *	Returns the specified standard channel, or NULL.
 *
 * Side effects:
 *	May cause the creation of a standard channel and the underlying
 *	file.
 *
 *----------------------------------------------------------------------
 */

Tcl_Channel
Tcl_GetStdChannel(type)
    int type;			/* One of TCL_STDIN, TCL_STDOUT, TCL_STDERR. */
{
    Tcl_Channel channel = NULL;

    /*
     * If the channels were not created yet, create them now and
     * store them in the static variables.  Note that we need to set
     * stdinInitialized before calling TclGetDefaultStdChannel in order
     * to avoid recursive loops when TclGetDefaultStdChannel calls
     * Tcl_CreateChannel.
     */

    switch (type) {
	case TCL_STDIN:
	    if (!stdinInitialized) {
		stdinChannel = TclGetDefaultStdChannel(TCL_STDIN);
		stdinInitialized = 1;

                /*
                 * Artificially bump the refcount to ensure that the channel
                 * is only closed on exit.
                 *
                 * NOTE: Must only do this if stdinChannel is not NULL. It
                 * can be NULL in situations where Tcl is unable to connect
                 * to the standard input.
                 */

                if (stdinChannel != (Tcl_Channel) NULL) {
                    (void) Tcl_RegisterChannel((Tcl_Interp *) NULL,
                            stdinChannel);
                }
	    }
	    channel = stdinChannel;
	    break;
	case TCL_STDOUT:
	    if (!stdoutInitialized) {
		stdoutChannel = TclGetDefaultStdChannel(TCL_STDOUT);
		stdoutInitialized = 1;

                /*
                 * Artificially bump the refcount to ensure that the channel
                 * is only closed on exit.
                 *
                 * NOTE: Must only do this if stdoutChannel is not NULL. It
                 * can be NULL in situations where Tcl is unable to connect
                 * to the standard output.
                 */

                if (stdoutChannel != (Tcl_Channel) NULL) {
                    (void) Tcl_RegisterChannel((Tcl_Interp *) NULL,
                            stdoutChannel);
                }
	    }
	    channel = stdoutChannel;
	    break;
	case TCL_STDERR:
	    if (!stderrInitialized) {
		stderrChannel = TclGetDefaultStdChannel(TCL_STDERR);
		stderrInitialized = 1;

                /*
                 * Artificially bump the refcount to ensure that the channel
                 * is only closed on exit.
                 *
                 * NOTE: Must only do this if stderrChannel is not NULL. It
                 * can be NULL in situations where Tcl is unable to connect
                 * to the standard error.
                 */

                if (stderrChannel != (Tcl_Channel) NULL) {
                    (void) Tcl_RegisterChannel((Tcl_Interp *) NULL,
                            stderrChannel);
                }
	    }
	    channel = stderrChannel;
	    break;
    }
    return channel;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_CreateCloseHandler
 *
 *	Creates a close callback which will be called when the channel is
 *	closed.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Causes the callback to be called in the future when the channel
 *	will be closed.
 *
 *----------------------------------------------------------------------
 */

void
Tcl_CreateCloseHandler(chan, proc, clientData)
    Tcl_Channel chan;		/* The channel for which to create the
                                 * close callback. */
    Tcl_CloseProc *proc;	/* The callback routine to call when the
                                 * channel will be closed. */
    ClientData clientData;	/* Arbitrary data to pass to the
                                 * close callback. */
{
    Channel *chanPtr;
    CloseCallback *cbPtr;

    chanPtr = (Channel *) chan;

    cbPtr = (CloseCallback *) ckalloc((unsigned) sizeof(CloseCallback));
    cbPtr->proc = proc;
    cbPtr->clientData = clientData;

    cbPtr->nextPtr = chanPtr->closeCbPtr;
    chanPtr->closeCbPtr = cbPtr;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_DeleteCloseHandler --
 *
 *	Removes a callback that would have been called on closing
 *	the channel. If there is no matching callback then this
 *	function has no effect.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The callback will not be called in the future when the channel
 *	is eventually closed.
 *
 *----------------------------------------------------------------------
 */

void
Tcl_DeleteCloseHandler(chan, proc, clientData)
    Tcl_Channel chan;		/* The channel for which to cancel the
                                 * close callback. */
    Tcl_CloseProc *proc;	/* The procedure for the callback to
                                 * remove. */
    ClientData clientData;	/* The callback data for the callback
                                 * to remove. */
{
    Channel *chanPtr;
    CloseCallback *cbPtr, *cbPrevPtr;

    chanPtr = (Channel *) chan;
    for (cbPtr = chanPtr->closeCbPtr, cbPrevPtr = (CloseCallback *) NULL;
             cbPtr != (CloseCallback *) NULL;
             cbPtr = cbPtr->nextPtr) {
        if ((cbPtr->proc == proc) && (cbPtr->clientData == clientData)) {
            if (cbPrevPtr == (CloseCallback *) NULL) {
                chanPtr->closeCbPtr = cbPtr->nextPtr;
            }
            ckfree((char *) cbPtr);
            break;
        } else {
            cbPrevPtr = cbPtr;
        }
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * CloseChannelsOnExit --
 *
 *	Closes all the existing channels, on exit. This	routine is called
 *	during exit processing.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Closes all channels.
 *
 *----------------------------------------------------------------------
 */

	/* ARGSUSED */
static void
CloseChannelsOnExit(clientData)
    ClientData clientData;		/* NULL - unused. */
{
    Channel *chanPtr;			/* Iterates over open channels. */
    Channel *nextChanPtr;		/* Iterates over open channels. */


    for (chanPtr = firstChanPtr; chanPtr != (Channel *) NULL;
             chanPtr = nextChanPtr) {
        nextChanPtr = chanPtr->nextChanPtr;

        /*
         * Set the channel back into blocking mode to ensure that we wait
         * for all data to flush out.
         */
        
        (void) Tcl_SetChannelOption(NULL, (Tcl_Channel) chanPtr,
                "-blocking", "on");

        if ((chanPtr == (Channel *) stdinChannel) ||
                (chanPtr == (Channel *) stdoutChannel) ||
                (chanPtr == (Channel *) stderrChannel)) {

            /*
             * Decrement the refcount which was earlier artificially bumped
             * up to keep the channel from being closed.
             */

            chanPtr->refCount--;
        }

        if (chanPtr->refCount <= 0) {

	    /*
             * Close it only if the refcount indicates that the channel is not
             * referenced from any interpreter. If it is, that interpreter will
             * close the channel when it gets destroyed.
             */

            (void) Tcl_Close((Tcl_Interp *) NULL, (Tcl_Channel) chanPtr);

        } else {

            /*
             * The refcount is greater than zero, so flush the channel.
             */

            Tcl_Flush((Tcl_Channel) chanPtr);

            /*
             * Call the device driver to actually close the underlying
             * device for this channel.
             */
            
            (chanPtr->typePtr->closeProc) (chanPtr->instanceData,
                    (Tcl_Interp *) NULL);

            /*
             * Finally, we clean up the fields in the channel data structure
             * since all of them have been deleted already. We mark the
             * channel with CHANNEL_DEAD to prevent any further IO operations
             * on it.
             */

            chanPtr->instanceData = (ClientData) NULL;
            chanPtr->flags |= CHANNEL_DEAD;
        }
    }

    /*
     * Reinitialize all the variables to the initial state:
     */
    
    firstChanPtr = (Channel *) NULL;
    nestedHandlerPtr = (NextChannelHandler *) NULL;
    channelExitHandlerCreated = 0;
    stdinChannel = NULL;
    stdinInitialized = 0;
    stdoutChannel = NULL;
    stdoutInitialized = 0;
    stderrChannel = NULL;
    stderrInitialized = 0;
}
 
/*
 *----------------------------------------------------------------------
 *
 * GetChannelTable --
 *
 *	Gets and potentially initializes the channel table for an
 *	interpreter. If it is initializing the table it also inserts
 *	channels for stdin, stdout and stderr if the interpreter is
 *	trusted.
 *
 * Results:
 *	A pointer to the hash table created, for use by the caller.
 *
 * Side effects:
 *	Initializes the channel table for an interpreter. May create
 *	channels for stdin, stdout and stderr.
 *
 *----------------------------------------------------------------------
 */

static Tcl_HashTable *
GetChannelTable(interp)
    Tcl_Interp *interp;
{
    Tcl_HashTable *hTblPtr;	/* Hash table of channels. */
    Tcl_Channel stdinChan, stdoutChan, stderrChan;

    hTblPtr = (Tcl_HashTable *) Tcl_GetAssocData(interp, "tclIO", NULL);
    if (hTblPtr == (Tcl_HashTable *) NULL) {
        hTblPtr = (Tcl_HashTable *) ckalloc((unsigned) sizeof(Tcl_HashTable));
        Tcl_InitHashTable(hTblPtr, TCL_STRING_KEYS);

        (void) Tcl_SetAssocData(interp, "tclIO",
                (Tcl_InterpDeleteProc *) DeleteChannelTable,
                (ClientData) hTblPtr);

        /*
         * If the interpreter is trusted (not "safe"), insert channels
         * for stdin, stdout and stderr (possibly creating them in the
         * process).
         */

        if (Tcl_IsSafe(interp) == 0) {
            stdinChan = Tcl_GetStdChannel(TCL_STDIN);
            if (stdinChan != NULL) {
                Tcl_RegisterChannel(interp, stdinChan);
            }
            stdoutChan = Tcl_GetStdChannel(TCL_STDOUT);
            if (stdoutChan != NULL) {
                Tcl_RegisterChannel(interp, stdoutChan);
            }
            stderrChan = Tcl_GetStdChannel(TCL_STDERR);
            if (stderrChan != NULL) {
                Tcl_RegisterChannel(interp, stderrChan);
            }
        }

    }
    return hTblPtr;
}
 
/*
 *----------------------------------------------------------------------
 *
 * DeleteChannelTable --
 *
 *	Deletes the channel table for an interpreter, closing any open
 *	channels whose refcount reaches zero. This procedure is invoked
 *	when an interpreter is deleted, via the AssocData cleanup
 *	mechanism.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Deletes the hash table of channels. May close channels. May flush
 *	output on closed channels. Removes any channeEvent handlers that were
 *	registered in this interpreter.
 *
 *----------------------------------------------------------------------
 */

static void
DeleteChannelTable(clientData, interp)
    ClientData clientData;	/* The per-interpreter data structure. */
    Tcl_Interp *interp;		/* The interpreter being deleted. */
{
    Tcl_HashTable *hTblPtr;	/* The hash table. */
    Tcl_HashSearch hSearch;	/* Search variable. */
    Tcl_HashEntry *hPtr;	/* Search variable. */
    Channel *chanPtr;	/* Channel being deleted. */
    EventScriptRecord *sPtr, *prevPtr, *nextPtr;
    				/* Variables to loop over all channel events
                                 * registered, to delete the ones that refer
                                 * to the interpreter being deleted. */
    
    /*
     * Delete all the registered channels - this will close channels whose
     * refcount reaches zero.
     */
    
    hTblPtr = (Tcl_HashTable *) clientData;
    for (hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch);
             hPtr != (Tcl_HashEntry *) NULL;
             hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch)) {

        chanPtr = (Channel *) Tcl_GetHashValue(hPtr);

        /*
         * Remove any fileevents registered in this interpreter.
         */
        
        for (sPtr = chanPtr->scriptRecordPtr,
                 prevPtr = (EventScriptRecord *) NULL;
                 sPtr != (EventScriptRecord *) NULL;
                 sPtr = nextPtr) {
            nextPtr = sPtr->nextPtr;
            if (sPtr->interp == interp) {
                if (prevPtr == (EventScriptRecord *) NULL) {
                    chanPtr->scriptRecordPtr = nextPtr;
                } else {
                    prevPtr->nextPtr = nextPtr;
                }

                Tcl_DeleteChannelHandler((Tcl_Channel) chanPtr,
                        ChannelEventScriptInvoker, (ClientData) sPtr);

		ckfree(sPtr->script);
                ckfree((char *) sPtr);
            } else {
                prevPtr = sPtr;
            }
        }

        /*
         * Cannot call Tcl_UnregisterChannel because that procedure calls
         * Tcl_GetAssocData to get the channel table, which might already
         * be inaccessible from the interpreter structure. Instead, we
         * emulate the behavior of Tcl_UnregisterChannel directly here.
         */

        Tcl_DeleteHashEntry(hPtr);
        chanPtr->refCount--;
        if (chanPtr->refCount <= 0) {
            if (!(chanPtr->flags & BG_FLUSH_SCHEDULED)) {
                (void) Tcl_Close(interp, (Tcl_Channel) chanPtr);
            }
        }
    }
    Tcl_DeleteHashTable(hTblPtr);
    ckfree((char *) hTblPtr);
}
 
/*
 *----------------------------------------------------------------------
 *
 * CheckForStdChannelsBeingClosed --
 *
 *	Perform special handling for standard channels being closed. When
 *	given a standard channel, if the refcount is now 1, it means that
 *	the last reference to the standard channel is being explicitly
 *	closed. Now bump the refcount artificially down to 0, to ensure the
 *	normal handling of channels being closed will occur. Also reset the
 *	static pointer to the channel to NULL, to avoid dangling references.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Manipulates the refcount on standard channels. May smash the global
 *	static pointer to a standard channel.
 *
 *----------------------------------------------------------------------
 */

static void
CheckForStdChannelsBeingClosed(chan)
    Tcl_Channel chan;
{
    Channel *chanPtr = (Channel *) chan;
    
    if ((chan == stdinChannel) && (stdinInitialized)) {
        if (chanPtr->refCount < 2) {
            chanPtr->refCount = 0;
            stdinChannel = NULL;
            return;
        }
    } else if ((chan == stdoutChannel) && (stdoutInitialized)) {
        if (chanPtr->refCount < 2) {
            chanPtr->refCount = 0;
            stdoutChannel = NULL;
            return;
        }
    } else if ((chan == stderrChannel) && (stderrInitialized)) {
        if (chanPtr->refCount < 2) {
            chanPtr->refCount = 0;
            stderrChannel = NULL;
            return;
        }
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_UnregisterChannel --
 *
 *	Deletes the hash entry for a channel associated with an interpreter.
 *	If the interpreter given as argument is NULL, it only decrements the
 *	reference count.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	Deletes the hash entry for a channel associated with an interpreter.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_UnregisterChannel(interp, chan)
    Tcl_Interp *interp;		/* Interpreter in which channel is defined. */
    Tcl_Channel chan;		/* Channel to delete. */
{
    Tcl_HashTable *hTblPtr;	/* Hash table of channels. */
    Tcl_HashEntry *hPtr;	/* Search variable. */
    Channel *chanPtr;		/* The real IO channel. */

    chanPtr = (Channel *) chan;
    
    if (interp != (Tcl_Interp *) NULL) {
        hTblPtr = (Tcl_HashTable *) Tcl_GetAssocData(interp, "tclIO", NULL);
        if (hTblPtr == (Tcl_HashTable *) NULL) {
            return TCL_OK;
        }
        hPtr = Tcl_FindHashEntry(hTblPtr, chanPtr->channelName);
        if (hPtr == (Tcl_HashEntry *) NULL) {
            return TCL_OK;
        }
        if ((Channel *) Tcl_GetHashValue(hPtr) != chanPtr) {
            return TCL_OK;
        }
        Tcl_DeleteHashEntry(hPtr);

        /*
         * Remove channel handlers that refer to this interpreter, so that they
         * will not be present if the actual close is delayed and more events
         * happen on the channel. This may occur if the channel is shared
         * between several interpreters, or if the channel has async
         * flushing active.
         */
    
        CleanupChannelHandlers(interp, chanPtr);
    }

    chanPtr->refCount--;
    
    /*
     * Perform special handling for standard channels being closed. If the
     * refCount is now 1 it means that the last reference to the standard
     * channel is being explicitly closed, so bump the refCount down
     * artificially to 0. This will ensure that the channel is actually
     * closed, below. Also set the static pointer to NULL for the channel.
     */

    CheckForStdChannelsBeingClosed(chan);

    /*
     * If the refCount reached zero, close the actual channel.
     */

    if (chanPtr->refCount <= 0) {

        /*
         * Ensure that if there is another buffer, it gets flushed
         * whether or not we are doing a background flush.
         */

        if ((chanPtr->curOutPtr != NULL) &&
                (chanPtr->curOutPtr->nextAdded >
                        chanPtr->curOutPtr->nextRemoved)) {
            chanPtr->flags |= BUFFER_READY;
        }
        chanPtr->flags |= CHANNEL_CLOSED;
        if (!(chanPtr->flags & BG_FLUSH_SCHEDULED)) {
            if (Tcl_Close(interp, chan) != TCL_OK) {
                return TCL_ERROR;
            }
        }
    }
    return TCL_OK;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_RegisterChannel --
 *
 *	Adds an already-open channel to the channel table of an interpreter.
 *	If the interpreter passed as argument is NULL, it only increments
 *	the channel refCount.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May increment the reference count of a channel.
 *
 *----------------------------------------------------------------------
 */

void
Tcl_RegisterChannel(interp, chan)
    Tcl_Interp *interp;		/* Interpreter in which to add the channel. */
    Tcl_Channel chan;		/* The channel to add to this interpreter
                                 * channel table. */
{
    Tcl_HashTable *hTblPtr;	/* Hash table of channels. */
    Tcl_HashEntry *hPtr;	/* Search variable. */
    int new;			/* Is the hash entry new or does it exist? */
    Channel *chanPtr;		/* The actual channel. */

    chanPtr = (Channel *) chan;

    if (chanPtr->channelName == (char *) NULL) {
        panic("Tcl_RegisterChannel: channel without name");
    }
    if (interp != (Tcl_Interp *) NULL) {
        hTblPtr = GetChannelTable(interp);
        hPtr = Tcl_CreateHashEntry(hTblPtr, chanPtr->channelName, &new);
        if (new == 0) {
            if (chan == (Tcl_Channel) Tcl_GetHashValue(hPtr)) {
                return;
            }
            panic("Tcl_RegisterChannel: duplicate channel names");
        }
        Tcl_SetHashValue(hPtr, (ClientData) chanPtr);
    }
    chanPtr->refCount++;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_GetChannel --
 *
 *	Finds an existing Tcl_Channel structure by name in a given
 *	interpreter. This function is public because it is used by
 *	channel-type-specific functions.
 *
 * Results:
 *	A Tcl_Channel or NULL on failure. If failed, interp->result
 *	contains an error message. It also returns, in modePtr, the
 *	modes in which the channel is opened.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

Tcl_Channel
Tcl_GetChannel(interp, chanName, modePtr)
    Tcl_Interp *interp;		/* Interpreter in which to find or create
                                 * the channel. */
    char *chanName;		/* The name of the channel. */
    int *modePtr;		/* Where to store the mode in which the
                                 * channel was opened? Will contain an ORed
                                 * combination of TCL_READABLE and
                                 * TCL_WRITABLE, if non-NULL. */
{
    Channel *chanPtr;		/* The actual channel. */
    Tcl_HashTable *hTblPtr;	/* Hash table of channels. */
    Tcl_HashEntry *hPtr;	/* Search variable. */
    char *name;			/* Translated name. */

    /*
     * Substitute "stdin", etc.  Note that even though we immediately
     * find the channel using Tcl_GetStdChannel, we still need to look
     * it up in the specified interpreter to ensure that it is present
     * in the channel table.  Otherwise, safe interpreters would always
     * have access to the standard channels.
     */

    name = chanName;
    if ((chanName[0] == 's') && (chanName[1] == 't')) {
	chanPtr = NULL;
	if (strcmp(chanName, "stdin") == 0) {
	    chanPtr = (Channel *)Tcl_GetStdChannel(TCL_STDIN);
	} else if (strcmp(chanName, "stdout") == 0) {
	    chanPtr = (Channel *)Tcl_GetStdChannel(TCL_STDOUT);
	} else if (strcmp(chanName, "stderr") == 0) {
	    chanPtr = (Channel *)Tcl_GetStdChannel(TCL_STDERR);
	}
	if (chanPtr != NULL) {
	    name = chanPtr->channelName;
	}
    }
    
    hTblPtr = GetChannelTable(interp);
    hPtr = Tcl_FindHashEntry(hTblPtr, name);
    if (hPtr == (Tcl_HashEntry *) NULL) {
        Tcl_AppendResult(interp, "can not find channel named \"",
                chanName, "\"", (char *) NULL);
        return NULL;
    }

    chanPtr = (Channel *) Tcl_GetHashValue(hPtr);
    if (modePtr != NULL) {
        *modePtr = (chanPtr->flags & (TCL_READABLE|TCL_WRITABLE));
    }
    
    return (Tcl_Channel) chanPtr;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_CreateChannel --
 *
 *	Creates a new entry in the hash table for a Tcl_Channel
 *	record.
 *
 * Results:
 *	Returns the new Tcl_Channel.
 *
 * Side effects:
 *	Creates a new Tcl_Channel instance and inserts it into the
 *	hash table.
 *
 *----------------------------------------------------------------------
 */

Tcl_Channel
Tcl_CreateChannel(typePtr, chanName, instanceData, mask)
    Tcl_ChannelType *typePtr;	/* The channel type record. */
    char *chanName;		/* Name of channel to record. */
    ClientData instanceData;	/* Instance specific data. */
    int mask;			/* TCL_READABLE & TCL_WRITABLE to indicate
                                 * if the channel is readable, writable. */
{
    Channel *chanPtr;		/* The channel structure newly created. */

    chanPtr = (Channel *) ckalloc((unsigned) sizeof(Channel));
    
    if (chanName != (char *) NULL) {
        chanPtr->channelName = ckalloc((unsigned) (strlen(chanName) + 1));
        strcpy(chanPtr->channelName, chanName);
    } else {
        panic("Tcl_CreateChannel: NULL channel name");
    }

    chanPtr->flags = mask;

    /*
     * Set the channel up initially in AUTO input translation mode to
     * accept "\n", "\r" and "\r\n". Output translation mode is set to
     * a platform specific default value. The eofChar is set to 0 for both
     * input and output, so that Tcl does not look for an in-file EOF
     * indicator (e.g. ^Z) and does not append an EOF indicator to files.
     */

    chanPtr->inputTranslation = TCL_TRANSLATE_AUTO;
    chanPtr->outputTranslation = TCL_PLATFORM_TRANSLATION;
    chanPtr->inEofChar = 0;
    chanPtr->outEofChar = 0;

    chanPtr->unreportedError = 0;
    chanPtr->instanceData = instanceData;
    chanPtr->typePtr = typePtr;
    chanPtr->refCount = 0;
    chanPtr->closeCbPtr = (CloseCallback *) NULL;
    chanPtr->curOutPtr = (ChannelBuffer *) NULL;
    chanPtr->outQueueHead = (ChannelBuffer *) NULL;
    chanPtr->outQueueTail = (ChannelBuffer *) NULL;
    chanPtr->saveInBufPtr = (ChannelBuffer *) NULL;
    chanPtr->inQueueHead = (ChannelBuffer *) NULL;
    chanPtr->inQueueTail = (ChannelBuffer *) NULL;
    chanPtr->chPtr = (ChannelHandler *) NULL;
    chanPtr->interestMask = 0;
    chanPtr->scriptRecordPtr = (EventScriptRecord *) NULL;
    chanPtr->bufSize = CHANNELBUFFER_DEFAULT_SIZE;
    chanPtr->timer = NULL;
    chanPtr->csPtr = NULL;

    /*
     * Link the channel into the list of all channels; create an on-exit
     * handler if there is not one already, to close off all the channels
     * in the list on exit.
     */

    chanPtr->nextChanPtr = firstChanPtr;
    firstChanPtr = chanPtr;

    if (!channelExitHandlerCreated) {
        channelExitHandlerCreated = 1;
        Tcl_CreateExitHandler(CloseChannelsOnExit, (ClientData) NULL);
    }
    
    /*
     * Install this channel in the first empty standard channel slot, if
     * the channel was previously closed explicitly.
     */

    if ((stdinChannel == NULL) && (stdinInitialized == 1)) {
	Tcl_SetStdChannel((Tcl_Channel)chanPtr, TCL_STDIN);
        Tcl_RegisterChannel((Tcl_Interp *) NULL, (Tcl_Channel) chanPtr);
    } else if ((stdoutChannel == NULL) && (stdoutInitialized == 1)) {
	Tcl_SetStdChannel((Tcl_Channel)chanPtr, TCL_STDOUT);
        Tcl_RegisterChannel((Tcl_Interp *) NULL, (Tcl_Channel) chanPtr);
    } else if ((stderrChannel == NULL) && (stderrInitialized == 1)) {
	Tcl_SetStdChannel((Tcl_Channel)chanPtr, TCL_STDERR);
        Tcl_RegisterChannel((Tcl_Interp *) NULL, (Tcl_Channel) chanPtr);
    } 
    return (Tcl_Channel) chanPtr;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_GetChannelMode --
 *
 *	Computes a mask indicating whether the channel is open for
 *	reading and writing.
 *
 * Results:
 *	An OR-ed combination of TCL_READABLE and TCL_WRITABLE.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_GetChannelMode(chan)
    Tcl_Channel chan;		/* The channel for which the mode is
                                 * being computed. */
{
    Channel *chanPtr;		/* The actual channel. */

    chanPtr = (Channel *) chan;
    return (chanPtr->flags & (TCL_READABLE | TCL_WRITABLE));
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_GetChannelName --
 *
 *	Returns the string identifying the channel name.
 *
 * Results:
 *	The string containing the channel name. This memory is
 *	owned by the generic layer and should not be modified by
 *	the caller.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

char *
Tcl_GetChannelName(chan)
    Tcl_Channel chan;		/* The channel for which to return the name. */
{
    Channel *chanPtr;		/* The actual channel. */

    chanPtr = (Channel *) chan;
    return chanPtr->channelName;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_GetChannelType --
 *
 *	Given a channel structure, returns the channel type structure.
 *
 * Results:
 *	Returns a pointer to the channel type structure.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

Tcl_ChannelType *
Tcl_GetChannelType(chan)
    Tcl_Channel chan;		/* The channel to return type for. */
{
    Channel *chanPtr;		/* The actual channel. */

    chanPtr = (Channel *) chan;
    return chanPtr->typePtr;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_GetChannelHandle --
 *
 *	Returns an OS handle associated with a channel.
 *
 * Results:
 *	Returns TCL_OK and places the handle in handlePtr, or returns
 *	TCL_ERROR on failure.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_GetChannelHandle(chan, direction, handlePtr)
    Tcl_Channel chan;		/* The channel to get file from. */
    int direction;		/* TCL_WRITABLE or TCL_READABLE. */
    ClientData *handlePtr;	/* Where to store handle */
{
    Channel *chanPtr;		/* The actual channel. */
    ClientData handle;
    int result;

    chanPtr = (Channel *) chan;
    result = (chanPtr->typePtr->getHandleProc)(chanPtr->instanceData,
	    direction, &handle);
    if (handlePtr) {
	*handlePtr = handle;
    }
    return result;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_GetChannelInstanceData --
 *
 *	Returns the client data associated with a channel.
 *
 * Results:
 *	The client data.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

ClientData
Tcl_GetChannelInstanceData(chan)
    Tcl_Channel chan;		/* Channel for which to return client data. */
{
    Channel *chanPtr;		/* The actual channel. */

    chanPtr = (Channel *) chan;
    return chanPtr->instanceData;
}
 
/*
 *----------------------------------------------------------------------
 *
 * RecycleBuffer --
 *
 *	Helper function to recycle input and output buffers. Ensures
 *	that two input buffers are saved (one in the input queue and
 *	another in the saveInBufPtr field) and that curOutPtr is set
 *	to a buffer. Only if these conditions are met is the buffer
 *	freed to the OS.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May free a buffer to the OS.
 *
 *----------------------------------------------------------------------
 */

static void
RecycleBuffer(chanPtr, bufPtr, mustDiscard)
    Channel *chanPtr;		/* Channel for which to recycle buffers. */
    ChannelBuffer *bufPtr;	/* The buffer to recycle. */
    int mustDiscard;		/* If nonzero, free the buffer to the
                                 * OS, always. */
{
    /*
     * Do we have to free the buffer to the OS?
     */

    if (mustDiscard) {
        ckfree((char *) bufPtr);
        return;
    }
    
    /*
     * Only save buffers for the input queue if the channel is readable.
     */
    
    if (chanPtr->flags & TCL_READABLE) {
        if (chanPtr->inQueueHead == (ChannelBuffer *) NULL) {
            chanPtr->inQueueHead = bufPtr;
            chanPtr->inQueueTail = bufPtr;
            goto keepit;
        }
        if (chanPtr->saveInBufPtr == (ChannelBuffer *) NULL) {
            chanPtr->saveInBufPtr = bufPtr;
            goto keepit;
        }
    }

    /*
     * Only save buffers for the output queue if the channel is writable.
     */

    if (chanPtr->flags & TCL_WRITABLE) {
        if (chanPtr->curOutPtr == (ChannelBuffer *) NULL) {
            chanPtr->curOutPtr = bufPtr;
            goto keepit;
        }
    }

    /*
     * If we reached this code we return the buffer to the OS.
     */

    ckfree((char *) bufPtr);
    return;

keepit:
    bufPtr->nextRemoved = 0;
    bufPtr->nextAdded = 0;
    bufPtr->nextPtr = (ChannelBuffer *) NULL;
}
 
/*
 *----------------------------------------------------------------------
 *
 * DiscardOutputQueued --
 *
 *	Discards all output queued in the output queue of a channel.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Recycles buffers.
 *
 *----------------------------------------------------------------------
 */

static void
DiscardOutputQueued(chanPtr)
    Channel *chanPtr;		/* The channel for which to discard output. */
{
    ChannelBuffer *bufPtr;
    
    while (chanPtr->outQueueHead != (ChannelBuffer *) NULL) {
        bufPtr = chanPtr->outQueueHead;
        chanPtr->outQueueHead = bufPtr->nextPtr;
        RecycleBuffer(chanPtr, bufPtr, 0);
    }
    chanPtr->outQueueHead = (ChannelBuffer *) NULL;
    chanPtr->outQueueTail = (ChannelBuffer *) NULL;
}
 
/*
 *----------------------------------------------------------------------
 *
 * CheckForDeadChannel --
 *
 *	This function checks is a given channel is Dead.
 *      (A channel that has been closed but not yet deallocated.)
 *
 * Results:
 *	True (1) if channel is Dead, False (0) if channel is Ok
 *
 * Side effects:
 *      None
 *
 *----------------------------------------------------------------------
 */

static int
CheckForDeadChannel(interp, chanPtr)
    Tcl_Interp *interp;		/* For error reporting (can be NULL) */
    Channel    *chanPtr;	/* The channel to check. */
{
    if (chanPtr->flags & CHANNEL_DEAD) {
        Tcl_SetErrno(EINVAL);
	if (interp) {
	    Tcl_AppendResult(interp,
			     "unable to access channel: invalid channel",
			     (char *) NULL);   
	}
	return 1;
    }
    return 0;
}
 
/*
 *----------------------------------------------------------------------
 *
 * FlushChannel --
 *
 *	This function flushes as much of the queued output as is possible
 *	now. If calledFromAsyncFlush is nonzero, it is being called in an
 *	event handler to flush channel output asynchronously.
 *
 * Results:
 *	0 if successful, else the error code that was returned by the
 *	channel type operation.
 *
 * Side effects:
 *	May produce output on a channel. May block indefinitely if the
 *	channel is synchronous. May schedule an async flush on the channel.
 *	May recycle memory for buffers in the output queue.
 *
 *----------------------------------------------------------------------
 */

static int
FlushChannel(interp, chanPtr, calledFromAsyncFlush)
    Tcl_Interp *interp;			/* For error reporting during close. */
    Channel *chanPtr;			/* The channel to flush on. */
    int calledFromAsyncFlush;		/* If nonzero then we are being
                                         * called from an asynchronous
                                         * flush callback. */
{
    ChannelBuffer *bufPtr;		/* Iterates over buffered output
                                         * queue. */
    int toWrite;			/* Amount of output data in current
                                         * buffer available to be written. */
    int written;			/* Amount of output data actually
                                         * written in current round. */
    int errorCode;			/* Stores POSIX error codes from
                                         * channel driver operations. */
    errorCode = 0;

    /*
     * Prevent writing on a dead channel -- a channel that has been closed
     * but not yet deallocated. This can occur if the exit handler for the
     * channel deallocation runs before all channels are deregistered in
     * all interpreters.
     */
    
    if (CheckForDeadChannel(interp,chanPtr)) return -1;
    
    /*
     * Loop over the queued buffers and attempt to flush as
     * much as possible of the queued output to the channel.
     */

    while (1) {

        /*
         * If the queue is empty and there is a ready current buffer, OR if
         * the current buffer is full, then move the current buffer to the
         * queue.
         */
        
        if (((chanPtr->curOutPtr != (ChannelBuffer *) NULL) &&
                (chanPtr->curOutPtr->nextAdded == chanPtr->curOutPtr->bufSize))
                || ((chanPtr->flags & BUFFER_READY) &&
                        (chanPtr->outQueueHead == (ChannelBuffer *) NULL))) {
            chanPtr->flags &= (~(BUFFER_READY));
            chanPtr->curOutPtr->nextPtr = (ChannelBuffer *) NULL;
            if (chanPtr->outQueueHead == (ChannelBuffer *) NULL) {
                chanPtr->outQueueHead = chanPtr->curOutPtr;
            } else {
                chanPtr->outQueueTail->nextPtr = chanPtr->curOutPtr;
            }
            chanPtr->outQueueTail = chanPtr->curOutPtr;
            chanPtr->curOutPtr = (ChannelBuffer *) NULL;
        }
        bufPtr = chanPtr->outQueueHead;

        /*
         * If we are not being called from an async flush and an async
         * flush is active, we just return without producing any output.
         */

        if ((!calledFromAsyncFlush) &&
                (chanPtr->flags & BG_FLUSH_SCHEDULED)) {
            return 0;
        }

        /*
         * If the output queue is still empty, break out of the while loop.
         */

        if (bufPtr == (ChannelBuffer *) NULL) {
            break;	/* Out of the "while (1)". */
        }

        /*
         * Produce the output on the channel.
         */
        
        toWrite = bufPtr->nextAdded - bufPtr->nextRemoved;
        written = (chanPtr->typePtr->outputProc) (chanPtr->instanceData,
                bufPtr->buf + bufPtr->nextRemoved, toWrite, &errorCode);
            
	/*
         * If the write failed completely attempt to start the asynchronous
         * flush mechanism and break out of this loop - do not attempt to
         * write any more output at this time.
         */

        if (written < 0) {
            
            /*
             * If the last attempt to write was interrupted, simply retry.
             */
            
            if (errorCode == EINTR) {
                errorCode = 0;
                continue;
            }

            /*
             * If the channel is non-blocking and we would have blocked,
             * start a background flushing handler and break out of the loop.
             */

            if ((errorCode == EWOULDBLOCK) || (errorCode == EAGAIN)) {
		if (chanPtr->flags & CHANNEL_NONBLOCKING) {
		    if (!(chanPtr->flags & BG_FLUSH_SCHEDULED)) {
			chanPtr->flags |= BG_FLUSH_SCHEDULED;
			UpdateInterest(chanPtr);
                    }
                    errorCode = 0;
                    break;
		} else {
		    panic("Blocking channel driver did not block on output");
                }
            }

            /*
             * Decide whether to report the error upwards or defer it.
             */

            if (calledFromAsyncFlush) {
                if (chanPtr->unreportedError == 0) {
                    chanPtr->unreportedError = errorCode;
                }
            } else {
                Tcl_SetErrno(errorCode);
		if (interp != NULL) {
		    Tcl_SetResult(interp,
			    Tcl_PosixError(interp), TCL_VOLATILE);
		}
            }

            /*
             * When we get an error we throw away all the output
             * currently queued.
             */

            DiscardOutputQueued(chanPtr);
            continue;
        }

        bufPtr->nextRemoved += written;

        /*
         * If this buffer is now empty, recycle it.
         */

        if (bufPtr->nextRemoved == bufPtr->nextAdded) {
            chanPtr->outQueueHead = bufPtr->nextPtr;
            if (chanPtr->outQueueHead == (ChannelBuffer *) NULL) {
                chanPtr->outQueueTail = (ChannelBuffer *) NULL;
            }
            RecycleBuffer(chanPtr, bufPtr, 0);
        }
    }	/* Closes "while (1)". */
    
    /*
     * If the queue became empty and we have the asynchronous flushing
     * mechanism active, cancel the asynchronous flushing.
     */

    if ((chanPtr->outQueueHead == (ChannelBuffer *) NULL) &&
            (chanPtr->flags & BG_FLUSH_SCHEDULED)) {
        chanPtr->flags &= (~(BG_FLUSH_SCHEDULED));
	(chanPtr->typePtr->watchProc)(chanPtr->instanceData,
		chanPtr->interestMask);
    }

    /*
     * If the channel is flagged as closed, delete it when the refCount
     * drops to zero, the output queue is empty and there is no output
     * in the current output buffer.
     */

    if ((chanPtr->flags & CHANNEL_CLOSED) && (chanPtr->refCount <= 0) &&
            (chanPtr->outQueueHead == (ChannelBuffer *) NULL) &&
            ((chanPtr->curOutPtr == (ChannelBuffer *) NULL) ||
                    (chanPtr->curOutPtr->nextAdded ==
                            chanPtr->curOutPtr->nextRemoved))) {
        return CloseChannel(interp, chanPtr, errorCode);
    }
    return errorCode;
}
 
/*
 *----------------------------------------------------------------------
 *
 * CloseChannel --
 *
 *	Utility procedure to close a channel and free its associated
 *	resources.
 *
 * Results:
 *	0 on success or a POSIX error code if the operation failed.
 *
 * Side effects:
 *	May close the actual channel; may free memory.
 *
 *----------------------------------------------------------------------
 */

static int
CloseChannel(interp, chanPtr, errorCode)
    Tcl_Interp *interp;			/* For error reporting. */
    Channel *chanPtr;			/* The channel to close. */
    int errorCode;			/* Status of operation so far. */
{
    int result = 0;			/* Of calling driver close
                                         * operation. */
    Channel *prevChanPtr;		/* Preceding channel in list of
                                         * all channels - used to splice a
                                         * channel out of the list on close. */
        
    if (chanPtr == NULL) {
        return result;
    }
    
    /*
     * No more input can be consumed so discard any leftover input.
     */

    DiscardInputQueued(chanPtr, 1);

    /*
     * Discard a leftover buffer in the current output buffer field.
     */

    if (chanPtr->curOutPtr != (ChannelBuffer *) NULL) {
        ckfree((char *) chanPtr->curOutPtr);
        chanPtr->curOutPtr = (ChannelBuffer *) NULL;
    }
    
    /*
     * The caller guarantees that there are no more buffers
     * queued for output.
     */

    if (chanPtr->outQueueHead != (ChannelBuffer *) NULL) {
        panic("TclFlush, closed channel: queued output left");
    }

    /*
     * If the EOF character is set in the channel, append that to the
     * output device.
     */

    if ((chanPtr->outEofChar != 0) && (chanPtr->flags & TCL_WRITABLE)) {
        int dummy;
        char c;

        c = (char) chanPtr->outEofChar;
        (chanPtr->typePtr->outputProc) (chanPtr->instanceData, &c, 1, &dummy);
    }

    /*
     * Remove TCL_READABLE and TCL_WRITABLE from chanPtr->flags, so
     * that close callbacks can not do input or output (assuming they
     * squirreled the channel away in their clientData). This also
     * prevents infinite loops if the callback calls any C API that
     * could call FlushChannel.
     */

    chanPtr->flags &= (~(TCL_READABLE|TCL_WRITABLE));
        
    /*
     * Splice this channel out of the list of all channels.
     */

    if (chanPtr == firstChanPtr) {
        firstChanPtr = chanPtr->nextChanPtr;
    } else {
        for (prevChanPtr = firstChanPtr;
                 (prevChanPtr != (Channel *) NULL) &&
                     (prevChanPtr->nextChanPtr != chanPtr);
                 prevChanPtr = prevChanPtr->nextChanPtr) {
            /* Empty loop body. */
        }
        if (prevChanPtr == (Channel *) NULL) {
            panic("FlushChannel: damaged channel list");
        }
        prevChanPtr->nextChanPtr = chanPtr->nextChanPtr;
    }

    /*
     * OK, close the channel itself.
     */
        
    result = (chanPtr->typePtr->closeProc) (chanPtr->instanceData, interp);
    
    if (chanPtr->channelName != (char *) NULL) {
        ckfree(chanPtr->channelName);
    }
    
    /*
     * If we are being called synchronously, report either
     * any latent error on the channel or the current error.
     */
        
    if (chanPtr->unreportedError != 0) {
        errorCode = chanPtr->unreportedError;
    }
    if (errorCode == 0) {
        errorCode = result;
        if (errorCode != 0) {
            Tcl_SetErrno(errorCode);
        }
    }

    /*
     * Cancel any outstanding timer.
     */

    Tcl_DeleteTimerHandler(chanPtr->timer);

    /*
     * Mark the channel as deleted by clearing the type structure.
     */

    chanPtr->typePtr = NULL;

    Tcl_EventuallyFree((ClientData) chanPtr, TCL_DYNAMIC);

    return errorCode;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_Close --
 *
 *	Closes a channel.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	Closes the channel if this is the last reference.
 *
 * NOTE:
 *	Tcl_Close removes the channel as far as the user is concerned.
 *	However, it may continue to exist for a while longer if it has
 *	a background flush scheduled. The device itself is eventually
 *	closed and the channel record removed, in CloseChannel, above.
 *
 *----------------------------------------------------------------------
 */

	/* ARGSUSED */
int
Tcl_Close(interp, chan)
    Tcl_Interp *interp;			/* Interpreter for errors. */
    Tcl_Channel chan;			/* The channel being closed. Must
                                         * not be referenced in any
                                         * interpreter. */
{
    ChannelHandler *chPtr, *chNext;	/* Iterate over channel handlers. */
    CloseCallback *cbPtr;		/* Iterate over close callbacks
                                         * for this channel. */
    EventScriptRecord *ePtr, *eNextPtr;	/* Iterate over eventscript records. */
    Channel *chanPtr;			/* The real IO channel. */
    int result;				/* Of calling FlushChannel. */
    NextChannelHandler *nhPtr;

    if (chan == (Tcl_Channel) NULL) {
        return TCL_OK;
    }
    
    /*
     * Perform special handling for standard channels being closed. If the
     * refCount is now 1 it means that the last reference to the standard
     * channel is being explicitly closed, so bump the refCount down
     * artificially to 0. This will ensure that the channel is actually
     * closed, below. Also set the static pointer to NULL for the channel.
     */

    CheckForStdChannelsBeingClosed(chan);

    chanPtr = (Channel *) chan;
    if (chanPtr->refCount > 0) {
        panic("called Tcl_Close on channel with refCount > 0");
    }

    /*
     * Remove any references to channel handlers for this channel that
     * may be about to be invoked.
     */

    for (nhPtr = nestedHandlerPtr;
             nhPtr != (NextChannelHandler *) NULL;
             nhPtr = nhPtr->nestedHandlerPtr) {
        if (nhPtr->nextHandlerPtr &&
		(nhPtr->nextHandlerPtr->chanPtr == chanPtr)) {
	    nhPtr->nextHandlerPtr = NULL;
        }
    }

    /*
     * Remove all the channel handler records attached to the channel
     * itself.
     */
        
    for (chPtr = chanPtr->chPtr;
             chPtr != (ChannelHandler *) NULL;
             chPtr = chNext) {
        chNext = chPtr->nextPtr;
        ckfree((char *) chPtr);
    }
    chanPtr->chPtr = (ChannelHandler *) NULL;
    
    
    /*
     * Cancel any pending copy operation.
     */

    StopCopy(chanPtr->csPtr);

    /*
     * Must set the interest mask now to 0, otherwise infinite loops
     * will occur if Tcl_DoOneEvent is called before the channel is
     * finally deleted in FlushChannel. This can happen if the channel
     * has a background flush active.
     */
        
    chanPtr->interestMask = 0;
    
    /*
     * Remove any EventScript records for this channel.
     */

    for (ePtr = chanPtr->scriptRecordPtr;
             ePtr != (EventScriptRecord *) NULL;
             ePtr = eNextPtr) {
        eNextPtr = ePtr->nextPtr;
	ckfree(ePtr->script);
        ckfree((char *) ePtr);
    }
    chanPtr->scriptRecordPtr = (EventScriptRecord *) NULL;
        
    /*
     * Invoke the registered close callbacks and delete their records.
     */

    while (chanPtr->closeCbPtr != (CloseCallback *) NULL) {
        cbPtr = chanPtr->closeCbPtr;
        chanPtr->closeCbPtr = cbPtr->nextPtr;
        (cbPtr->proc) (cbPtr->clientData);
        ckfree((char *) cbPtr);
    }

    /*
     * Ensure that the last output buffer will be flushed.
     */
    
    if ((chanPtr->curOutPtr != (ChannelBuffer *) NULL) &&
           (chanPtr->curOutPtr->nextAdded > chanPtr->curOutPtr->nextRemoved)) {
        chanPtr->flags |= BUFFER_READY;
    }

    /*
     * The call to FlushChannel will flush any queued output and invoke
     * the close function of the channel driver, or it will set up the
     * channel to be flushed and closed asynchronously.
     */
    
    chanPtr->flags |= CHANNEL_CLOSED;
    result = FlushChannel(interp, chanPtr, 0);
    if (result != 0) {
        return TCL_ERROR;
    }

    return TCL_OK;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_Write --
 *
 *	Puts a sequence of characters into an output buffer, may queue the
 *	buffer for output if it gets full, and also remembers whether the
 *	current buffer is ready e.g. if it contains a newline and we are in
 *	line buffering mode.
 *
 * Results:
 *	The number of bytes written or -1 in case of error. If -1,
 *	Tcl_GetErrno will return the error code.
 *
 * Side effects:
 *	May buffer up output and may cause output to be produced on the
 *	channel.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_Write(chan, srcPtr, slen)
    Tcl_Channel chan;			/* The channel to buffer output for. */
    char *srcPtr;			/* Output to buffer. */
    int slen;				/* Its length. Negative means
                                         * the output is null terminated
                                         * and we must compute its length. */
{
    Channel *chanPtr = (Channel *) chan;

    /*
     * Check for unreported error.
     */

    if (chanPtr->unreportedError != 0) {
        Tcl_SetErrno(chanPtr->unreportedError);
        chanPtr->unreportedError = 0;
        return -1;
    }
    
    /*
     * If the channel is not open for writing punt.
     */

    if (!(chanPtr->flags & TCL_WRITABLE)) {
        Tcl_SetErrno(EACCES);
        return -1;
    }
    
    /*
     * If the channel is in the middle of a background copy, fail.
     */

    if (chanPtr->csPtr) {
	Tcl_SetErrno(EBUSY);
	return -1;
    }

    /*
     * If length passed is negative, assume that the output is null terminated
     * and compute its length.
     */
    
    if (slen < 0) {
        slen = strlen(srcPtr);
    }

    return DoWrite(chanPtr, srcPtr, slen);
}
 
/*
 *----------------------------------------------------------------------
 *
 * DoWrite --
 *
 *	Puts a sequence of characters into an output buffer, may queue the
 *	buffer for output if it gets full, and also remembers whether the
 *	current buffer is ready e.g. if it contains a newline and we are in
 *	line buffering mode.
 *
 * Results:
 *	The number of bytes written or -1 in case of error. If -1,
 *	Tcl_GetErrno will return the error code.
 *
 * Side effects:
 *	May buffer up output and may cause output to be produced on the
 *	channel.
 *
 *----------------------------------------------------------------------
 */

static int
DoWrite(chanPtr, srcPtr, slen)
    Channel *chanPtr;			/* The channel to buffer output for. */
    char *srcPtr;			/* Data to write. */
    int slen;				/* Number of bytes to write. */
{
    ChannelBuffer *outBufPtr;		/* Current output buffer. */
    int foundNewline;			/* Did we find a newline in output? */
    char *dPtr, *sPtr;			/* Search variables for newline. */
    int crsent;				/* In CRLF eol translation mode,
                                         * remember the fact that a CR was
                                         * output to the channel without
                                         * its following NL. */
    int i;				/* Loop index for newline search. */
    int destCopied;			/* How many bytes were used in this
                                         * destination buffer to hold the
                                         * output? */
    int totalDestCopied;		/* How many bytes total were
                                         * copied to the channel buffer? */
    int srcCopied;			/* How many bytes were copied from
                                         * the source string? */
    char *destPtr;			/* Where in line to copy to? */

    /*
     * If we are in network (or windows) translation mode, record the fact
     * that we have not yet sent a CR to the channel.
     */

    crsent = 0;
    
    /*
     * Loop filling buffers and flushing them until all output has been
     * consumed.
     */

    srcCopied = 0;
    totalDestCopied = 0;

    while (slen > 0) {
        
        /*
         * Make sure there is a current output buffer to accept output.
         */

        if (chanPtr->curOutPtr == (ChannelBuffer *) NULL) {
            chanPtr->curOutPtr = (ChannelBuffer *) ckalloc((unsigned)
                    (CHANNELBUFFER_HEADER_SIZE + chanPtr->bufSize));
            chanPtr->curOutPtr->nextAdded = 0;
            chanPtr->curOutPtr->nextRemoved = 0;
            chanPtr->curOutPtr->bufSize = chanPtr->bufSize;
            chanPtr->curOutPtr->nextPtr = (ChannelBuffer *) NULL;
        }

        outBufPtr = chanPtr->curOutPtr;

        destCopied = outBufPtr->bufSize - outBufPtr->nextAdded;
        if (destCopied > slen) {
            destCopied = slen;
        }
        
        destPtr = outBufPtr->buf + outBufPtr->nextAdded;
        switch (chanPtr->outputTranslation) {
            case TCL_TRANSLATE_LF:
                srcCopied = destCopied;
                memcpy((VOID *) destPtr, (VOID *) srcPtr, (size_t) destCopied);
                break;
            case TCL_TRANSLATE_CR:
                srcCopied = destCopied;
                memcpy((VOID *) destPtr, (VOID *) srcPtr, (size_t) destCopied);
                for (dPtr = destPtr; dPtr < destPtr + destCopied; dPtr++) {
                    if (*dPtr == '\n') {
                        *dPtr = '\r';
                    }
                }
                break;
            case TCL_TRANSLATE_CRLF:
                for (srcCopied = 0, dPtr = destPtr, sPtr = srcPtr;
                     dPtr < destPtr + destCopied;
                     dPtr++, sPtr++, srcCopied++) {
                    if (*sPtr == '\n') {
                        if (crsent) {
                            *dPtr = '\n';
                            crsent = 0;
                        } else {
                            *dPtr = '\r';
                            crsent = 1;
                            sPtr--, srcCopied--;
                        }
                    } else {
                        *dPtr = *sPtr;
                    }
                }
                break;
            case TCL_TRANSLATE_AUTO:
                panic("Tcl_Write: AUTO output translation mode not supported");
            default:
                panic("Tcl_Write: unknown output translation mode");
        }

        /*
         * The current buffer is ready for output if it is full, or if it
         * contains a newline and this channel is line-buffered, or if it
         * contains any output and this channel is unbuffered.
         */

        outBufPtr->nextAdded += destCopied;
        if (!(chanPtr->flags & BUFFER_READY)) {
            if (outBufPtr->nextAdded == outBufPtr->bufSize) {
                chanPtr->flags |= BUFFER_READY;
            } else if (chanPtr->flags & CHANNEL_LINEBUFFERED) {
                for (sPtr = srcPtr, i = 0, foundNewline = 0;
                         (i < srcCopied) && (!foundNewline);
                         i++, sPtr++) {
                    if (*sPtr == '\n') {
                        foundNewline = 1;
                        break;
                    }
                }
                if (foundNewline) {
                    chanPtr->flags |= BUFFER_READY;
                }
            } else if (chanPtr->flags & CHANNEL_UNBUFFERED) {
                chanPtr->flags |= BUFFER_READY;
            }
        }
        
        totalDestCopied += srcCopied;
        srcPtr += srcCopied;
        slen -= srcCopied;

        if (chanPtr->flags & BUFFER_READY) {
            if (FlushChannel(NULL, chanPtr, 0) != 0) {
                return -1;
            }
        }
    } /* Closes "while" */

    return totalDestCopied;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_Flush --
 *
 *	Flushes output data on a channel.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	May flush output queued on this channel.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_Flush(chan)
    Tcl_Channel chan;			/* The Channel to flush. */
{
    int result;				/* Of calling FlushChannel. */
    Channel *chanPtr;			/* The actual channel. */

    chanPtr = (Channel *) chan;

    /*
     * Check for unreported error.
     */

    if (chanPtr->unreportedError != 0) {
        Tcl_SetErrno(chanPtr->unreportedError);
        chanPtr->unreportedError = 0;
        return TCL_ERROR;
    }

    /*
     * If the channel is not open for writing punt.
     */

    if (!(chanPtr->flags & TCL_WRITABLE)) {
        Tcl_SetErrno(EACCES);
        return TCL_ERROR;
    }
    
    /*
     * If the channel is in the middle of a background copy, fail.
     */

    if (chanPtr->csPtr) {
	Tcl_SetErrno(EBUSY);
	return -1;
    }

    /*
     * Force current output buffer to be output also.
     */
    
    if ((chanPtr->curOutPtr != (ChannelBuffer *) NULL) &&
            (chanPtr->curOutPtr->nextAdded > 0)) {
        chanPtr->flags |= BUFFER_READY;
    }
    
    result = FlushChannel(NULL, chanPtr, 0);
    if (result != 0) {
        return TCL_ERROR;
    }

    return TCL_OK;
}
 
/*
 *----------------------------------------------------------------------
 *
 * DiscardInputQueued --
 *
 *	Discards any input read from the channel but not yet consumed
 *	by Tcl reading commands.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May discard input from the channel. If discardLastBuffer is zero,
 *	leaves one buffer in place for back-filling.
 *
 *----------------------------------------------------------------------
 */

static void
DiscardInputQueued(chanPtr, discardSavedBuffers)
    Channel *chanPtr;		/* Channel on which to discard
                                 * the queued input. */
    int discardSavedBuffers;	/* If non-zero, discard all buffers including
                                 * last one. */
{
    ChannelBuffer *bufPtr, *nxtPtr;	/* Loop variables. */

    bufPtr = chanPtr->inQueueHead;
    chanPtr->inQueueHead = (ChannelBuffer *) NULL;
    chanPtr->inQueueTail = (ChannelBuffer *) NULL;
    for (; bufPtr != (ChannelBuffer *) NULL; bufPtr = nxtPtr) {
        nxtPtr = bufPtr->nextPtr;
        RecycleBuffer(chanPtr, bufPtr, discardSavedBuffers);
    }

    /*
     * If discardSavedBuffers is nonzero, must also discard any previously
     * saved buffer in the saveInBufPtr field.
     */
    
    if (discardSavedBuffers) {
        if (chanPtr->saveInBufPtr != (ChannelBuffer *) NULL) {
            ckfree((char *) chanPtr->saveInBufPtr);
            chanPtr->saveInBufPtr = (ChannelBuffer *) NULL;
        }
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * GetInput --
 *
 *	Reads input data from a device or file into an input buffer.
 *
 * Results:
 *	A Posix error code or 0.
 *
 * Side effects:
 *	Reads from the underlying device.
 *
 *----------------------------------------------------------------------
 */

static int
GetInput(chanPtr)
    Channel *chanPtr;			/* Channel to read input from. */
{
    int toRead;				/* How much to read? */
    int result;				/* Of calling driver. */
    int nread;				/* How much was read from channel? */
    ChannelBuffer *bufPtr;		/* New buffer to add to input queue. */

    /*
     * Prevent reading from a dead channel -- a channel that has been closed
     * but not yet deallocated, which can happen if the exit handler for
     * channel cleanup has run but the channel is still registered in some
     * interpreter.
     */
    
    if (CheckForDeadChannel(NULL,chanPtr)) return EINVAL;

    /*
     * See if we can fill an existing buffer. If we can, read only
     * as much as will fit in it. Otherwise allocate a new buffer,
     * add it to the input queue and attempt to fill it to the max.
     */

    if ((chanPtr->inQueueTail != (ChannelBuffer *) NULL) &&
           (chanPtr->inQueueTail->nextAdded < chanPtr->inQueueTail->bufSize)) {
        bufPtr = chanPtr->inQueueTail;
        toRead = bufPtr->bufSize - bufPtr->nextAdded;
    } else {
	if (chanPtr->saveInBufPtr != (ChannelBuffer *) NULL) {
	    bufPtr = chanPtr->saveInBufPtr;
	    chanPtr->saveInBufPtr = (ChannelBuffer *) NULL;
	} else {
	    bufPtr = (ChannelBuffer *) ckalloc(
		((unsigned) CHANNELBUFFER_HEADER_SIZE + chanPtr->bufSize));
	    bufPtr->bufSize = chanPtr->bufSize;
	}
	bufPtr->nextRemoved = 0;
	bufPtr->nextAdded = 0;
        toRead = bufPtr->bufSize;
        if (chanPtr->inQueueTail == (ChannelBuffer *) NULL) {
            chanPtr->inQueueHead = bufPtr;
        } else {
            chanPtr->inQueueTail->nextPtr = bufPtr;
        }
        chanPtr->inQueueTail = bufPtr;
        bufPtr->nextPtr = (ChannelBuffer *) NULL;
    }
      
    /*
     * If EOF is set, we should avoid calling the driver because on some
     * platforms it is impossible to read from a device after EOF.
     */

    if (chanPtr->flags & CHANNEL_EOF) {
	return 0;
    }

    nread = (chanPtr->typePtr->inputProc) (chanPtr->instanceData,
	    bufPtr->buf + bufPtr->nextAdded, toRead, &result);

    if (nread == 0) {
	chanPtr->flags |= CHANNEL_EOF;
    } else if (nread < 0) {
	if ((result == EWOULDBLOCK) || (result == EAGAIN)) {
	    chanPtr->flags |= CHANNEL_BLOCKED;
	    result = EAGAIN;
	    if (chanPtr->flags & CHANNEL_NONBLOCKING) {
		Tcl_SetErrno(result);
	    } else {
		panic("Blocking channel driver did not block on input");
	    }
	} else {
	    Tcl_SetErrno(result);
	}
	return result;
    } else {
	bufPtr->nextAdded += nread;

	/*
	 * If we get a short read, signal up that we may be BLOCKED. We
	 * should avoid calling the driver because on some platforms we
	 * will block in the low level reading code even though the
	 * channel is set into nonblocking mode.
	 */
            
	if (nread < toRead) {
	    chanPtr->flags |= CHANNEL_BLOCKED;
	}
    }
    return 0;
}
 
/*
 *----------------------------------------------------------------------
 *
 * CopyAndTranslateBuffer --
 *
 *	Copy at most one buffer of input to the result space, doing
 *	eol translations according to mode in effect currently.
 *
 * Results:
 *	Number of characters (as opposed to bytes) copied. May return
 *	zero if no input is available to be translated.
 *
 * Side effects:
 *	Consumes buffered input. May deallocate one buffer.
 *
 *----------------------------------------------------------------------
 */

static int
CopyAndTranslateBuffer(chanPtr, result, space)
    Channel *chanPtr;		/* The channel from which to read input. */
    char *result;		/* Where to store the copied input. */
    int space;			/* How many bytes are available in result
                                 * to store the copied input? */
{
    int bytesInBuffer;		/* How many bytes are available to be
                                 * copied in the current input buffer? */
    int copied;			/* How many characters were already copied
                                 * into the destination space? */
    ChannelBuffer *bufPtr;	/* The buffer from which to copy bytes. */
    char curByte;		/* The byte we are currently translating. */
    int i;			/* Iterates over the copied input looking
                                 * for the input eofChar. */
    
    /*
     * If there is no input at all, return zero. The invariant is that either
     * there is no buffer in the queue, or if the first buffer is empty, it
     * is also the last buffer (and thus there is no input in the queue).
     * Note also that if the buffer is empty, we leave it in the queue.
     */
    
    if (chanPtr->inQueueHead == (ChannelBuffer *) NULL) {
        return 0;
    }
    bufPtr = chanPtr->inQueueHead;
    bytesInBuffer = bufPtr->nextAdded - bufPtr->nextRemoved;
    if (bytesInBuffer < space) {
        space = bytesInBuffer;
    }
    copied = 0;
    switch (chanPtr->inputTranslation) {
        case TCL_TRANSLATE_LF:

            if (space == 0) {
                return 0;
            }
            
	    /*
             * Copy the current chunk into the result buffer.
             */

            memcpy((VOID *) result,
                    (VOID *)(bufPtr->buf + bufPtr->nextRemoved),
                    (size_t) space);
            bufPtr->nextRemoved += space;
            copied = space;
            break;

        case TCL_TRANSLATE_CR:

            if (space == 0) {
                return 0;
            }

	    /*
             * Copy the current chunk into the result buffer, then
             * replace all \r with \n.
             */

            memcpy((VOID *) result,
                    (VOID *)(bufPtr->buf + bufPtr->nextRemoved),
                    (size_t) space);
            bufPtr->nextRemoved += space;
            for (copied = 0; copied < space; copied++) {
                if (result[copied] == '\r') {
                    result[copied] = '\n';
                }
            }
            break;

        case TCL_TRANSLATE_CRLF:

            /*
             * If there is a held-back "\r" at EOF, produce it now.
             */
            
            if (space == 0) {
                if ((chanPtr->flags & (INPUT_SAW_CR | CHANNEL_EOF)) ==
                        (INPUT_SAW_CR | CHANNEL_EOF)) {
                    result[0] = '\r';
                    chanPtr->flags &= (~(INPUT_SAW_CR));
                    return 1;
                }
                return 0;
            }

            /*
             * Copy the current chunk and replace "\r\n" with "\n"
             * (but not standalone "\r"!).
             */

            for (copied = 0;
                     (copied < space) &&
                         (bufPtr->nextRemoved < bufPtr->nextAdded);
                     copied++) {
                curByte = bufPtr->buf[bufPtr->nextRemoved];
                bufPtr->nextRemoved++;
                if (curByte == '\r') {
                    if (chanPtr->flags & INPUT_SAW_CR) {
                        result[copied] = '\r';
                    } else {
                        chanPtr->flags |= INPUT_SAW_CR;
                        copied--;
                    }
                } else if (curByte == '\n') {
                    chanPtr->flags &= (~(INPUT_SAW_CR));
                    result[copied] = '\n';
                } else {
                    if (chanPtr->flags & INPUT_SAW_CR) {
                        chanPtr->flags &= (~(INPUT_SAW_CR));
                        result[copied] = '\r';
                        bufPtr->nextRemoved--;
                    } else {
                        result[copied] = curByte;
                    }
                }
            }
            break;
                
        case TCL_TRANSLATE_AUTO:
            
            if (space == 0) {
                return 0;
            }

            /*
             * Loop over the current buffer, converting "\r" and "\r\n"
             * to "\n".
             */

            for (copied = 0;
                     (copied < space) &&
                         (bufPtr->nextRemoved < bufPtr->nextAdded); ) {
                curByte = bufPtr->buf[bufPtr->nextRemoved];
                bufPtr->nextRemoved++;
                if (curByte == '\r') {
                    result[copied] = '\n';
		    copied++;
                    if (bufPtr->nextRemoved < bufPtr->nextAdded) {
                        if (bufPtr->buf[bufPtr->nextRemoved] == '\n') {
                            bufPtr->nextRemoved++;
                        }
                        chanPtr->flags &= (~(INPUT_SAW_CR));
                    } else {
                        chanPtr->flags |= INPUT_SAW_CR;
                    }
                } else {
                    if (curByte == '\n') {
                        if (!(chanPtr->flags & INPUT_SAW_CR)) {
                            result[copied] = '\n';
			    copied++;
                        }
                    } else {
                        result[copied] = curByte;
			copied++;
                    }
                    chanPtr->flags &= (~(INPUT_SAW_CR));
                }
            }
            break;

        default:
            panic("unknown eol translation mode");
    }

    /*
     * If an in-stream EOF character is set for this channel,, check that
     * the input we copied so far does not contain the EOF char. If it does,
     * copy only up to and excluding that character.
     */
    
    if (chanPtr->inEofChar != 0) {
        for (i = 0; i < copied; i++) {
            if (result[i] == (char) chanPtr->inEofChar) {
                break;
            }
        }
        if (i < copied) {

            /*
             * Set sticky EOF so that no further input is presented
             * to the caller.
             */
            
            chanPtr->flags |= (CHANNEL_EOF | CHANNEL_STICKY_EOF);

            /*
             * Reset the start of valid data in the input buffer to the
             * position of the eofChar, so that subsequent reads will
             * encounter it immediately. First we set it to the position
             * of the last byte consumed if all result bytes were the
             * product of one input byte; since it is possible that "\r\n"
             * contracted to "\n" in the result, we have to search back
             * from that position until we find the eofChar, because it
             * is possible that its actual position in the buffer is n
             * bytes further back (n is the number of "\r\n" sequences
             * that were contracted to "\n" in the result).
             */
                  
            bufPtr->nextRemoved -= (copied - i);
            while ((bufPtr->nextRemoved > 0) &&
                    (bufPtr->buf[bufPtr->nextRemoved] !=
                            (char) chanPtr->inEofChar)) {
                bufPtr->nextRemoved--;
            }
            copied = i;
        }
    }

    /*
     * If the current buffer is empty recycle it.
     */

    if (bufPtr->nextRemoved == bufPtr->nextAdded) {
        chanPtr->inQueueHead = bufPtr->nextPtr;
        if (chanPtr->inQueueHead == (ChannelBuffer *) NULL) {
            chanPtr->inQueueTail = (ChannelBuffer *) NULL;
        }
        RecycleBuffer(chanPtr, bufPtr, 0);
    }

    /*
     * Return the number of characters copied into the result buffer.
     * This may be different from the number of bytes consumed, because
     * of EOL translations.
     */

    return copied;
}
 
/*
 *----------------------------------------------------------------------
 *
 * ScanBufferForEOL --
 *
 *	Scans one buffer for EOL according to the specified EOL
 *	translation mode. If it sees the input eofChar for the channel
 *	it stops also.
 *
 * Results:
 *	TRUE if EOL is found, FALSE otherwise. Also sets output parameter
 *	bytesToEOLPtr to the number of bytes so far to EOL, and crSeenPtr
 *	to whether a "\r" was seen.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
ScanBufferForEOL(chanPtr, bufPtr, translation, eofChar, bytesToEOLPtr,
                 crSeenPtr)
    Channel *chanPtr;
    ChannelBuffer *bufPtr;		/* Buffer to scan for EOL. */
    Tcl_EolTranslation translation;	/* Translation mode to use. */
    int eofChar;			/* EOF char to look for. */
    int *bytesToEOLPtr;			/* Running counter. */
    int *crSeenPtr;			/* Has "\r" been seen? */
{
    char *rPtr;				/* Iterates over input string. */
    char *sPtr;				/* Where to stop search? */
    int EOLFound;
    int bytesToEOL;
    
    for (EOLFound = 0, rPtr = bufPtr->buf + bufPtr->nextRemoved,
             sPtr = bufPtr->buf + bufPtr->nextAdded,
             bytesToEOL = *bytesToEOLPtr;
             (!EOLFound) && (rPtr < sPtr);
             rPtr++) {
        switch (translation) {
            case TCL_TRANSLATE_AUTO:
                if ((*rPtr == (char) eofChar) && (eofChar != 0)) {
                    chanPtr->flags |= (CHANNEL_EOF | CHANNEL_STICKY_EOF);
                    EOLFound = 1;
                } else if (*rPtr == '\n') {

		    /*
                     * CopyAndTranslateBuffer wants to know the length
                     * of the result, not the input. The input is one
                     * larger because "\r\n" shrinks to "\n".
                     */

                    if (!(*crSeenPtr)) {
                        bytesToEOL++;
			EOLFound = 1;
                    } else {

			/*
			 * This is a lf at the begining of a buffer
			 * where the previous buffer ended in a cr.
			 * Consume this lf because we've already emitted
			 * the newline for this crlf sequence. ALSO, if
                         * bytesToEOL is 0 (which means that we are at the
                         * first character of the scan), unset the
                         * INPUT_SAW_CR flag in the channel, because we
                         * already handled it; leaving it set would cause
                         * CopyAndTranslateBuffer to potentially consume
                         * another lf if one follows the current byte.
			 */

			bufPtr->nextRemoved++;
                        *crSeenPtr = 0;
                        chanPtr->flags &= (~(INPUT_SAW_CR));
		    }
                } else if (*rPtr == '\r') {
                    bytesToEOL++;
                    EOLFound = 1;
                } else {
                    *crSeenPtr = 0;
                    bytesToEOL++;
                }
                break;
            case TCL_TRANSLATE_LF:
                if ((*rPtr == (char) eofChar) && (eofChar != 0)) {
                    chanPtr->flags |= (CHANNEL_EOF | CHANNEL_STICKY_EOF);
                    EOLFound = 1;
                } else {
                    if (*rPtr == '\n') {
                        EOLFound = 1;
                    }
                    bytesToEOL++;
                }
                break;
            case TCL_TRANSLATE_CR:
                if ((*rPtr == (char) eofChar) && (eofChar != 0)) {
                    chanPtr->flags |= (CHANNEL_EOF | CHANNEL_STICKY_EOF);
                    EOLFound = 1;
                } else {
                    if (*rPtr == '\r') {
                        EOLFound = 1;
                    }
                    bytesToEOL++;
                }
                break;
            case TCL_TRANSLATE_CRLF:
                if ((*rPtr == (char) eofChar) && (eofChar != 0)) {
                    chanPtr->flags |= (CHANNEL_EOF | CHANNEL_STICKY_EOF);
                    EOLFound = 1;
                } else if (*rPtr == '\n') {

                    /*
                     * CopyAndTranslateBuffer wants to know the length
                     * of the result, not the input. The input is one
                     * larger because crlf shrinks to lf.
                     */

                    if (*crSeenPtr) {
                        EOLFound = 1;
                    } else {
                        bytesToEOL++;
                    }
                } else {
                    if (*rPtr == '\r') {
                        *crSeenPtr = 1;
                    } else {
                        *crSeenPtr = 0;
                    }
                    bytesToEOL++;
                }
                break;
            default:
                panic("unknown eol translation mode");
        }
    }

    *bytesToEOLPtr = bytesToEOL;
    return EOLFound;
}
 
/*
 *----------------------------------------------------------------------
 *
 * ScanInputForEOL --
 *
 *	Scans queued input for chanPtr for an end of line (according to the
 *	current EOL translation mode) and returns the number of bytes
 *	upto and including the end of line, or -1 if none was found.
 *
 * Results:
 *	Count of bytes upto and including the end of line if one is present
 *	or -1 if none was found. Also returns in an output parameter the
 *	number of bytes queued if no end of line was found.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
ScanInputForEOL(chanPtr, bytesQueuedPtr)
    Channel *chanPtr;	/* Channel for which to scan queued
                                 * input for end of line. */
    int *bytesQueuedPtr;	/* Where to store the number of bytes
                                 * currently queued if no end of line
                                 * was found. */
{
    ChannelBuffer *bufPtr;	/* Iterates over queued buffers. */
    int bytesToEOL;		/* How many bytes to end of line? */
    int EOLFound;		/* Did we find an end of line? */
    int crSeen;			/* Did we see a "\r" in CRLF mode? */

    *bytesQueuedPtr = 0;
    bytesToEOL = 0;
    EOLFound = 0;
    for (bufPtr = chanPtr->inQueueHead,
             crSeen = (chanPtr->flags & INPUT_SAW_CR) ? 1 : 0;
            (!EOLFound) && (bufPtr != (ChannelBuffer *) NULL);
            bufPtr = bufPtr->nextPtr) {
        EOLFound = ScanBufferForEOL(chanPtr, bufPtr, chanPtr->inputTranslation,
                chanPtr->inEofChar, &bytesToEOL, &crSeen);
    }

    if (EOLFound == 0) {
        *bytesQueuedPtr = bytesToEOL;
        return -1;
    }
    return bytesToEOL;        
}
 
/*
 *----------------------------------------------------------------------
 *
 * GetEOL --
 *
 *	Accumulate input into the channel input buffer queue until an
 *	end of line has been seen.
 *
 * Results:
 *	Number of bytes buffered (at least 1) or -1 on failure.
 *
 * Side effects:
 *	Consumes input from the channel.
 *
 *----------------------------------------------------------------------
 */

static int
GetEOL(chanPtr)
    Channel *chanPtr;	/* Channel to queue input on. */
{
    int bytesToEOL;		/* How many bytes in buffer up to and
                                 * including the end of line? */
    int bytesQueued;		/* How many bytes are queued currently
                                 * in the input chain of the channel? */

    /*
     * Check for unreported error.
     */

    if (chanPtr->unreportedError != 0) {
        Tcl_SetErrno(chanPtr->unreportedError);
        chanPtr->unreportedError = 0;
        return -1;
    }

    /*
     * Punt if the channel is not opened for reading.
     */

    if (!(chanPtr->flags & TCL_READABLE)) {
        Tcl_SetErrno(EACCES);
        return -1;
    }

    /*
     * If the channel is in the middle of a background copy, fail.
     */

    if (chanPtr->csPtr) {
	Tcl_SetErrno(EBUSY);
	return -1;
    }

    /*
     * If we have not encountered a sticky EOF, clear the EOF bit
     * (sticky EOF is set if we have seen the input eofChar, to prevent
     * reading beyond the eofChar). Also, always clear the BLOCKED bit.
     * We want to discover these conditions anew in each operation.
     */
    
    if (!(chanPtr->flags & CHANNEL_STICKY_EOF)) {
        chanPtr->flags &= (~(CHANNEL_EOF));
    }
    chanPtr->flags &= (~(CHANNEL_BLOCKED | CHANNEL_GETS_BLOCKED));

    while (1) {
        bytesToEOL = ScanInputForEOL(chanPtr, &bytesQueued);
        if (bytesToEOL > 0) {
            chanPtr->flags &= (~(CHANNEL_BLOCKED));
            return bytesToEOL;
        }
        if (chanPtr->flags & CHANNEL_EOF) {
	    /*
	     * Boundary case where cr was at the end of the previous buffer
	     * and this buffer just has a newline.  At EOF our caller wants
	     * to see -1 for the line length.
	     */
            return (bytesQueued == 0) ? -1 : bytesQueued ;
        }
        if (chanPtr->flags & CHANNEL_BLOCKED) {
            if (chanPtr->flags & CHANNEL_NONBLOCKING) {
		goto blocked;
            }
            chanPtr->flags &= (~(CHANNEL_BLOCKED));
        }
	if (GetInput(chanPtr) != 0) {
	    goto blocked;
        }
    }

    blocked:

    /*
     * We didn't get a complete line so we need to indicate to UpdateInterest
     * that the gets blocked.  It will wait for more data instead of firing
     * a timer, avoiding a busy wait.  This is where we are assuming that the
     * next operation is a gets.  No more file events will be delivered on 
     * this channel until new data arrives or some operation is performed
     * on the channel (e.g. gets, read, fconfigure) that changes the blocking
     * state.  Note that this means a file event will not be delivered even
     * though a read would be able to consume the buffered data.
     */

    chanPtr->flags |= CHANNEL_GETS_BLOCKED;
    return -1;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_Read --
 *
 *	Reads a given number of characters from a channel.
 *
 * Results:
 *	The number of characters read, or -1 on error. Use Tcl_GetErrno()
 *	to retrieve the error code for the error that occurred.
 *
 * Side effects:
 *	May cause input to be buffered.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_Read(chan, bufPtr, toRead)
    Tcl_Channel chan;		/* The channel from which to read. */
    char *bufPtr;		/* Where to store input read. */
    int toRead;			/* Maximum number of characters to read. */
{
    Channel *chanPtr;		/* The real IO channel. */
    
    chanPtr = (Channel *) chan;

    /*
     * Check for unreported error.
     */

    if (chanPtr->unreportedError != 0) {
        Tcl_SetErrno(chanPtr->unreportedError);
        chanPtr->unreportedError = 0;
        return -1;
    }

    /*
     * Punt if the channel is not opened for reading.
     */

    if (!(chanPtr->flags & TCL_READABLE)) {
        Tcl_SetErrno(EACCES);
        return -1;
    }
    
    /*
     * If the channel is in the middle of a background copy, fail.
     */

    if (chanPtr->csPtr) {
	Tcl_SetErrno(EBUSY);
	return -1;
    }

    return DoRead(chanPtr, bufPtr, toRead);
}
 
/*
 *----------------------------------------------------------------------
 *
 * DoRead --
 *
 *	Reads a given number of characters from a channel.
 *
 * Results:
 *	The number of characters read, or -1 on error. Use Tcl_GetErrno()
 *	to retrieve the error code for the error that occurred.
 *
 * Side effects:
 *	May cause input to be buffered.
 *
 *----------------------------------------------------------------------
 */

static int
DoRead(chanPtr, bufPtr, toRead)
    Channel *chanPtr;		/* The channel from which to read. */
    char *bufPtr;		/* Where to store input read. */
    int toRead;			/* Maximum number of characters to read. */
{
    int copied;			/* How many characters were copied into
                                 * the result string? */
    int copiedNow;		/* How many characters were copied from
                                 * the current input buffer? */
    int result;			/* Of calling GetInput. */
    
    /*
     * If we have not encountered a sticky EOF, clear the EOF bit. Either
     * way clear the BLOCKED bit. We want to discover these anew during
     * each operation.
     */

    if (!(chanPtr->flags & CHANNEL_STICKY_EOF)) {
        chanPtr->flags &= (~(CHANNEL_EOF));
    }
    chanPtr->flags &= (~(CHANNEL_BLOCKED | CHANNEL_GETS_BLOCKED));
    
    for (copied = 0; copied < toRead; copied += copiedNow) {
        copiedNow = CopyAndTranslateBuffer(chanPtr, bufPtr + copied,
                toRead - copied);
        if (copiedNow == 0) {
            if (chanPtr->flags & CHANNEL_EOF) {
		goto done;
            }
            if (chanPtr->flags & CHANNEL_BLOCKED) {
                if (chanPtr->flags & CHANNEL_NONBLOCKING) {
		    goto done;
                }
                chanPtr->flags &= (~(CHANNEL_BLOCKED));
            }
            result = GetInput(chanPtr);
            if (result != 0) {
                if (result != EAGAIN) {
		    copied = -1;
                }
		goto done;
            }
        }
    }

    chanPtr->flags &= (~(CHANNEL_BLOCKED));

    done:
    /*
     * Update the notifier state so we don't block while there is still
     * data in the buffers.
     */

    UpdateInterest(chanPtr);
    return copied;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_Gets --
 *
 *	Reads a complete line of input from the channel into a
 *	Tcl_DString.
 *
 * Results:
 *	Length of line read or -1 if error, EOF or blocked. If -1, use
 *	Tcl_GetErrno() to retrieve the POSIX error code for the
 *	error or condition that occurred.
 *
 * Side effects:
 *	May flush output on the channel. May cause input to be
 *	consumed from the channel.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_Gets(chan, lineRead)
    Tcl_Channel chan;		/* Channel from which to read. */
    Tcl_DString *lineRead;	/* The characters of the line read
                                 * (excluding the terminating newline if
                                 * present) will be appended to this
                                 * DString. The caller must have initialized
                                 * it and is responsible for managing the
                                 * storage. */
{
    Channel *chanPtr;		/* The channel to read from. */
    char *buf;			/* Points into DString where data
                                 * will be stored. */
    int offset;			/* Offset from start of DString at
                                 * which to append the line just read. */
    int copiedTotal;		/* Accumulates total length of input copied. */
    int copiedNow;		/* How many bytes were copied from the
                                 * current input buffer? */
    int lineLen;		/* Length of line read, including the
                                 * translated newline. If this is zero
                                 * and neither EOF nor BLOCKED is set,
                                 * the current line is empty. */
    
    chanPtr = (Channel *) chan;

    lineLen = GetEOL(chanPtr);
    if (lineLen < 0) {
	copiedTotal = -1;
	goto done;
    }
    offset = Tcl_DStringLength(lineRead);
    Tcl_DStringSetLength(lineRead, lineLen + offset);
    buf = Tcl_DStringValue(lineRead) + offset;

    for (copiedTotal = 0; copiedTotal < lineLen; copiedTotal += copiedNow) {
        copiedNow = CopyAndTranslateBuffer(chanPtr, buf + copiedTotal,
                lineLen - copiedTotal);
    }
    if ((copiedTotal > 0) && (buf[copiedTotal - 1] == '\n')) {
        copiedTotal--;
    }
    Tcl_DStringSetLength(lineRead, copiedTotal + offset);

    done:
    /*
     * Update the notifier state so we don't block while there is still
     * data in the buffers.
     */

    UpdateInterest(chanPtr);
    return copiedTotal;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_GetsObj --
 *
 *	Reads a complete line of input from the channel into a
 *	string object.
 *
 * Results:
 *	Length of line read or -1 if error, EOF or blocked. If -1, use
 *	Tcl_GetErrno() to retrieve the POSIX error code for the
 *	error or condition that occurred.
 *
 * Side effects:
 *	May flush output on the channel. May cause input to be
 *	consumed from the channel.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_GetsObj(chan, objPtr)
    Tcl_Channel chan;		/* Channel from which to read. */
    Tcl_Obj *objPtr;		/* The characters of the line read
                                 * (excluding the terminating newline if
                                 * present) will be appended to this
                                 * object. The caller must have initialized
                                 * it and is responsible for managing the
                                 * storage. */
{
    Channel *chanPtr;		/* The channel to read from. */
    char *buf;			/* Points into DString where data
                                 * will be stored. */
    int offset;			/* Offset from start of DString at
                                 * which to append the line just read. */
    int copiedTotal;		/* Accumulates total length of input copied. */
    int copiedNow;		/* How many bytes were copied from the
                                 * current input buffer? */
    int lineLen;		/* Length of line read, including the
                                 * translated newline. If this is zero
                                 * and neither EOF nor BLOCKED is set,
                                 * the current line is empty. */
    
    chanPtr = (Channel *) chan;

    lineLen = GetEOL(chanPtr);
    if (lineLen < 0) {
	copiedTotal = -1;
	goto done;
    }

    (void) Tcl_GetStringFromObj(objPtr, &offset);
    Tcl_SetObjLength(objPtr, lineLen + offset);
    buf = Tcl_GetStringFromObj(objPtr, NULL) + offset;

    for (copiedTotal = 0; copiedTotal < lineLen; copiedTotal += copiedNow) {
        copiedNow = CopyAndTranslateBuffer(chanPtr, buf + copiedTotal,
                lineLen - copiedTotal);
    }
    if ((copiedTotal > 0) && (buf[copiedTotal - 1] == '\n')) {
        copiedTotal--;
    }
    Tcl_SetObjLength(objPtr, copiedTotal + offset);

    done:
    /*
     * Update the notifier state so we don't block while there is still
     * data in the buffers.
     */

    UpdateInterest(chanPtr);
    return copiedTotal;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_Ungets --
 *
 *	Causes the supplied string to be added to the input queue of
 *	the channel, at either the head or tail of the queue.
 *
 * Results:
 *	The number of bytes stored in the channel, or -1 on error.
 *
 * Side effects:
 *	Adds input to the input queue of a channel.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_Ungets(chan, str, len, atEnd)
    Tcl_Channel chan;		/* The channel for which to add the input. */
    char *str;			/* The input itself. */
    int len;			/* The length of the input. */
    int atEnd;			/* If non-zero, add at end of queue; otherwise
                                 * add at head of queue. */    
{
    Channel *chanPtr;		/* The real IO channel. */
    ChannelBuffer *bufPtr;	/* Buffer to contain the data. */
    int i;

    chanPtr = (Channel *) chan;

    /*
     * Check for unreported error.
     */

    if (chanPtr->unreportedError != 0) {
        Tcl_SetErrno(chanPtr->unreportedError);
        chanPtr->unreportedError = 0;
        return -1;
    }

    /*
     * Punt if the channel is not opened for reading.
     */

    if (!(chanPtr->flags & TCL_READABLE)) {
        Tcl_SetErrno(EACCES);
        return -1;
    }

    /*
     * If the channel is in the middle of a background copy, fail.
     */

    if (chanPtr->csPtr) {
	Tcl_SetErrno(EBUSY);
	return -1;
    }

    /*
     * If we have encountered a sticky EOF, just punt without storing.
     * (sticky EOF is set if we have seen the input eofChar, to prevent
     * reading beyond the eofChar). Otherwise, clear the EOF flags, and
     * clear the BLOCKED bit. We want to discover these conditions anew
     * in each operation.
     */

    if (chanPtr->flags & CHANNEL_STICKY_EOF) {
        return len;
    }
    chanPtr->flags &= (~(CHANNEL_BLOCKED | CHANNEL_EOF));

    bufPtr = (ChannelBuffer *) ckalloc((unsigned)
            (CHANNELBUFFER_HEADER_SIZE + len));
    for (i = 0; i < len; i++) {
        bufPtr->buf[i] = str[i];
    }
    bufPtr->bufSize = len;
    bufPtr->nextAdded = len;
    bufPtr->nextRemoved = 0;

    if (chanPtr->inQueueHead == (ChannelBuffer *) NULL) {
        bufPtr->nextPtr = (ChannelBuffer *) NULL;
        chanPtr->inQueueHead = bufPtr;
        chanPtr->inQueueTail = bufPtr;
    } else if (atEnd) {
        bufPtr->nextPtr = (ChannelBuffer *) NULL;
        chanPtr->inQueueTail->nextPtr = bufPtr;
        chanPtr->inQueueTail = bufPtr;
    } else {
        bufPtr->nextPtr = chanPtr->inQueueHead;
        chanPtr->inQueueHead = bufPtr;
    }

    /*
     * Update the notifier state so we don't block while there is still
     * data in the buffers.
     */

    UpdateInterest(chanPtr);
    return len;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_Seek --
 *
 *	Implements seeking on Tcl Channels. This is a public function
 *	so that other C facilities may be implemented on top of it.
 *
 * Results:
 *	The new access point or -1 on error. If error, use Tcl_GetErrno()
 *	to retrieve the POSIX error code for the error that occurred.
 *
 * Side effects:
 *	May flush output on the channel. May discard queued input.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_Seek(chan, offset, mode)
    Tcl_Channel chan;		/* The channel on which to seek. */
    int offset;			/* Offset to seek to. */
    int mode;			/* Relative to which location to seek? */
{
    Channel *chanPtr;		/* The real IO channel. */
    ChannelBuffer *bufPtr;
    int inputBuffered, outputBuffered;
    int result;			/* Of device driver operations. */
    int curPos;			/* Position on the device. */
    int wasAsync;		/* Was the channel nonblocking before the
                                 * seek operation? If so, must restore to
                                 * nonblocking mode after the seek. */

    chanPtr = (Channel *) chan;

    /*
     * Check for unreported error.
     */

    if (chanPtr->unreportedError != 0) {
        Tcl_SetErrno(chanPtr->unreportedError);
        chanPtr->unreportedError = 0;
        return -1;
    }

    /*
     * Disallow seek on channels that are open for neither writing nor
     * reading (e.g. socket server channels).
     */

    if (!(chanPtr->flags & (TCL_WRITABLE|TCL_READABLE))) {
        Tcl_SetErrno(EACCES);
        return -1;
    }

    /*
     * If the channel is in the middle of a background copy, fail.
     */

    if (chanPtr->csPtr) {
	Tcl_SetErrno(EBUSY);
	return -1;
    }

    /*
     * Disallow seek on dead channels -- channels that have been closed but
     * not yet been deallocated. Such channels can be found if the exit
     * handler for channel cleanup has run but the channel is still
     * registered in an interpreter.
     */

    if (CheckForDeadChannel(NULL,chanPtr)) return -1;

    /*
     * Disallow seek on channels whose type does not have a seek procedure
     * defined. This means that the channel does not support seeking.
     */

    if (chanPtr->typePtr->seekProc == (Tcl_DriverSeekProc *) NULL) {
        Tcl_SetErrno(EINVAL);
        return -1;
    }

    /*
     * Compute how much input and output is buffered. If both input and
     * output is buffered, cannot compute the current position.
     */

    for (bufPtr = chanPtr->inQueueHead, inputBuffered = 0;
             bufPtr != (ChannelBuffer *) NULL;
             bufPtr = bufPtr->nextPtr) {
        inputBuffered += (bufPtr->nextAdded - bufPtr->nextRemoved);
    }
    for (bufPtr = chanPtr->outQueueHead, outputBuffered = 0;
             bufPtr != (ChannelBuffer *) NULL;
             bufPtr = bufPtr->nextPtr) {
        outputBuffered += (bufPtr->nextAdded - bufPtr->nextRemoved);
    }
    if ((chanPtr->curOutPtr != (ChannelBuffer *) NULL) &&
           (chanPtr->curOutPtr->nextAdded > chanPtr->curOutPtr->nextRemoved)) {
        chanPtr->flags |= BUFFER_READY;
        outputBuffered +=
            (chanPtr->curOutPtr->nextAdded - chanPtr->curOutPtr->nextRemoved);
    }

    if ((inputBuffered != 0) && (outputBuffered != 0)) {
        Tcl_SetErrno(EFAULT);
        return -1;
    }

    /*
     * If we are seeking relative to the current position, compute the
     * corrected offset taking into account the amount of unread input.
     */

    if (mode == SEEK_CUR) {
        offset -= inputBuffered;
    }

    /*
     * Discard any queued input - this input should not be read after
     * the seek.
     */

    DiscardInputQueued(chanPtr, 0);

    /*
     * Reset EOF and BLOCKED flags. We invalidate them by moving the
     * access point. Also clear CR related flags.
     */

    chanPtr->flags &=
        (~(CHANNEL_EOF | CHANNEL_STICKY_EOF | CHANNEL_BLOCKED | INPUT_SAW_CR));
    
    /*
     * If the channel is in asynchronous output mode, switch it back
     * to synchronous mode and cancel any async flush that may be
     * scheduled. After the flush, the channel will be put back into
     * asynchronous output mode.
     */

    wasAsync = 0;
    if (chanPtr->flags & CHANNEL_NONBLOCKING) {
        wasAsync = 1;
        result = 0;
        if (chanPtr->typePtr->blockModeProc != NULL) {
            result = (chanPtr->typePtr->blockModeProc) (chanPtr->instanceData,
                    TCL_MODE_BLOCKING);
        }
        if (result != 0) {
            Tcl_SetErrno(result);
            return -1;
        }
        chanPtr->flags &= (~(CHANNEL_NONBLOCKING));
        if (chanPtr->flags & BG_FLUSH_SCHEDULED) {
            chanPtr->flags &= (~(BG_FLUSH_SCHEDULED));
        }
    }
    
    /*
     * If the flush fails we cannot recover the original position. In
     * that case the seek is not attempted because we do not know where
     * the access position is - instead we return the error. FlushChannel
     * has already called Tcl_SetErrno() to report the error upwards.
     * If the flush succeeds we do the seek also.
     */
    
    if (FlushChannel(NULL, chanPtr, 0) != 0) {
        curPos = -1;
    } else {

        /*
         * Now seek to the new position in the channel as requested by the
         * caller.
         */

        curPos = (chanPtr->typePtr->seekProc) (chanPtr->instanceData,
                (long) offset, mode, &result);
        if (curPos == -1) {
            Tcl_SetErrno(result);
        }
    }
    
    /*
     * Restore to nonblocking mode if that was the previous behavior.
     *
     * NOTE: Even if there was an async flush active we do not restore
     * it now because we already flushed all the queued output, above.
     */
    
    if (wasAsync) {
        chanPtr->flags |= CHANNEL_NONBLOCKING;
        result = 0;
        if (chanPtr->typePtr->blockModeProc != NULL) {
            result = (chanPtr->typePtr->blockModeProc) (chanPtr->instanceData,
                    TCL_MODE_NONBLOCKING);
        }
        if (result != 0) {
            Tcl_SetErrno(result);
            return -1;
        }
    }

    return curPos;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_Tell --
 *
 *	Returns the position of the next character to be read/written on
 *	this channel.
 *
 * Results:
 *	A nonnegative integer on success, -1 on failure. If failed,
 *	use Tcl_GetErrno() to retrieve the POSIX error code for the
 *	error that occurred.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_Tell(chan)
    Tcl_Channel chan;			/* The channel to return pos for. */
{
    Channel *chanPtr;			/* The actual channel to tell on. */
    ChannelBuffer *bufPtr;
    int inputBuffered, outputBuffered;
    int result;				/* Of calling device driver. */
    int curPos;				/* Position on device. */

    chanPtr = (Channel *) chan;

    /*
     * Check for unreported error.
     */

    if (chanPtr->unreportedError != 0) {
        Tcl_SetErrno(chanPtr->unreportedError);
        chanPtr->unreportedError = 0;
        return -1;
    }

    /*
     * Disallow tell on dead channels -- channels that have been closed but
     * not yet been deallocated. Such channels can be found if the exit
     * handler for channel cleanup has run but the channel is still
     * registered in an interpreter.
     */

    if (CheckForDeadChannel(NULL,chanPtr)) return -1;

    /*
     * Disallow tell on channels that are open for neither
     * writing nor reading (e.g. socket server channels).
     */

    if (!(chanPtr->flags & (TCL_WRITABLE|TCL_READABLE))) {
        Tcl_SetErrno(EACCES);
        return -1;
    }

    /*
     * If the channel is in the middle of a background copy, fail.
     */

    if (chanPtr->csPtr) {
	Tcl_SetErrno(EBUSY);
	return -1;
    }

    /*
     * Disallow tell on channels whose type does not have a seek procedure
     * defined. This means that the channel does not support seeking.
     */

    if (chanPtr->typePtr->seekProc == (Tcl_DriverSeekProc *) NULL) {
        Tcl_SetErrno(EINVAL);
        return -1;
    }

    /*
     * Compute how much input and output is buffered. If both input and
     * output is buffered, cannot compute the current position.
     */

    for (bufPtr = chanPtr->inQueueHead, inputBuffered = 0;
             bufPtr != (ChannelBuffer *) NULL;
             bufPtr = bufPtr->nextPtr) {
        inputBuffered += (bufPtr->nextAdded - bufPtr->nextRemoved);
    }
    for (bufPtr = chanPtr->outQueueHead, outputBuffered = 0;
             bufPtr != (ChannelBuffer *) NULL;
             bufPtr = bufPtr->nextPtr) {
        outputBuffered += (bufPtr->nextAdded - bufPtr->nextRemoved);
    }
    if ((chanPtr->curOutPtr != (ChannelBuffer *) NULL) &&
           (chanPtr->curOutPtr->nextAdded > chanPtr->curOutPtr->nextRemoved)) {
        chanPtr->flags |= BUFFER_READY;
        outputBuffered +=
            (chanPtr->curOutPtr->nextAdded - chanPtr->curOutPtr->nextRemoved);
    }

    if ((inputBuffered != 0) && (outputBuffered != 0)) {
        Tcl_SetErrno(EFAULT);
        return -1;
    }

    /*
     * Get the current position in the device and compute the position
     * where the next character will be read or written.
     */

    curPos = (chanPtr->typePtr->seekProc) (chanPtr->instanceData,
            (long) 0, SEEK_CUR, &result);
    if (curPos == -1) {
        Tcl_SetErrno(result);
        return -1;
    }
    if (inputBuffered != 0) {
        return (curPos - inputBuffered);
    }
    return (curPos + outputBuffered);
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_Eof --
 *
 *	Returns 1 if the channel is at EOF, 0 otherwise.
 *
 * Results:
 *	1 or 0, always.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_Eof(chan)
    Tcl_Channel chan;			/* Does this channel have EOF? */
{
    Channel *chanPtr;		/* The real channel structure. */

    chanPtr = (Channel *) chan;
    return ((chanPtr->flags & CHANNEL_STICKY_EOF) ||
            ((chanPtr->flags & CHANNEL_EOF) && (Tcl_InputBuffered(chan) == 0)))
        ? 1 : 0;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_InputBlocked --
 *
 *	Returns 1 if input is blocked on this channel, 0 otherwise.
 *
 * Results:
 *	0 or 1, always.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_InputBlocked(chan)
    Tcl_Channel chan;			/* Is this channel blocked? */
{
    Channel *chanPtr;		/* The real channel structure. */

    chanPtr = (Channel *) chan;
    return (chanPtr->flags & CHANNEL_BLOCKED) ? 1 : 0;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_InputBuffered --
 *
 *	Returns the number of bytes of input currently buffered in the
 *	internal buffer of a channel.
 *
 * Results:
 *	The number of input bytes buffered, or zero if the channel is not
 *	open for reading.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_InputBuffered(chan)
    Tcl_Channel chan;			/* The channel to query. */
{
    Channel *chanPtr;
    int bytesBuffered;
    ChannelBuffer *bufPtr;

    chanPtr = (Channel *) chan;
    for (bytesBuffered = 0, bufPtr = chanPtr->inQueueHead;
             bufPtr != (ChannelBuffer *) NULL;
             bufPtr = bufPtr->nextPtr) {
        bytesBuffered += (bufPtr->nextAdded - bufPtr->nextRemoved);
    }
    return bytesBuffered;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_SetChannelBufferSize --
 *
 *	Sets the size of buffers to allocate to store input or output
 *	in the channel. The size must be between 10 bytes and 1 MByte.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Sets the size of buffers subsequently allocated for this channel.
 *
 *----------------------------------------------------------------------
 */

void
Tcl_SetChannelBufferSize(chan, sz)
    Tcl_Channel chan;			/* The channel whose buffer size
                                         * to set. */
    int sz;				/* The size to set. */
{
    Channel *chanPtr;
    
    /*
     * If the buffer size is smaller than 10 bytes or larger than one MByte,
     * do not accept the requested size and leave the current buffer size.
     */
    
    if (sz < 10) {
        return;
    }
    if (sz > (1024 * 1024)) {
        return;
    }

    chanPtr = (Channel *) chan;
    chanPtr->bufSize = sz;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_GetChannelBufferSize --
 *
 *	Retrieves the size of buffers to allocate for this channel.
 *
 * Results:
 *	The size.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_GetChannelBufferSize(chan)
    Tcl_Channel chan;		/* The channel for which to find the
                                 * buffer size. */
{
    Channel *chanPtr;

    chanPtr = (Channel *) chan;
    return chanPtr->bufSize;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_BadChannelOption --
 *
 *	This procedure generates a "bad option" error message in an
 *	(optional) interpreter.  It is used by channel drivers when 
 *      a invalid Set/Get option is requested. Its purpose is to concatenate
 *      the generic options list to the specific ones and factorize
 *      the generic options error message string.
 *
 * Results:
 *	TCL_ERROR.
 *
 * Side effects:
 *	An error message is generated in interp's result object to
 *	indicate that a command was invoked with the a bad option
 *	The message has the form
 *		bad option "blah": should be one of 
 *              <...generic options...>+<...specific options...>
 *	"blah" is the optionName argument and "<specific options>"
 *	is a space separated list of specific option words.
 *      The function takes good care of inserting minus signs before
 *      each option, commas after, and an "or" before the last option.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_BadChannelOption(interp, optionName, optionList)
    Tcl_Interp *interp;			/* Current interpreter. (can be NULL)*/
    char *optionName;			/* 'bad option' name */
    char *optionList;			/* Specific options list to append 
					 * to the standard generic options.
					 * can be NULL for generic options 
					 * only.
					 */
{
    if (interp) {
	CONST char *genericopt = 
	    	"blocking buffering buffersize eofchar translation";
	char **argv;
	int  argc, i;
	Tcl_DString ds;

	Tcl_DStringInit(&ds);
	Tcl_DStringAppend(&ds, (char *) genericopt, -1);
	if (optionList && (*optionList)) {
	    Tcl_DStringAppend(&ds, " ", 1);
	    Tcl_DStringAppend(&ds, optionList, -1);
	}
	if (Tcl_SplitList(interp, Tcl_DStringValue(&ds), 
	      	  &argc, &argv) != TCL_OK) {
	    panic("malformed option list in channel driver");
	}
	Tcl_ResetResult(interp);
	Tcl_AppendResult(interp, "bad option \"", optionName, 
		 "\": should be one of ", (char *) NULL);
	argc--;
	for (i = 0; i < argc; i++) {
	    Tcl_AppendResult(interp, "-", argv[i], ", ", (char *) NULL);
	}
	Tcl_AppendResult(interp, "or -", argv[i], (char *) NULL);
	Tcl_DStringFree(&ds);
	ckfree((char *) argv);
    }
    Tcl_SetErrno(EINVAL);
    return TCL_ERROR;
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_GetChannelOption --
 *
 *	Gets a mode associated with an IO channel. If the optionName arg
 *	is non NULL, retrieves the value of that option. If the optionName
 *	arg is NULL, retrieves a list of alternating option names and
 *	values for the given channel.
 *
 * Results:
 *	A standard Tcl result. Also sets the supplied DString to the
 *	string value of the option(s) returned.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_GetChannelOption(interp, chan, optionName, dsPtr)
    Tcl_Interp *interp;		/* For error reporting - can be NULL. */
    Tcl_Channel chan;		/* Channel on which to get option. */
    char *optionName;		/* Option to get. */
    Tcl_DString *dsPtr;		/* Where to store value(s). */
{
    size_t len;			/* Length of optionName string. */
    char optionVal[128];	/* Buffer for sprintf. */
    Channel *chanPtr = (Channel *) chan;
    int flags;

    /*
     * If we are in the middle of a background copy, use the saved flags.
     */

    if (chanPtr->csPtr) {
	if (chanPtr == chanPtr->csPtr->readPtr) {
	    flags = chanPtr->csPtr->readFlags;
	} else {
	    flags = chanPtr->csPtr->writeFlags;
	}
    } else {
	flags = chanPtr->flags;
    }

    /*
     * Disallow options on dead channels -- channels that have been closed but
     * not yet been deallocated. Such channels can be found if the exit
     * handler for channel cleanup has run but the channel is still
     * registered in an interpreter.
     */

    if (CheckForDeadChannel(interp,chanPtr)) return TCL_ERROR;

    /*
     * If the optionName is NULL it means that we want a list of all
     * options and values.
     */
    
    if (optionName == (char *) NULL) {
        len = 0;
    } else {
        len = strlen(optionName);
    }
    
    if ((len == 0) || ((len > 2) && (optionName[1] == 'b') &&
            (strncmp(optionName, "-blocking", len) == 0))) {
        if (len == 0) {
            Tcl_DStringAppendElement(dsPtr, "-blocking");
        }
        Tcl_DStringAppendElement(dsPtr,
		(flags & CHANNEL_NONBLOCKING) ? "0" : "1");
        if (len > 0) {
            return TCL_OK;
        }
    }
    if ((len == 0) || ((len > 7) && (optionName[1] == 'b') &&
            (strncmp(optionName, "-buffering", len) == 0))) {
        if (len == 0) {
            Tcl_DStringAppendElement(dsPtr, "-buffering");
        }
        if (flags & CHANNEL_LINEBUFFERED) {
            Tcl_DStringAppendElement(dsPtr, "line");
        } else if (flags & CHANNEL_UNBUFFERED) {
            Tcl_DStringAppendElement(dsPtr, "none");
        } else {
            Tcl_DStringAppendElement(dsPtr, "full");
        }
        if (len > 0) {
            return TCL_OK;
        }
    }
    if ((len == 0) || ((len > 7) && (optionName[1] == 'b') &&
            (strncmp(optionName, "-buffersize", len) == 0))) {
        if (len == 0) {
            Tcl_DStringAppendElement(dsPtr, "-buffersize");
        }
        TclFormatInt(optionVal, chanPtr->bufSize);
        Tcl_DStringAppendElement(dsPtr, optionVal);
        if (len > 0) {
            return TCL_OK;
        }
    }
    if ((len == 0) ||
            ((len > 1) && (optionName[1] == 'e') &&
                    (strncmp(optionName, "-eofchar", len) == 0))) {
        if (len == 0) {
            Tcl_DStringAppendElement(dsPtr, "-eofchar");
        }
        if (((flags & (TCL_READABLE|TCL_WRITABLE)) ==
                (TCL_READABLE|TCL_WRITABLE)) && (len == 0)) {
            Tcl_DStringStartSublist(dsPtr);
        }
        if (flags & TCL_READABLE) {
            if (chanPtr->inEofChar == 0) {
                Tcl_DStringAppendElement(dsPtr, "");
            } else {
                char buf[4];

                sprintf(buf, "%c", chanPtr->inEofChar);
                Tcl_DStringAppendElement(dsPtr, buf);
            }
        }
        if (flags & TCL_WRITABLE) {
            if (chanPtr->outEofChar == 0) {
                Tcl_DStringAppendElement(dsPtr, "");
            } else {
                char buf[4];

                sprintf(buf, "%c", chanPtr->outEofChar);
                Tcl_DStringAppendElement(dsPtr, buf);
            }
        }
        if (((flags & (TCL_READABLE|TCL_WRITABLE)) ==
                (TCL_READABLE|TCL_WRITABLE)) && (len == 0)) {
            Tcl_DStringEndSublist(dsPtr);
        }
        if (len > 0) {
            return TCL_OK;
        }
    }
    if ((len == 0) ||
            ((len > 1) && (optionName[1] == 't') &&
                    (strncmp(optionName, "-translation", len) == 0))) {
        if (len == 0) {
            Tcl_DStringAppendElement(dsPtr, "-translation");
        }
        if (((flags & (TCL_READABLE|TCL_WRITABLE)) ==
                (TCL_READABLE|TCL_WRITABLE)) && (len == 0)) {
            Tcl_DStringStartSublist(dsPtr);
        }
        if (flags & TCL_READABLE) {
            if (chanPtr->inputTranslation == TCL_TRANSLATE_AUTO) {
                Tcl_DStringAppendElement(dsPtr, "auto");
            } else if (chanPtr->inputTranslation == TCL_TRANSLATE_CR) {
                Tcl_DStringAppendElement(dsPtr, "cr");
            } else if (chanPtr->inputTranslation == TCL_TRANSLATE_CRLF) {
                Tcl_DStringAppendElement(dsPtr, "crlf");
            } else {
                Tcl_DStringAppendElement(dsPtr, "lf");
            }
        }
        if (flags & TCL_WRITABLE) {
            if (chanPtr->outputTranslation == TCL_TRANSLATE_AUTO) {
                Tcl_DStringAppendElement(dsPtr, "auto");
            } else if (chanPtr->outputTranslation == TCL_TRANSLATE_CR) {
                Tcl_DStringAppendElement(dsPtr, "cr");
            } else if (chanPtr->outputTranslation == TCL_TRANSLATE_CRLF) {
                Tcl_DStringAppendElement(dsPtr, "crlf");
            } else {
                Tcl_DStringAppendElement(dsPtr, "lf");
            }
        }
        if (((flags & (TCL_READABLE|TCL_WRITABLE)) ==
                (TCL_READABLE|TCL_WRITABLE)) && (len == 0)) {
            Tcl_DStringEndSublist(dsPtr);
        }
        if (len > 0) {
            return TCL_OK;
        }
    }
    if (chanPtr->typePtr->getOptionProc != (Tcl_DriverGetOptionProc *) NULL) {
	/*
	 * let the driver specific handle additional options
	 * and result code and message.
	 */

        return (chanPtr->typePtr->getOptionProc) (chanPtr->instanceData,
		  interp, optionName, dsPtr);
    } else {
	/*
	 * no driver specific options case.
	 */

        if (len == 0) {
            return TCL_OK;
        }
	return Tcl_BadChannelOption(interp, optionName, NULL);
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_SetChannelOption --
 *
 *	Sets an option on a channel.
 *
 * Results:
 *	A standard Tcl result. Also sets interp->result on error if
 *	interp is not NULL.
 *
 * Side effects:
 *	May modify an option on a device.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_SetChannelOption(interp, chan, optionName, newValue)
    Tcl_Interp *interp;		/* For error reporting - can be NULL. */
    Tcl_Channel chan;		/* Channel on which to set mode. */
    char *optionName;		/* Which option to set? */
    char *newValue;		/* New value for option. */
{
    int newMode;		/* New (numeric) mode to sert. */
    Channel *chanPtr;		/* The real IO channel. */
    size_t len;			/* Length of optionName string. */
    int argc;
    char **argv;
    
    chanPtr = (Channel *) chan;

    /*
     * If the channel is in the middle of a background copy, fail.
     */

    if (chanPtr->csPtr) {
	if (interp) {
	    Tcl_AppendResult(interp,
	         "unable to set channel options: background copy in progress",
		 (char *) NULL);
	}
        return TCL_ERROR;
    }


    /*
     * Disallow options on dead channels -- channels that have been closed but
     * not yet been deallocated. Such channels can be found if the exit
     * handler for channel cleanup has run but the channel is still
     * registered in an interpreter.
     */

    if (CheckForDeadChannel(NULL,chanPtr)) return TCL_ERROR;
    
    len = strlen(optionName);

    if ((len > 2) && (optionName[1] == 'b') &&
            (strncmp(optionName, "-blocking", len) == 0)) {
        if (Tcl_GetBoolean(interp, newValue, &newMode) == TCL_ERROR) {
            return TCL_ERROR;
        }
        if (newMode) {
            newMode = TCL_MODE_BLOCKING;
        } else {
            newMode = TCL_MODE_NONBLOCKING;
        }
	return SetBlockMode(interp, chanPtr, newMode);
    }

    if ((len > 7) && (optionName[1] == 'b') &&
            (strncmp(optionName, "-buffering", len) == 0)) {
        len = strlen(newValue);
        if ((newValue[0] == 'f') && (strncmp(newValue, "full", len) == 0)) {
            chanPtr->flags &=
                (~(CHANNEL_UNBUFFERED|CHANNEL_LINEBUFFERED));
        } else if ((newValue[0] == 'l') &&
                (strncmp(newValue, "line", len) == 0)) {
            chanPtr->flags &= (~(CHANNEL_UNBUFFERED));
            chanPtr->flags |= CHANNEL_LINEBUFFERED;
        } else if ((newValue[0] == 'n') &&
                (strncmp(newValue, "none", len) == 0)) {
            chanPtr->flags &= (~(CHANNEL_LINEBUFFERED));
            chanPtr->flags |= CHANNEL_UNBUFFERED;
        } else {
            if (interp) {
                Tcl_AppendResult(interp, "bad value for -buffering: ",
                        "must be one of full, line, or none",
                        (char *) NULL);
                return TCL_ERROR;
            }
        }
        return TCL_OK;
    }

    if ((len > 7) && (optionName[1] == 'b') &&
            (strncmp(optionName, "-buffersize", len) == 0)) {
        chanPtr->bufSize = atoi(newValue);
        if ((chanPtr->bufSize < 10) || (chanPtr->bufSize > (1024 * 1024))) {
            chanPtr->bufSize = CHANNELBUFFER_DEFAULT_SIZE;
        }
        return TCL_OK;
    }
    
    if ((len > 1) && (optionName[1] == 'e') &&
            (strncmp(optionName, "-eofchar", len) == 0)) {
        if (Tcl_SplitList(interp, newValue, &argc, &argv) == TCL_ERROR) {
            return TCL_ERROR;
        }
        if (argc == 0) {
            chanPtr->inEofChar = 0;
            chanPtr->outEofChar = 0;
        } else if (argc == 1) {
            if (chanPtr->flags & TCL_WRITABLE) {
                chanPtr->outEofChar = (int) argv[0][0];
            }
            if (chanPtr->flags & TCL_READABLE) {
                chanPtr->inEofChar = (int) argv[0][0];
            }
        } else if (argc != 2) {
            if (interp) {
                Tcl_AppendResult(interp,
                        "bad value for -eofchar: should be a list of one or",
                        " two elements", (char *) NULL);
            }
            ckfree((char *) argv);
            return TCL_ERROR;
        } else {
            if (chanPtr->flags & TCL_READABLE) {
                chanPtr->inEofChar = (int) argv[0][0];
            }
            if (chanPtr->flags & TCL_WRITABLE) {
                chanPtr->outEofChar = (int) argv[1][0];
            }
        }
        if (argv != (char **) NULL) {
            ckfree((char *) argv);
        }
        return TCL_OK;
    }

    if ((len > 1) && (optionName[1] == 't') &&
            (strncmp(optionName, "-translation", len) == 0)) {
	char *readMode, *writeMode;

        if (Tcl_SplitList(interp, newValue, &argc, &argv) == TCL_ERROR) {
            return TCL_ERROR;
        }

        if (argc == 1) {
	    readMode = (chanPtr->flags & TCL_READABLE) ? argv[0] : NULL;
	    writeMode = (chanPtr->flags & TCL_WRITABLE) ? argv[0] : NULL;
	} else if (argc == 2) {
	    readMode = (chanPtr->flags & TCL_READABLE) ? argv[0] : NULL;
	    writeMode = (chanPtr->flags & TCL_WRITABLE) ? argv[1] : NULL;
	} else {
            if (interp) {
                Tcl_AppendResult(interp,
                        "bad value for -translation: must be a one or two",
                        " element list", (char *) NULL);
            }
            ckfree((char *) argv);
            return TCL_ERROR;
	}

	if (readMode) {
	    if (*readMode == '\0') {
		newMode = chanPtr->inputTranslation;
	    } else if (strcmp(readMode, "auto") == 0) {
		newMode = TCL_TRANSLATE_AUTO;
	    } else if (strcmp(readMode, "binary") == 0) {
		chanPtr->inEofChar = 0;
		newMode = TCL_TRANSLATE_LF;
	    } else if (strcmp(readMode, "lf") == 0) {
		newMode = TCL_TRANSLATE_LF;
	    } else if (strcmp(readMode, "cr") == 0) {
		newMode = TCL_TRANSLATE_CR;
	    } else if (strcmp(readMode, "crlf") == 0) {
		newMode = TCL_TRANSLATE_CRLF;
	    } else if (strcmp(readMode, "platform") == 0) {
		newMode = TCL_PLATFORM_TRANSLATION;
	    } else {
		if (interp) {
		    Tcl_AppendResult(interp,
			    "bad value for -translation: ",
			    "must be one of auto, binary, cr, lf, crlf,",
			    " or platform", (char *) NULL);
		}
		ckfree((char *) argv);
		return TCL_ERROR;
	    }

	    /*
	     * Reset the EOL flags since we need to look at any buffered
	     * data to see if the new translation mode allows us to
	     * complete the line.
	     */

	    if (newMode != chanPtr->inputTranslation) {
		chanPtr->inputTranslation = (Tcl_EolTranslation) newMode;
		chanPtr->flags &= ~(INPUT_SAW_CR);
		chanPtr->flags &= ~(CHANNEL_GETS_BLOCKED);
		UpdateInterest(chanPtr);
	    }
	}
	if (writeMode) {
	    if (*writeMode == '\0') {
		/* Do nothing. */
	    } else if (strcmp(writeMode, "auto") == 0) {
		/*
		 * This is a hack to get TCP sockets to produce output
		 * in CRLF mode if they are being set into AUTO mode.
		 * A better solution for achieving this effect will be
		 * coded later.
		 */

		if (strcmp(chanPtr->typePtr->typeName, "tcp") == 0) {
		    chanPtr->outputTranslation = TCL_TRANSLATE_CRLF;
		} else {
		    chanPtr->outputTranslation = TCL_PLATFORM_TRANSLATION;
		}
	    } else if (strcmp(writeMode, "binary") == 0) {
		chanPtr->outEofChar = 0;
		chanPtr->outputTranslation = TCL_TRANSLATE_LF;
	    } else if (strcmp(writeMode, "lf") == 0) {
		chanPtr->outputTranslation = TCL_TRANSLATE_LF;
	    } else if (strcmp(writeMode, "cr") == 0) {
		chanPtr->outputTranslation = TCL_TRANSLATE_CR;
	    } else if (strcmp(writeMode, "crlf") == 0) {
		chanPtr->outputTranslation = TCL_TRANSLATE_CRLF;
	    } else if (strcmp(writeMode, "platform") == 0) {
		chanPtr->outputTranslation = TCL_PLATFORM_TRANSLATION;
	    } else {
		if (interp) {
		    Tcl_AppendResult(interp,
			    "bad value for -translation: ",
			    "must be one of auto, binary, cr, lf, crlf,",
			    " or platform", (char *) NULL);
		}
		ckfree((char *) argv);
		return TCL_ERROR;
	    }
	}
        ckfree((char *) argv);            
        return TCL_OK;
    }

    if (chanPtr->typePtr->setOptionProc != (Tcl_DriverSetOptionProc *) NULL) {
        return (chanPtr->typePtr->setOptionProc) (chanPtr->instanceData,
                interp, optionName, newValue);
    }
    
    return Tcl_BadChannelOption(interp, optionName, (char *) NULL);
}
 
/*
 *----------------------------------------------------------------------
 *
 * CleanupChannelHandlers --
 *
 *	Removes channel handlers that refer to the supplied interpreter,
 *	so that if the actual channel is not closed now, these handlers
 *	will not run on subsequent events on the channel. This would be
 *	erroneous, because the interpreter no longer has a reference to
 *	this channel.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Removes channel handlers.
 *
 *----------------------------------------------------------------------
 */

static void
CleanupChannelHandlers(interp, chanPtr)
    Tcl_Interp *interp;
    Channel *chanPtr;
{
    EventScriptRecord *sPtr, *prevPtr, *nextPtr;

    /*
     * Remove fileevent records on this channel that refer to the
     * given interpreter.
     */
    
    for (sPtr = chanPtr->scriptRecordPtr,
             prevPtr = (EventScriptRecord *) NULL;
             sPtr != (EventScriptRecord *) NULL;
             sPtr = nextPtr) {
        nextPtr = sPtr->nextPtr;
        if (sPtr->interp == interp) {
            if (prevPtr == (EventScriptRecord *) NULL) {
                chanPtr->scriptRecordPtr = nextPtr;
            } else {
                prevPtr->nextPtr = nextPtr;
            }

            Tcl_DeleteChannelHandler((Tcl_Channel) chanPtr,
                    ChannelEventScriptInvoker, (ClientData) sPtr);

	    ckfree(sPtr->script);
            ckfree((char *) sPtr);
        } else {
            prevPtr = sPtr;
        }
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_NotifyChannel --
 *
 *	This procedure is called by a channel driver when a driver
 *	detects an event on a channel.  This procedure is responsible
 *	for actually handling the event by invoking any channel
 *	handler callbacks.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Whatever the channel handler callback procedure does.
 *
 *----------------------------------------------------------------------
 */

void
Tcl_NotifyChannel(channel, mask)
    Tcl_Channel channel;	/* Channel that detected an event. */
    int mask;			/* OR'ed combination of TCL_READABLE,
				 * TCL_WRITABLE, or TCL_EXCEPTION: indicates
				 * which events were detected. */
{
    Channel *chanPtr = (Channel *) channel;
    ChannelHandler *chPtr;
    NextChannelHandler nh;

    /*
     * Preserve the channel struct in case the script closes it.
     */
     
    Tcl_Preserve((ClientData) channel);

    /*
     * If we are flushing in the background, be sure to call FlushChannel
     * for writable events.  Note that we have to discard the writable
     * event so we don't call any write handlers before the flush is
     * complete.
     */

    if ((chanPtr->flags & BG_FLUSH_SCHEDULED) && (mask & TCL_WRITABLE)) {
	FlushChannel(NULL, chanPtr, 1);
	mask &= ~TCL_WRITABLE;
    }

    /*
     * Add this invocation to the list of recursive invocations of
     * ChannelHandlerEventProc.
     */
    
    nh.nextHandlerPtr = (ChannelHandler *) NULL;
    nh.nestedHandlerPtr = nestedHandlerPtr;
    nestedHandlerPtr = &nh;
    
    for (chPtr = chanPtr->chPtr; chPtr != (ChannelHandler *) NULL; ) {

        /*
         * If this channel handler is interested in any of the events that
         * have occurred on the channel, invoke its procedure.
         */
        
        if ((chPtr->mask & mask) != 0) {
            nh.nextHandlerPtr = chPtr->nextPtr;
	    (*(chPtr->proc))(chPtr->clientData, mask);
            chPtr = nh.nextHandlerPtr;
        } else {
            chPtr = chPtr->nextPtr;
	}
    }

    /*
     * Update the notifier interest, since it may have changed after
     * invoking event handlers.
     */

    if (chanPtr->typePtr != NULL) {
	UpdateInterest(chanPtr);
    }

    Tcl_Release((ClientData) channel);

    nestedHandlerPtr = nh.nestedHandlerPtr;
}
 
/*
 *----------------------------------------------------------------------
 *
 * UpdateInterest --
 *
 *	Arrange for the notifier to call us back at appropriate times
 *	based on the current state of the channel.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May schedule a timer or driver handler.
 *
 *----------------------------------------------------------------------
 */

static void
UpdateInterest(chanPtr)
    Channel *chanPtr;		/* Channel to update. */
{
    int mask = chanPtr->interestMask;

    /*
     * If there are flushed buffers waiting to be written, then
     * we need to watch for the channel to become writable.
     */

    if (chanPtr->flags & BG_FLUSH_SCHEDULED) {
	mask |= TCL_WRITABLE;
    }

    /*
     * If there is data in the input queue, and we aren't blocked waiting for
     * an EOL, then we need to schedule a timer so we don't block in the
     * notifier.  Also, cancel the read interest so we don't get duplicate
     * events.
     */

    if (mask & TCL_READABLE) {
	if (!(chanPtr->flags & CHANNEL_GETS_BLOCKED)
		&& (chanPtr->inQueueHead != (ChannelBuffer *) NULL)
		&& (chanPtr->inQueueHead->nextRemoved <
			chanPtr->inQueueHead->nextAdded)) {
	    mask &= ~TCL_READABLE;
	    if (!chanPtr->timer) {
		chanPtr->timer = Tcl_CreateTimerHandler(0, ChannelTimerProc,
			(ClientData) chanPtr);
	    }
	}
    }
    (chanPtr->typePtr->watchProc)(chanPtr->instanceData, mask);
}
 
/*
 *----------------------------------------------------------------------
 *
 * ChannelTimerProc --
 *
 *	Timer handler scheduled by UpdateInterest to monitor the
 *	channel buffers until they are empty.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May invoke channel handlers.
 *
 *----------------------------------------------------------------------
 */

static void
ChannelTimerProc(clientData)
    ClientData clientData;
{
    Channel *chanPtr = (Channel *) clientData;

    if (!(chanPtr->flags & CHANNEL_GETS_BLOCKED)
	    && (chanPtr->interestMask & TCL_READABLE)
	    && (chanPtr->inQueueHead != (ChannelBuffer *) NULL)
	    && (chanPtr->inQueueHead->nextRemoved <
		    chanPtr->inQueueHead->nextAdded)) {
	/*
	 * Restart the timer in case a channel handler reenters the
	 * event loop before UpdateInterest gets called by Tcl_NotifyChannel.
	 */

	chanPtr->timer = Tcl_CreateTimerHandler(0, ChannelTimerProc,
			(ClientData) chanPtr);
	Tcl_NotifyChannel((Tcl_Channel)chanPtr, TCL_READABLE);
 
   } else {
	chanPtr->timer = NULL;
	UpdateInterest(chanPtr);
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_CreateChannelHandler --
 *
 *	Arrange for a given procedure to be invoked whenever the
 *	channel indicated by the chanPtr arg becomes readable or
 *	writable.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	From now on, whenever the I/O channel given by chanPtr becomes
 *	ready in the way indicated by mask, proc will be invoked.
 *	See the manual entry for details on the calling sequence
 *	to proc.  If there is already an event handler for chan, proc
 *	and clientData, then the mask will be updated.
 *
 *----------------------------------------------------------------------
 */

void
Tcl_CreateChannelHandler(chan, mask, proc, clientData)
    Tcl_Channel chan;		/* The channel to create the handler for. */
    int mask;			/* OR'ed combination of TCL_READABLE,
				 * TCL_WRITABLE, and TCL_EXCEPTION:
				 * indicates conditions under which
				 * proc should be called. Use 0 to
                                 * disable a registered handler. */
    Tcl_ChannelProc *proc;	/* Procedure to call for each
				 * selected event. */
    ClientData clientData;	/* Arbitrary data to pass to proc. */
{
    ChannelHandler *chPtr;
    Channel *chanPtr;

    chanPtr = (Channel *) chan;
    
    /*
     * Check whether this channel handler is not already registered. If
     * it is not, create a new record, else reuse existing record (smash
     * current values).
     */

    for (chPtr = chanPtr->chPtr;
             chPtr != (ChannelHandler *) NULL;
             chPtr = chPtr->nextPtr) {
        if ((chPtr->chanPtr == chanPtr) && (chPtr->proc == proc) &&
                (chPtr->clientData == clientData)) {
            break;
        }
    }
    if (chPtr == (ChannelHandler *) NULL) {
        chPtr = (ChannelHandler *) ckalloc((unsigned) sizeof(ChannelHandler));
        chPtr->mask = 0;
        chPtr->proc = proc;
        chPtr->clientData = clientData;
        chPtr->chanPtr = chanPtr;
        chPtr->nextPtr = chanPtr->chPtr;
        chanPtr->chPtr = chPtr;
    }

    /*
     * The remainder of the initialization below is done regardless of
     * whether or not this is a new record or a modification of an old
     * one.
     */

    chPtr->mask = mask;

    /*
     * Recompute the interest mask for the channel - this call may actually
     * be disabling an existing handler.
     */
    
    chanPtr->interestMask = 0;
    for (chPtr = chanPtr->chPtr;
	 chPtr != (ChannelHandler *) NULL;
	 chPtr = chPtr->nextPtr) {
	chanPtr->interestMask |= chPtr->mask;
    }

    UpdateInterest(chanPtr);
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_DeleteChannelHandler --
 *
 *	Cancel a previously arranged callback arrangement for an IO
 *	channel.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	If a callback was previously registered for this chan, proc and
 *	 clientData , it is removed and the callback will no longer be called
 *	when the channel becomes ready for IO.
 *
 *----------------------------------------------------------------------
 */

void
Tcl_DeleteChannelHandler(chan, proc, clientData)
    Tcl_Channel chan;		/* The channel for which to remove the
                                 * callback. */
    Tcl_ChannelProc *proc;	/* The procedure in the callback to delete. */
    ClientData clientData;	/* The client data in the callback
                                 * to delete. */
    
{
    ChannelHandler *chPtr, *prevChPtr;
    Channel *chanPtr;
    NextChannelHandler *nhPtr;

    chanPtr = (Channel *) chan;

    /*
     * Find the entry and the previous one in the list.
     */

    for (prevChPtr = (ChannelHandler *) NULL, chPtr = chanPtr->chPtr;
             chPtr != (ChannelHandler *) NULL;
             chPtr = chPtr->nextPtr) {
        if ((chPtr->chanPtr == chanPtr) && (chPtr->clientData == clientData)
                && (chPtr->proc == proc)) {
            break;
        }
        prevChPtr = chPtr;
    }
    
    /*
     * If not found, return without doing anything.
     */

    if (chPtr == (ChannelHandler *) NULL) {
        return;
    }

    /*
     * If ChannelHandlerEventProc is about to process this handler, tell it to
     * process the next one instead - we are going to delete *this* one.
     */

    for (nhPtr = nestedHandlerPtr;
             nhPtr != (NextChannelHandler *) NULL;
             nhPtr = nhPtr->nestedHandlerPtr) {
        if (nhPtr->nextHandlerPtr == chPtr) {
            nhPtr->nextHandlerPtr = chPtr->nextPtr;
        }
    }

    /*
     * Splice it out of the list of channel handlers.
     */
    
    if (prevChPtr == (ChannelHandler *) NULL) {
        chanPtr->chPtr = chPtr->nextPtr;
    } else {
        prevChPtr->nextPtr = chPtr->nextPtr;
    }
    ckfree((char *) chPtr);

    /*
     * Recompute the interest list for the channel, so that infinite loops
     * will not result if Tcl_DeleteChanelHandler is called inside an event.
     */

    chanPtr->interestMask = 0;
    for (chPtr = chanPtr->chPtr;
             chPtr != (ChannelHandler *) NULL;
             chPtr = chPtr->nextPtr) {
        chanPtr->interestMask |= chPtr->mask;
    }

    UpdateInterest(chanPtr);
}
 
/*
 *----------------------------------------------------------------------
 *
 * DeleteScriptRecord --
 *
 *	Delete a script record for this combination of channel, interp
 *	and mask.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Deletes a script record and cancels a channel event handler.
 *
 *----------------------------------------------------------------------
 */

static void
DeleteScriptRecord(interp, chanPtr, mask)
    Tcl_Interp *interp;		/* Interpreter in which script was to be
                                 * executed. */
    Channel *chanPtr;		/* The channel for which to delete the
                                 * script record (if any). */
    int mask;			/* Events in mask must exactly match mask
                                 * of script to delete. */
{
    EventScriptRecord *esPtr, *prevEsPtr;

    for (esPtr = chanPtr->scriptRecordPtr,
             prevEsPtr = (EventScriptRecord *) NULL;
             esPtr != (EventScriptRecord *) NULL;
             prevEsPtr = esPtr, esPtr = esPtr->nextPtr) {
        if ((esPtr->interp == interp) && (esPtr->mask == mask)) {
            if (esPtr == chanPtr->scriptRecordPtr) {
                chanPtr->scriptRecordPtr = esPtr->nextPtr;
            } else {
                prevEsPtr->nextPtr = esPtr->nextPtr;
            }

            Tcl_DeleteChannelHandler((Tcl_Channel) chanPtr,
                    ChannelEventScriptInvoker, (ClientData) esPtr);
            
	    ckfree(esPtr->script);
            ckfree((char *) esPtr);

            break;
        }
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * CreateScriptRecord --
 *
 *	Creates a record to store a script to be executed when a specific
 *	event fires on a specific channel.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Causes the script to be stored for later execution.
 *
 *----------------------------------------------------------------------
 */

static void
CreateScriptRecord(interp, chanPtr, mask, script)
    Tcl_Interp *interp;			/* Interpreter in which to execute
                                         * the stored script. */
    Channel *chanPtr;			/* Channel for which script is to
                                         * be stored. */
    int mask;				/* Set of events for which script
                                         * will be invoked. */
    char *script;			/* A copy of this script is stored
                                         * in the newly created record. */
{
    EventScriptRecord *esPtr;

    for (esPtr = chanPtr->scriptRecordPtr;
             esPtr != (EventScriptRecord *) NULL;
             esPtr = esPtr->nextPtr) {
        if ((esPtr->interp == interp) && (esPtr->mask == mask)) {
	    ckfree(esPtr->script);
            esPtr->script = (char *) NULL;
            break;
        }
    }
    if (esPtr == (EventScriptRecord *) NULL) {
        esPtr = (EventScriptRecord *) ckalloc((unsigned)
                sizeof(EventScriptRecord));
        Tcl_CreateChannelHandler((Tcl_Channel) chanPtr, mask,
                ChannelEventScriptInvoker, (ClientData) esPtr);
        esPtr->nextPtr = chanPtr->scriptRecordPtr;
        chanPtr->scriptRecordPtr = esPtr;
    }
    esPtr->chanPtr = chanPtr;
    esPtr->interp = interp;
    esPtr->mask = mask;
    esPtr->script = ckalloc((unsigned) (strlen(script) + 1));
    strcpy(esPtr->script, script);
}
 
/*
 *----------------------------------------------------------------------
 *
 * ChannelEventScriptInvoker --
 *
 *	Invokes a script scheduled by "fileevent" for when the channel
 *	becomes ready for IO. This function is invoked by the channel
 *	handler which was created by the Tcl "fileevent" command.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Whatever the script does.
 *
 *----------------------------------------------------------------------
 */

static void
ChannelEventScriptInvoker(clientData, mask)
    ClientData clientData;	/* The script+interp record. */
    int mask;			/* Not used. */
{
    Tcl_Interp *interp;		/* Interpreter in which to eval the script. */
    Channel *chanPtr;		/* The channel for which this handler is
                                 * registered. */
    char *script;		/* Script to eval. */
    EventScriptRecord *esPtr;	/* The event script + interpreter to eval it
                                 * in. */
    int result;			/* Result of call to eval script. */

    esPtr = (EventScriptRecord *) clientData;

    chanPtr = esPtr->chanPtr;
    mask = esPtr->mask;
    interp = esPtr->interp;
    script = esPtr->script;

    /*
     * We must preserve the interpreter so we can report errors on it
     * later.  Note that we do not need to preserve the channel because
     * that is done by Tcl_NotifyChannel before calling channel handlers.
     */
    
    Tcl_Preserve((ClientData) interp);
    result = Tcl_GlobalEval(interp, script);

    /*
     * On error, cause a background error and remove the channel handler
     * and the script record.
     *
     * NOTE: Must delete channel handler before causing the background error
     * because the background error may want to reinstall the handler.
     */
    
    if (result != TCL_OK) {
	if (chanPtr->typePtr != NULL) {
	    DeleteScriptRecord(interp, chanPtr, mask);
	}
        Tcl_BackgroundError(interp);
    }
    Tcl_Release((ClientData) interp);
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tcl_FileEventCmd --
 *
 *	This procedure implements the "fileevent" Tcl command. See the
 *	user documentation for details on what it does. This command is
 *	based on the Tk command "fileevent" which in turn is based on work
 *	contributed by Mark Diekhans.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	May create a channel handler for the specified channel.
 *
 *----------------------------------------------------------------------
 */

	/* ARGSUSED */
int
Tcl_FileEventCmd(clientData, interp, argc, argv)
    ClientData clientData;		/* Not used. */
    Tcl_Interp *interp;			/* Interpreter in which the channel
                                         * for which to create the handler
                                         * is found. */
    int argc;				/* Number of arguments. */
    char **argv;			/* Argument strings. */
{
    Channel *chanPtr;			/* The channel to create
                                         * the handler for. */
    Tcl_Channel chan;			/* The opaque type for the channel. */
    int c;				/* First char of mode argument. */
    int mask;				/* Mask for events of interest. */
    size_t length;			/* Length of mode argument. */

    /*
     * Parse arguments.
     */

    if ((argc != 3) && (argc != 4)) {
	Tcl_AppendResult(interp, "wrong # args: must be \"", argv[0],
		" channelId event ?script?", (char *) NULL);
	return TCL_ERROR;
    }
    c = argv[2][0];
    length = strlen(argv[2]);
    if ((c == 'r') && (strncmp(argv[2], "readable", length) == 0)) {
        mask = TCL_READABLE;
    } else if ((c == 'w') && (strncmp(argv[2], "writable", length) == 0)) {
        mask = TCL_WRITABLE;
    } else {
	Tcl_AppendResult(interp, "bad event name \"", argv[2],
		"\": must be readable or writable", (char *) NULL);
	return TCL_ERROR;
    }
    chan = Tcl_GetChannel(interp, argv[1], NULL);
    if (chan == (Tcl_Channel) NULL) {
        return TCL_ERROR;
    }
    
    chanPtr = (Channel *) chan;
    if ((chanPtr->flags & mask) == 0) {
        Tcl_AppendResult(interp, "channel is not ",
                (mask == TCL_READABLE) ? "readable" : "writable",
                (char *) NULL);
        return TCL_ERROR;
    }
    
    /*
     * If we are supposed to return the script, do so.
     */

    if (argc == 3) {
	EventScriptRecord *esPtr;
	for (esPtr = chanPtr->scriptRecordPtr;
             esPtr != (EventScriptRecord *) NULL;
             esPtr = esPtr->nextPtr) {
	    if ((esPtr->interp == interp) && (esPtr->mask == mask)) {
		Tcl_SetResult(interp, esPtr->script, TCL_STATIC);
		break;
	    }
	}
        return TCL_OK;
    }

    /*
     * If we are supposed to delete a stored script, do so.
     */

    if (argv[3][0] == 0) {
        DeleteScriptRecord(interp, chanPtr, mask);
        return TCL_OK;
    }

    /*
     * Make the script record that will link between the event and the
     * script to invoke. This also creates a channel event handler which
     * will evaluate the script in the supplied interpreter.
     */

    CreateScriptRecord(interp, chanPtr, mask, argv[3]);
    
    return TCL_OK;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TclTestChannelCmd --
 *
 *	Implements the Tcl "testchannel" debugging command and its
 *	subcommands. This is part of the testing environment but must be
 *	in this file instead of tclTest.c because it needs access to the
 *	fields of struct Channel.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

	/* ARGSUSED */
int
TclTestChannelCmd(clientData, interp, argc, argv)
    ClientData clientData;	/* Not used. */
    Tcl_Interp *interp;		/* Interpreter for result. */
    int argc;			/* Count of additional args. */
    char **argv;		/* Additional arg strings. */
{
    char *cmdName;		/* Sub command. */
    Tcl_HashTable *hTblPtr;	/* Hash table of channels. */
    Tcl_HashSearch hSearch;	/* Search variable. */
    Tcl_HashEntry *hPtr;	/* Search variable. */
    Channel *chanPtr;		/* The actual channel. */
    Tcl_Channel chan;		/* The opaque type. */
    size_t len;			/* Length of subcommand string. */
    int IOQueued;		/* How much IO is queued inside channel? */
    ChannelBuffer *bufPtr;	/* For iterating over queued IO. */
    char buf[128];		/* For sprintf. */
    
    if (argc < 2) {
        Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                " subcommand ?additional args..?\"", (char *) NULL);
        return TCL_ERROR;
    }
    cmdName = argv[1];
    len = strlen(cmdName);

    chanPtr = (Channel *) NULL;
    if (argc > 2) {
        chan = Tcl_GetChannel(interp, argv[2], NULL);
        if (chan == (Tcl_Channel) NULL) {
            return TCL_ERROR;
        }
        chanPtr = (Channel *) chan;
    }
    
    if ((cmdName[0] == 'i') && (strncmp(cmdName, "info", len) == 0)) {
        if (argc != 3) {
            Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                    " info channelName\"", (char *) NULL);
            return TCL_ERROR;
        }
        Tcl_AppendElement(interp, argv[2]);
        Tcl_AppendElement(interp, chanPtr->typePtr->typeName);
        if (chanPtr->flags & TCL_READABLE) {
            Tcl_AppendElement(interp, "read");
        } else {
            Tcl_AppendElement(interp, "");
        }
        if (chanPtr->flags & TCL_WRITABLE) {
            Tcl_AppendElement(interp, "write");
        } else {
            Tcl_AppendElement(interp, "");
        }
        if (chanPtr->flags & CHANNEL_NONBLOCKING) {
            Tcl_AppendElement(interp, "nonblocking");
        } else {
            Tcl_AppendElement(interp, "blocking");
        }
        if (chanPtr->flags & CHANNEL_LINEBUFFERED) {
            Tcl_AppendElement(interp, "line");
        } else if (chanPtr->flags & CHANNEL_UNBUFFERED) {
            Tcl_AppendElement(interp, "none");
        } else {
            Tcl_AppendElement(interp, "full");
        }
        if (chanPtr->flags & BG_FLUSH_SCHEDULED) {
            Tcl_AppendElement(interp, "async_flush");
        } else {
            Tcl_AppendElement(interp, "");
        }
        if (chanPtr->flags & CHANNEL_EOF) {
            Tcl_AppendElement(interp, "eof");
        } else {
            Tcl_AppendElement(interp, "");
        }
        if (chanPtr->flags & CHANNEL_BLOCKED) {
            Tcl_AppendElement(interp, "blocked");
        } else {
            Tcl_AppendElement(interp, "unblocked");
        }
        if (chanPtr->inputTranslation == TCL_TRANSLATE_AUTO) {
            Tcl_AppendElement(interp, "auto");
            if (chanPtr->flags & INPUT_SAW_CR) {
                Tcl_AppendElement(interp, "saw_cr");
            } else {
                Tcl_AppendElement(interp, "");
            }
        } else if (chanPtr->inputTranslation == TCL_TRANSLATE_LF) {
            Tcl_AppendElement(interp, "lf");
            Tcl_AppendElement(interp, "");
        } else if (chanPtr->inputTranslation == TCL_TRANSLATE_CR) {
            Tcl_AppendElement(interp, "cr");
            Tcl_AppendElement(interp, "");
        } else if (chanPtr->inputTranslation == TCL_TRANSLATE_CRLF) {
            Tcl_AppendElement(interp, "crlf");
            if (chanPtr->flags & INPUT_SAW_CR) {
                Tcl_AppendElement(interp, "queued_cr");
            } else {
                Tcl_AppendElement(interp, "");
            }
        }
        if (chanPtr->outputTranslation == TCL_TRANSLATE_AUTO) {
            Tcl_AppendElement(interp, "auto");
        } else if (chanPtr->outputTranslation == TCL_TRANSLATE_LF) {
            Tcl_AppendElement(interp, "lf");
        } else if (chanPtr->outputTranslation == TCL_TRANSLATE_CR) {
            Tcl_AppendElement(interp, "cr");
        } else if (chanPtr->outputTranslation == TCL_TRANSLATE_CRLF) {
            Tcl_AppendElement(interp, "crlf");
        }
        for (IOQueued = 0, bufPtr = chanPtr->inQueueHead;
                 bufPtr != (ChannelBuffer *) NULL;
                 bufPtr = bufPtr->nextPtr) {
            IOQueued += bufPtr->nextAdded - bufPtr->nextRemoved;
        }
        TclFormatInt(buf, IOQueued);
        Tcl_AppendElement(interp, buf);
        
        IOQueued = 0;
        if (chanPtr->curOutPtr != (ChannelBuffer *) NULL) {
            IOQueued = chanPtr->curOutPtr->nextAdded -
                chanPtr->curOutPtr->nextRemoved;
        }
        for (bufPtr = chanPtr->outQueueHead;
                 bufPtr != (ChannelBuffer *) NULL;
                 bufPtr = bufPtr->nextPtr) {
            IOQueued += (bufPtr->nextAdded - bufPtr->nextRemoved);
        }
        TclFormatInt(buf, IOQueued);
        Tcl_AppendElement(interp, buf);
        
        TclFormatInt(buf, Tcl_Tell((Tcl_Channel) chanPtr));
        Tcl_AppendElement(interp, buf);

        TclFormatInt(buf, chanPtr->refCount);
        Tcl_AppendElement(interp, buf);

        return TCL_OK;
    }

    if ((cmdName[0] == 'i') &&
            (strncmp(cmdName, "inputbuffered", len) == 0)) {
        if (argc != 3) {
            Tcl_AppendResult(interp, "channel name required",
                    (char *) NULL);
            return TCL_ERROR;
        }
        
        for (IOQueued = 0, bufPtr = chanPtr->inQueueHead;
                 bufPtr != (ChannelBuffer *) NULL;
                 bufPtr = bufPtr->nextPtr) {
            IOQueued += bufPtr->nextAdded - bufPtr->nextRemoved;
        }
        sprintf(buf, "%d", IOQueued);
        Tcl_AppendResult(interp, buf, (char *) NULL);
        return TCL_OK;
    }
        
    if ((cmdName[0] == 'm') && (strncmp(cmdName, "mode", len) == 0)) {
        if (argc != 3) {
            Tcl_AppendResult(interp, "channel name required",
                    (char *) NULL);
            return TCL_ERROR;
        }
        
        if (chanPtr->flags & TCL_READABLE) {
            Tcl_AppendElement(interp, "read");
        } else {
            Tcl_AppendElement(interp, "");
        }
        if (chanPtr->flags & TCL_WRITABLE) {
            Tcl_AppendElement(interp, "write");
        } else {
            Tcl_AppendElement(interp, "");
        }
        return TCL_OK;
    }
    
    if ((cmdName[0] == 'n') && (strncmp(cmdName, "name", len) == 0)) {
        if (argc != 3) {
            Tcl_AppendResult(interp, "channel name required",
                    (char *) NULL);
            return TCL_ERROR;
        }
        Tcl_AppendResult(interp, chanPtr->channelName, (char *) NULL);
        return TCL_OK;
    }
    
    if ((cmdName[0] == 'o') && (strncmp(cmdName, "open", len) == 0)) {
        hTblPtr = (Tcl_HashTable *) Tcl_GetAssocData(interp, "tclIO", NULL);
        if (hTblPtr == (Tcl_HashTable *) NULL) {
            return TCL_OK;
        }
        for (hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch);
                 hPtr != (Tcl_HashEntry *) NULL;
                 hPtr = Tcl_NextHashEntry(&hSearch)) {
            Tcl_AppendElement(interp, Tcl_GetHashKey(hTblPtr, hPtr));
        }
        return TCL_OK;
    }

    if ((cmdName[0] == 'o') &&
            (strncmp(cmdName, "outputbuffered", len) == 0)) {
        if (argc != 3) {
            Tcl_AppendResult(interp, "channel name required",
                    (char *) NULL);
            return TCL_ERROR;
        }
        
        IOQueued = 0;
        if (chanPtr->curOutPtr != (ChannelBuffer *) NULL) {
            IOQueued = chanPtr->curOutPtr->nextAdded -
                chanPtr->curOutPtr->nextRemoved;
        }
        for (bufPtr = chanPtr->outQueueHead;
                 bufPtr != (ChannelBuffer *) NULL;
                 bufPtr = bufPtr->nextPtr) {
            IOQueued += (bufPtr->nextAdded - bufPtr->nextRemoved);
        }
        sprintf(buf, "%d", IOQueued);
        Tcl_AppendResult(interp, buf, (char *) NULL);
        return TCL_OK;
    }
        
    if ((cmdName[0] == 'q') &&
            (strncmp(cmdName, "queuedcr", len) == 0)) {
        if (argc != 3) {
            Tcl_AppendResult(interp, "channel name required",
                    (char *) NULL);
            return TCL_ERROR;
        }
        
        Tcl_AppendResult(interp,
                (chanPtr->flags & INPUT_SAW_CR) ? "1" : "0",
                (char *) NULL);
        return TCL_OK;
    }
    
    if ((cmdName[0] == 'r') && (strncmp(cmdName, "readable", len) == 0)) {
        hTblPtr = (Tcl_HashTable *) Tcl_GetAssocData(interp, "tclIO", NULL);
        if (hTblPtr == (Tcl_HashTable *) NULL) {
            return TCL_OK;
        }
        for (hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch);
                 hPtr != (Tcl_HashEntry *) NULL;
                 hPtr = Tcl_NextHashEntry(&hSearch)) {
            chanPtr = (Channel *) Tcl_GetHashValue(hPtr);
            if (chanPtr->flags & TCL_READABLE) {
                Tcl_AppendElement(interp, Tcl_GetHashKey(hTblPtr, hPtr));
            }
        }
        return TCL_OK;
    }

    if ((cmdName[0] == 'r') && (strncmp(cmdName, "refcount", len) == 0)) {
        if (argc != 3) {
            Tcl_AppendResult(interp, "channel name required",
                    (char *) NULL);
            return TCL_ERROR;
        }
        
        sprintf(buf, "%d", chanPtr->refCount);
        Tcl_AppendResult(interp, buf, (char *) NULL);
        return TCL_OK;
    }
    
    if ((cmdName[0] == 't') && (strncmp(cmdName, "type", len) == 0)) {
        if (argc != 3) {
            Tcl_AppendResult(interp, "channel name required",
                    (char *) NULL);
            return TCL_ERROR;
        }
        Tcl_AppendResult(interp, chanPtr->typePtr->typeName, (char *) NULL);
        return TCL_OK;
    }
    
    if ((cmdName[0] == 'w') && (strncmp(cmdName, "writable", len) == 0)) {
        hTblPtr = (Tcl_HashTable *) Tcl_GetAssocData(interp, "tclIO", NULL);
        if (hTblPtr == (Tcl_HashTable *) NULL) {
            return TCL_OK;
        }
        for (hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch);
                 hPtr != (Tcl_HashEntry *) NULL;
                 hPtr = Tcl_NextHashEntry(&hSearch)) {
            chanPtr = (Channel *) Tcl_GetHashValue(hPtr);
            if (chanPtr->flags & TCL_WRITABLE) {
                Tcl_AppendElement(interp, Tcl_GetHashKey(hTblPtr, hPtr));
            }
        }
        return TCL_OK;
    }

    Tcl_AppendResult(interp, "bad option \"", cmdName, "\": should be ",
            "info, open, readable, or writable",
            (char *) NULL);
    return TCL_ERROR;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TclTestChannelEventCmd --
 *
 *	This procedure implements the "testchannelevent" command. It is
 *	used to test the Tcl channel event mechanism. It is present in
 *	this file instead of tclTest.c because it needs access to the
 *	internal structure of the channel.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	Creates, deletes and returns channel event handlers.
 *
 *----------------------------------------------------------------------
 */

	/* ARGSUSED */
int
TclTestChannelEventCmd(dummy, interp, argc, argv)
    ClientData dummy;			/* Not used. */
    Tcl_Interp *interp;			/* Current interpreter. */
    int argc;				/* Number of arguments. */
    char **argv;			/* Argument strings. */
{
    Channel *chanPtr;
    EventScriptRecord *esPtr, *prevEsPtr, *nextEsPtr;
    char *cmd;
    int index, i, mask, len;

    if ((argc < 3) || (argc > 5)) {
        Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                " channelName cmd ?arg1? ?arg2?\"", (char *) NULL);
        return TCL_ERROR;
    }
    chanPtr = (Channel *) Tcl_GetChannel(interp, argv[1], NULL);
    if (chanPtr == (Channel *) NULL) {
        return TCL_ERROR;
    }
    cmd = argv[2];
    len = strlen(cmd);
    if ((cmd[0] == 'a') && (strncmp(cmd, "add", (unsigned) len) == 0)) {
        if (argc != 5) {
            Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                    " channelName add eventSpec script\"", (char *) NULL);
            return TCL_ERROR;
        }
        if (strcmp(argv[3], "readable") == 0) {
            mask = TCL_READABLE;
        } else if (strcmp(argv[3], "writable") == 0) {
            mask = TCL_WRITABLE;
        } else if (strcmp(argv[3], "none") == 0) {
            mask = 0;
	} else {
            Tcl_AppendResult(interp, "bad event name \"", argv[3],
                    "\": must be readable, writable, or none", (char *) NULL);
            return TCL_ERROR;
        }

        esPtr = (EventScriptRecord *) ckalloc((unsigned)
                sizeof(EventScriptRecord));
        esPtr->nextPtr = chanPtr->scriptRecordPtr;
        chanPtr->scriptRecordPtr = esPtr;
        
        esPtr->chanPtr = chanPtr;
        esPtr->interp = interp;
        esPtr->mask = mask;
        esPtr->script = ckalloc((unsigned) (strlen(argv[4]) + 1));
        strcpy(esPtr->script, argv[4]);

        Tcl_CreateChannelHandler((Tcl_Channel) chanPtr, mask,
                ChannelEventScriptInvoker, (ClientData) esPtr);
        
        return TCL_OK;
    }

    if ((cmd[0] == 'd') && (strncmp(cmd, "delete", (unsigned) len) == 0)) {
        if (argc != 4) {
            Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                    " channelName delete index\"", (char *) NULL);
            return TCL_ERROR;
        }
        if (Tcl_GetInt(interp, argv[3], &index) == TCL_ERROR) {
            return TCL_ERROR;
        }
        if (index < 0) {
            Tcl_AppendResult(interp, "bad event index: ", argv[3],
                    ": must be nonnegative", (char *) NULL);
            return TCL_ERROR;
        }
        for (i = 0, esPtr = chanPtr->scriptRecordPtr;
                 (i < index) && (esPtr != (EventScriptRecord *) NULL);
                 i++, esPtr = esPtr->nextPtr) {
	    /* Empty loop body. */
        }
        if (esPtr == (EventScriptRecord *) NULL) {
            Tcl_AppendResult(interp, "bad event index ", argv[3],
                    ": out of range", (char *) NULL);
            return TCL_ERROR;
        }
        if (esPtr == chanPtr->scriptRecordPtr) {
            chanPtr->scriptRecordPtr = esPtr->nextPtr;
        } else {
            for (prevEsPtr = chanPtr->scriptRecordPtr;
                     (prevEsPtr != (EventScriptRecord *) NULL) &&
                         (prevEsPtr->nextPtr != esPtr);
                     prevEsPtr = prevEsPtr->nextPtr) {
                /* Empty loop body. */
            }
            if (prevEsPtr == (EventScriptRecord *) NULL) {
                panic("TclTestChannelEventCmd: damaged event script list");
            }
            prevEsPtr->nextPtr = esPtr->nextPtr;
        }
        Tcl_DeleteChannelHandler((Tcl_Channel) chanPtr,
                ChannelEventScriptInvoker, (ClientData) esPtr);
	ckfree(esPtr->script);
        ckfree((char *) esPtr);

        return TCL_OK;
    }

    if ((cmd[0] == 'l') && (strncmp(cmd, "list", (unsigned) len) == 0)) {
        if (argc != 3) {
            Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                    " channelName list\"", (char *) NULL);
            return TCL_ERROR;
        }
        for (esPtr = chanPtr->scriptRecordPtr;
                 esPtr != (EventScriptRecord *) NULL;
                 esPtr = esPtr->nextPtr) {
	    char *event;
	    if (esPtr->mask) {
		event = ((esPtr->mask == TCL_READABLE)
			? "readable" : "writable");
	    } else {
		event = "none";
	    }
            Tcl_AppendElement(interp, event);
            Tcl_AppendElement(interp, esPtr->script);
        }
        return TCL_OK;
    }

    if ((cmd[0] == 'r') && (strncmp(cmd, "removeall", (unsigned) len) == 0)) {
        if (argc != 3) {
            Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                    " channelName removeall\"", (char *) NULL);
            return TCL_ERROR;
        }
        for (esPtr = chanPtr->scriptRecordPtr;
                 esPtr != (EventScriptRecord *) NULL;
                 esPtr = nextEsPtr) {
            nextEsPtr = esPtr->nextPtr;
            Tcl_DeleteChannelHandler((Tcl_Channel) chanPtr,
                    ChannelEventScriptInvoker, (ClientData) esPtr);
	    ckfree(esPtr->script);
            ckfree((char *) esPtr);
        }
        chanPtr->scriptRecordPtr = (EventScriptRecord *) NULL;
        return TCL_OK;
    }

    if  ((cmd[0] == 's') && (strncmp(cmd, "set", (unsigned) len) == 0)) {
        if (argc != 5) {
            Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                    " channelName delete index event\"", (char *) NULL);
            return TCL_ERROR;
        }
        if (Tcl_GetInt(interp, argv[3], &index) == TCL_ERROR) {
            return TCL_ERROR;
        }
        if (index < 0) {
            Tcl_AppendResult(interp, "bad event index: ", argv[3],
                    ": must be nonnegative", (char *) NULL);
            return TCL_ERROR;
        }
        for (i = 0, esPtr = chanPtr->scriptRecordPtr;
                 (i < index) && (esPtr != (EventScriptRecord *) NULL);
                 i++, esPtr = esPtr->nextPtr) {
	    /* Empty loop body. */
        }
        if (esPtr == (EventScriptRecord *) NULL) {
            Tcl_AppendResult(interp, "bad event index ", argv[3],
                    ": out of range", (char *) NULL);
            return TCL_ERROR;
        }

        if (strcmp(argv[4], "readable") == 0) {
            mask = TCL_READABLE;
        } else if (strcmp(argv[4], "writable") == 0) {
            mask = TCL_WRITABLE;
        } else if (strcmp(argv[4], "none") == 0) {
            mask = 0;
	} else {
            Tcl_AppendResult(interp, "bad event name \"", argv[4],
                    "\": must be readable, writable, or none", (char *) NULL);
            return TCL_ERROR;
        }
	esPtr->mask = mask;
        Tcl_CreateChannelHandler((Tcl_Channel) chanPtr, mask,
                ChannelEventScriptInvoker, (ClientData) esPtr);
	return TCL_OK;
    }    
    Tcl_AppendResult(interp, "bad command ", cmd, ", must be one of ",
            "add, delete, list, set, or removeall", (char *) NULL);
    return TCL_ERROR;

}
 
/*
 *----------------------------------------------------------------------
 *
 * TclCopyChannel --
 *
 *	This routine copies data from one channel to another, either
 *	synchronously or asynchronously.  If a command script is
 *	supplied, the operation runs in the background.  The script
 *	is invoked when the copy completes.  Otherwise the function
 *	waits until the copy is completed before returning.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	May schedule a background copy operation that causes both
 *	channels to be marked busy.
 *
 *----------------------------------------------------------------------
 */

int
TclCopyChannel(interp, inChan, outChan, toRead, cmdPtr)
    Tcl_Interp *interp;		/* Current interpreter. */
    Tcl_Channel inChan;		/* Channel to read from. */
    Tcl_Channel outChan;	/* Channel to write to. */
    int toRead;			/* Amount of data to copy, or -1 for all. */
    Tcl_Obj *cmdPtr;		/* Pointer to script to execute or NULL. */
{
    Channel *inPtr = (Channel *) inChan;
    Channel *outPtr = (Channel *) outChan;
    int readFlags, writeFlags;
    CopyState *csPtr;
    int nonBlocking = (cmdPtr) ? CHANNEL_NONBLOCKING : 0;

    if (inPtr->csPtr) {
	Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), "channel \"",
		Tcl_GetChannelName(inChan), "\" is busy", NULL);
	return TCL_ERROR;
    }
    if (outPtr->csPtr) {
	Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), "channel \"",
		Tcl_GetChannelName(outChan), "\" is busy", NULL);
	return TCL_ERROR;
    }

    readFlags = inPtr->flags;
    writeFlags = outPtr->flags;

    /*
     * Set up the blocking mode appropriately.  Background copies need
     * non-blocking channels.  Foreground copies need blocking channels.
     * If there is an error, restore the old blocking mode.
     */

    if (nonBlocking != (readFlags & CHANNEL_NONBLOCKING)) {
	if (SetBlockMode(interp, inPtr,
		nonBlocking ? TCL_MODE_NONBLOCKING : TCL_MODE_BLOCKING)
		!= TCL_OK) {
	    return TCL_ERROR;
	}
    }	    
    if (inPtr != outPtr) {
	if (nonBlocking != (writeFlags & CHANNEL_NONBLOCKING)) {
	    if (SetBlockMode(NULL, outPtr,
		    nonBlocking ? TCL_MODE_BLOCKING : TCL_MODE_NONBLOCKING)
		    != TCL_OK) {
		if (nonBlocking != (readFlags & CHANNEL_NONBLOCKING)) {
		    SetBlockMode(NULL, inPtr,
			    (readFlags & CHANNEL_NONBLOCKING)
			    ? TCL_MODE_NONBLOCKING : TCL_MODE_BLOCKING);
		    return TCL_ERROR;
		}
	    }
	}
    }

    /*
     * Make sure the output side is unbuffered.
     */

    outPtr->flags = (outPtr->flags & ~(CHANNEL_LINEBUFFERED))
	| CHANNEL_UNBUFFERED;

    /*
     * Allocate a new CopyState to maintain info about the current copy in
     * progress.  This structure will be deallocated when the copy is
     * completed.
     */

    csPtr = (CopyState*) ckalloc(sizeof(CopyState) + inPtr->bufSize);
    csPtr->bufSize = inPtr->bufSize;
    csPtr->readPtr = inPtr;
    csPtr->writePtr = outPtr;
    csPtr->readFlags = readFlags;
    csPtr->writeFlags = writeFlags;
    csPtr->toRead = toRead;
    csPtr->total = 0;
    csPtr->interp = interp;
    if (cmdPtr) {
	Tcl_IncrRefCount(cmdPtr);
    }
    csPtr->cmdPtr = cmdPtr;
    inPtr->csPtr = csPtr;
    outPtr->csPtr = csPtr;

    /*
     * Start copying data between the channels.
     */

    return CopyData(csPtr, 0);
}
 
/*
 *----------------------------------------------------------------------
 *
 * CopyData --
 *
 *	This function implements the lowest level of the copying
 *	mechanism for TclCopyChannel.
 *
 * Results:
 *	Returns TCL_OK on success, else TCL_ERROR.
 *
 * Side effects:
 *	Moves data between channels, may create channel handlers.
 *
 *----------------------------------------------------------------------
 */

static int
CopyData(csPtr, mask)
    CopyState *csPtr;		/* State of copy operation. */
    int mask;			/* Current channel event flags. */
{
    Tcl_Interp *interp;
    Tcl_Obj *cmdPtr, *errObj = NULL;
    Tcl_Channel inChan, outChan;
    int result = TCL_OK;
    int size;
    int total;

    inChan = (Tcl_Channel)csPtr->readPtr;
    outChan = (Tcl_Channel)csPtr->writePtr;
    interp = csPtr->interp;
    cmdPtr = csPtr->cmdPtr;

    /*
     * Copy the data the slow way, using the translation mechanism.
     */

    while (csPtr->toRead != 0) {

	/*
	 * Check for unreported background errors.
	 */

	if (csPtr->readPtr->unreportedError != 0) {
	    Tcl_SetErrno(csPtr->readPtr->unreportedError);
	    csPtr->readPtr->unreportedError = 0;
	    goto readError;
	}
	if (csPtr->writePtr->unreportedError != 0) {
	    Tcl_SetErrno(csPtr->writePtr->unreportedError);
	    csPtr->writePtr->unreportedError = 0;
	    goto writeError;
	}
	
	/*
	 * Read up to bufSize bytes.
	 */

	if ((csPtr->toRead == -1)
		|| (csPtr->toRead > csPtr->bufSize)) {
	    size = csPtr->bufSize;
	} else {
	    size = csPtr->toRead;
	}
	size = DoRead(csPtr->readPtr, csPtr->buffer, size);

	if (size < 0) {
	    readError:
	    errObj = Tcl_NewObj();
	    Tcl_AppendStringsToObj(errObj, "error reading \"",
		    Tcl_GetChannelName(inChan), "\": ",
		    Tcl_PosixError(interp), (char *) NULL);
	    break;
	} else if (size == 0) {
	    /*
	     * We had an underflow on the read side.  If we are at EOF,
	     * then the copying is done, otherwise set up a channel
	     * handler to detect when the channel becomes readable again.
	     */
	    
	    if (Tcl_Eof(inChan)) {
		break;
	    } else if (!(mask & TCL_READABLE)) {
		if (mask & TCL_WRITABLE) {
		    Tcl_DeleteChannelHandler(outChan, CopyEventProc,
			    (ClientData) csPtr);
		}
		Tcl_CreateChannelHandler(inChan, TCL_READABLE,
			CopyEventProc, (ClientData) csPtr);
	    }
	    return TCL_OK;
	}

	/*
	 * Now write the buffer out.
	 */

	size = DoWrite(csPtr->writePtr, csPtr->buffer, size);
	if (size < 0) {
	    writeError:
	    errObj = Tcl_NewObj();
	    Tcl_AppendStringsToObj(errObj, "error writing \"",
		    Tcl_GetChannelName(outChan), "\": ",
		    Tcl_PosixError(interp), (char *) NULL);
	    break;
	}

	/*
	 * Check to see if the write is happening in the background.  If so,
	 * stop copying and wait for the channel to become writable again.
	 */

	if (csPtr->writePtr->flags & BG_FLUSH_SCHEDULED) {
	    if (!(mask & TCL_WRITABLE)) {
		if (mask & TCL_READABLE) {
		    Tcl_DeleteChannelHandler(outChan, CopyEventProc,
			    (ClientData) csPtr);
		}
		Tcl_CreateChannelHandler(outChan, TCL_WRITABLE,
			CopyEventProc, (ClientData) csPtr);
	    }
	    return TCL_OK;
	}

	/*
	 * Update the current byte count if we care.
	 */

	if (csPtr->toRead != -1) {
	    csPtr->toRead -= size;
	}
	csPtr->total += size;

	/*
	 * For background copies, we only do one buffer per invocation so
	 * we don't starve the rest of the system.
	 */

	if (cmdPtr) {
	    /*
	     * The first time we enter this code, there won't be a
	     * channel handler established yet, so do it here.
	     */

	    if (mask == 0) {
		Tcl_CreateChannelHandler(outChan, TCL_WRITABLE,
			CopyEventProc, (ClientData) csPtr);
	    }
	    return TCL_OK;
	}
    }

    /*
     * Make the callback or return the number of bytes transferred.
     * The local total is used because StopCopy frees csPtr.
     */

    total = csPtr->total;
    if (cmdPtr) {
	/*
	 * Get a private copy of the command so we can mutate it
	 * by adding arguments.  Note that StopCopy frees our saved
	 * reference to the original command obj.
	 */

	cmdPtr = Tcl_DuplicateObj(cmdPtr);
	Tcl_IncrRefCount(cmdPtr);
	StopCopy(csPtr);
	Tcl_Preserve((ClientData) interp);

	Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewIntObj(total));
	if (errObj) {
	    Tcl_ListObjAppendElement(interp, cmdPtr, errObj);
	}
	if (Tcl_GlobalEvalObj(interp, cmdPtr) != TCL_OK) {
	    Tcl_BackgroundError(interp);
	    result = TCL_ERROR;
	}
	Tcl_DecrRefCount(cmdPtr);
	Tcl_Release((ClientData) interp);
    } else {
	StopCopy(csPtr);
	if (errObj) {
	    Tcl_SetObjResult(interp, errObj);
	    result = TCL_ERROR;
	} else {
	    Tcl_ResetResult(interp);
	    Tcl_SetIntObj(Tcl_GetObjResult(interp), total);
	}
    }
    return result;
}
 
/*
 *----------------------------------------------------------------------
 *
 * CopyEventProc --
 *
 *	This routine is invoked as a channel event handler for
 *	the background copy operation.  It is just a trivial wrapper
 *	around the CopyData routine.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
CopyEventProc(clientData, mask)
    ClientData clientData;
    int mask;
{
    (void) CopyData((CopyState *)clientData, mask);
}
 
/*
 *----------------------------------------------------------------------
 *
 * StopCopy --
 *
 *	This routine halts a copy that is in progress.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Removes any pending channel handlers and restores the blocking
 *	and buffering modes of the channels.  The CopyState is freed.
 *
 *----------------------------------------------------------------------
 */

static void
StopCopy(csPtr)
    CopyState *csPtr;		/* State for bg copy to stop . */
{
    int nonBlocking;

    if (!csPtr) {
	return;
    }

    /*
     * Restore the old blocking mode and output buffering mode.
     */

    nonBlocking = (csPtr->readFlags & CHANNEL_NONBLOCKING);
    if (nonBlocking != (csPtr->readPtr->flags & CHANNEL_NONBLOCKING)) {
	SetBlockMode(NULL, csPtr->readPtr,
		nonBlocking ? TCL_MODE_NONBLOCKING : TCL_MODE_BLOCKING);
    }
    if (csPtr->writePtr != csPtr->writePtr) {
	if (nonBlocking != (csPtr->writePtr->flags & CHANNEL_NONBLOCKING)) {
	    SetBlockMode(NULL, csPtr->writePtr,
		    nonBlocking ? TCL_MODE_NONBLOCKING : TCL_MODE_BLOCKING);
	}
    }
    csPtr->writePtr->flags &= ~(CHANNEL_LINEBUFFERED | CHANNEL_UNBUFFERED);
    csPtr->writePtr->flags |=
	csPtr->writeFlags & (CHANNEL_LINEBUFFERED | CHANNEL_UNBUFFERED);
	    

    if (csPtr->cmdPtr) {
	Tcl_DeleteChannelHandler((Tcl_Channel)csPtr->readPtr, CopyEventProc,
	    (ClientData)csPtr);
	if (csPtr->readPtr != csPtr->writePtr) {
	    Tcl_DeleteChannelHandler((Tcl_Channel)csPtr->writePtr,
		    CopyEventProc, (ClientData)csPtr);
	}
        Tcl_DecrRefCount(csPtr->cmdPtr);
    }
    csPtr->readPtr->csPtr = NULL;
    csPtr->writePtr->csPtr = NULL;
    ckfree((char*) csPtr);
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<