File: eustags.c

package info (click to toggle)
euslisp 9.31%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 55,448 kB
  • sloc: ansic: 41,610; lisp: 3,339; makefile: 286; sh: 238; asm: 138; python: 53
file content (1751 lines) | stat: -rw-r--r-- 37,902 bytes parent folder | download
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
/* Tags file maker to go with GNUmacs
   Copyright (C) 1984, 1987, 1988 Free Software Foundation, Inc. and Ken Arnold

			   NO WARRANTY

  BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.

 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.

		GENERAL PUBLIC LICENSE TO COPY

  1. You may copy and distribute verbatim copies of this source file
as you receive it, in any medium, provided that you conspicuously
and appropriately publish on each copy a valid copyright notice
"Copyright (C) 1986 Free Software Foundation"; and include
following the copyright notice a verbatim copy of the above disclaimer
of warranty and of this License.

  2. You may modify your copy or copies of this source file or
any portion of it, and copy and distribute such modifications under
the terms of Paragraph 1 above, provided that you also do the following:

    a) cause the modified files to carry prominent notices stating
    that you changed the files and the date of any change; and

    b) cause the whole of any work that you distribute or publish,
    that in whole or in part contains or is a derivative of this
    program or any part thereof, to be licensed at no charge to all
    third parties on terms identical to those contained in this
    License Agreement (except that you may choose to grant more extensive
    warranty protection to some or all third parties, at your option).

    c) You may charge a distribution fee for the physical act of
    transferring a copy, and you may at your option offer warranty
    protection in exchange for a fee.

Mere aggregation of another unrelated program with this program (or its
derivative) on a volume of a storage or distribution medium does not bring
the other program under the scope of these terms.

  3. You may copy and distribute this program (or a portion or derivative
of it, under Paragraph 2) in object code or executable form under the terms
of Paragraphs 1 and 2 above provided that you also do one of the following:

    a) accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of
    Paragraphs 1 and 2 above; or,

    b) accompany it with a written offer, valid for at least three
    years, to give any third party free (except for a nominal
    shipping charge) a complete machine-readable copy of the
    corresponding source code, to be distributed under the terms of
    Paragraphs 1 and 2 above; or,

    c) accompany it with the information you received as to where the
    corresponding source code may be obtained.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form alone.)

For an executable file, complete source code means all the source code for
all modules it contains; but, as a special exception, it need not include
source code for modules which are standard libraries that accompany the
operating system on which the executable file runs.

  4. You may not copy, sublicense, distribute or transfer this program
except as expressly provided under this License Agreement.  Any attempt
otherwise to copy, sublicense, distribute or transfer this program is void and
your rights to use the program under this License agreement shall be
automatically terminated.  However, parties who have received computer
software programs from you with this License Agreement will not have
their licenses terminated so long as such parties remain in full compliance.

In other words, you are welcome to use, share and improve this program.
You are forbidden to forbid anyone else to use, share and improve
what you give them.   Help stamp out software-hoarding!  */

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

/* Define the symbol ETAGS to make the program "etags",
 which makes emacs-style tag tables by default.
 Define CTAGS to make the program "ctags" compatible with the usual one.
 Define neither one to get behavior that depends
 on the name with which the program is invoked
 (but we don't normally compile it that way).  */

/* On VMS, CTAGS is not useful, so always do ETAGS.  */
#ifdef VMS
#ifndef ETAGS
#define ETAGS
#endif
#endif

/* Exit codes for success and failure.  */

#ifdef VMS
#define	GOOD	(1)
#define BAD	(0)
#else
#define	GOOD	(0)
#define	BAD	(1)
#endif

#define	reg	register
#define	logical	char

#define	TRUE	(1)
#define	FALSE	(0)

#define	iswhite(arg)	(_wht[arg])	/* T if char is white		*/
#define	begtoken(arg)	(_btk[arg])	/* T if char can start token	*/
#define	intoken(arg)	(_itk[arg])	/* T if char can be in token	*/
#define	endtoken(arg)	(_etk[arg])	/* T if char ends tokens	*/
#define	isgood(arg)	(_gd[arg])	/* T if char can be after ')'	*/

#define	max(I1,I2)	(I1 > I2 ? I1 : I2)

/* cause token checking for typedef, struct, union, enum to distinguish
   keywords from identifier-prefixes (e.g. struct vs struct_tag).  */
#define istoken(s, tok, len) (!strncmp(s,tok,len) && endtoken(*((s)+(len))))

struct	nd_st {			/* sorting structure			*/
	char	*name;			/* function or type name	*/
	char	*file;			/* file name			*/
	logical f;			/* use pattern or line no	*/
	int	lno;			/* line number tag is on	*/
	long    cno;			/* character number line starts on */
	char	*pat;			/* search pattern		*/
	logical	been_warned;		/* set if noticed dup		*/
	struct	nd_st	*left,*right;	/* left and right sons		*/
};

long	ftell();
typedef	struct	nd_st	NODE;

int number; /* tokens found so far on line starting with # (including #) */
logical gotone,				/* found a func already on line	*/
					/* boolean "func" (see init)	*/
	_wht[0177],_etk[0177],_itk[0177],_btk[0177],_gd[0177];

	/* typedefs are recognized using a simple finite automata,
	 * tydef is its state variable.
	 */
typedef enum {none, begin, tag_ok, middle, end } TYST;

TYST tydef = none;

char	searchar = '/';			/* use /.../ searches 		*/

int	lineno;			/* line number of current line */
long	charno;			/* current character number */
long	linecharno;		/* character number of start of line */

char    *curfile,		/* current input file name		*/
	*outfile= 0,		/* output file				*/
	*white	= " \f\t\n",	/* white chars				*/
	*endtk	= " \t\n\"'#()[]{}=-+%*/&|^~!<>;,.:?",
				/* token ending chars			*/
	*begtk	= "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$",
				/* token starting chars			*/
	*intk	= "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$0123456789",
				/* valid in-token chars			*/
	*notgd	= ",;";		/* non-valid after-function chars	*/

int	file_num = 0;		/* current file number			*/
int	aflag = 0;		/* -a: append to tags */
int	tflag = 0;		/* -t: create tags for typedefs */
int	uflag = 0;		/* -u: update tags */
int	wflag = 0;		/* -w: suppress warnings */
int	vflag = 0;		/* -v: create vgrind style index output */
int	xflag = 0;		/* -x: create cxref style output */
int	eflag = 0;		/* -e: emacs style output */

/* Name this program was invoked with.  */
char *progname;

FILE	*inf,			/* ioptr for current input file		*/
	*outf;			/* ioptr for tags file			*/

NODE	*head;			/* the head of the sorted binary tree	*/

void init ();
void find_entries (char *file);
void free_tree (NODE *node);
void put_entries (NODE *node);

char *savestr();
char *savenstr ();
char *_rindex();
char *_index();
char *concat ();
void initbuffer ();
long readline ();

int total_size_of_entries ();
int PF_funcs ();
int xmalloc ();
int consider_token ();
int tail ();
int TEX_Token ();
int xrealloc ();

/* A `struct linebuffer' is a structure which holds a line of text.
 `readline' reads a line from a stream into a linebuffer
 and works regardless of the length of the line.  */

struct linebuffer
  {
    long size;
    char *buffer;
  };

struct linebuffer lb, lb1;

#if 0  /* VMS now provides the `system' function.  */
#ifdef VMS

#include <descrip.h>

void
system (buf)
     char *buf;
{
  struct dsc$descriptor_s command =
    {
      strlen(buf), DSC$K_DTYPE_T, DSC$K_CLASS_S, buf
    };

  LIB$SPAWN(&command);
}
#endif /* VMS */
#endif /* 0 */

int main(ac,av)
     int	ac;
     char	*av[];
{
  char cmd[100];
  int i;
  int fflag = 0;
  char *this_file;
#ifdef VMS
  char got_err;

  extern char *gfnames();
  extern char *massage_name();
#endif

  progname = av[0];

#ifdef ETAGS
  eflag = 1;
#else
#ifdef CTAGS
  eflag = 0;
#else
  {
    char *subname = _rindex (progname, '/');
    if (subname++ == NULL)
      subname = progname;
    eflag = ! strcmp(subname, "ctags");
  }
#endif
#endif

  while (ac > 1 && av[1][0] == '-')
    {
      for (i=1; av[1][i]; i++)
	{
	  switch(av[1][i])
	    {
#ifndef VMS  /* These options are useful only with ctags,
		and VMS can't input them, so just omit them.  */
	    case 'B':
	      searchar='?';
	      eflag = 0;
	      break;
	    case 'F':
	      searchar='/';
	      eflag = 0;
	      break;
#endif
	    case 'a':
	      aflag++;
	      break;
	    case 'e':
	      eflag++;
	      break;
	    case 'f':
	      if (fflag > 0)
		{
		  fprintf(stderr,
			  "%s: -f flag may only be given once\n", progname);
		  goto usage;
		}
	      fflag++, ac--; av++;
	      if (ac <= 1 || av[1][0] == '\0')
		{
		  fprintf(stderr,
			  "%s: -f flag must be followed by a filename\n",
			  progname);
		  goto usage;
		}
	      outfile = av[1];
	      goto end_loop;
	    case 't':
	      tflag++;
	      break;
#ifndef VMS
	    case 'u':
	      uflag++;
	      eflag = 0;
	      break;
#endif
	    case 'w':
	      wflag++;
	      break;
	    case 'v':
	      vflag++;
	      xflag++;
	      eflag = 0;
	      break;
	    case 'x':
	      xflag++;
	      eflag = 0;
	      break;
	    default:
	      goto usage;
	    }
	}
    end_loop: ;
      ac--; av++;
    }

  if (ac <= 1)
    {
    usage:
#ifdef VMS
      fprintf (stderr, "Usage: %s [-aetwvx] [-f outfile] file ...\n", progname);
#else
      fprintf (stderr, "Usage: %s [-BFaetuwvx] [-f outfile] file ...\n", progname);
#endif
      exit(BAD);
    }

  if (outfile == 0)
    {
      outfile = eflag ? "TAGS" : "tags";
    }

  init();			/* set up boolean "functions"		*/

  initbuffer (&lb);
  initbuffer (&lb1);
  /*
   * loop through files finding functions
   */
  if (eflag)
    {
      outf = fopen (outfile, aflag ? "a" : "w");
      if (!outf)
	{
	  fprintf (stderr, "%s: ", progname);
	  perror (outfile);
	  exit (BAD);
	}
    }

  file_num = 1;
#ifdef VMS
  for (ac--, av++;
       (this_file = gfnames (&ac, &av, &got_err)) != NULL; file_num++)
    {
      if (got_err)
	{
	  error("Can't find file %s\n", this_file);
	  ac--, av++;
	}
      else
	{
	  this_file = massage_name (this_file);
#else     
  for (; file_num < ac; file_num++)
    {
      this_file = av[file_num];
      if (1)
	{
#endif
	  find_entries (this_file);
	  if (eflag)
	    {
	      fprintf (outf, "\f\n%s,%d\n",
		       this_file, total_size_of_entries (head));
	      put_entries (head);
	      free_tree (head);
	      head = NULL;
	    }
	}
    }

  if (eflag)
    {
      fclose (outf);
      exit (GOOD);
    }

  if (xflag)
    {
      put_entries(head);
      exit(GOOD);
    }
  if (uflag)
    {
      for (i=1; i<ac; i++)
	{
	  sprintf(cmd,
		  "mv %s OTAGS;fgrep -v '\t%s\t' OTAGS >%s;rm OTAGS",
		  outfile, av[i], outfile);
	  system(cmd);
	}
      aflag++;
    }
  outf = fopen(outfile, aflag ? "a" : "w");
  if (outf == NULL)
    {
      fprintf (stderr, "%s: ", outfile);
      perror(outfile);
      exit(BAD);
    }
  put_entries(head);
  fclose(outf);
#ifndef VMS
  if (uflag)
    {
      sprintf(cmd, "sort %s -o %s", outfile, outfile);
      system(cmd);
    }
#endif
  exit(GOOD);
}

/*
 * This routine sets up the boolean psuedo-functions which work
 * by seting boolean flags dependent upon the corresponding character
 * Every char which is NOT in that string is not a white char.  Therefore,
 * all of the array "_wht" is set to FALSE, and then the elements
 * subscripted by the chars in "white" are set to TRUE.  Thus "_wht"
 * of a char is TRUE if it is the string "white", else FALSE.
 */
void
init()
{

  reg char *sp;
  reg int i;

  for (i = 0; i < 0177; i++)
    {
      _wht[i] = _etk[i] = _itk[i] = _btk[i] = FALSE;
      _gd[i] = TRUE;
    }
  for (sp = white; *sp; sp++)
    _wht[*sp] = TRUE;
  for (sp = endtk; *sp; sp++)
    _etk[*sp] = TRUE;
  for (sp = intk; *sp; sp++)
    _itk[*sp] = TRUE;
  for (sp = begtk; *sp; sp++)
    _btk[*sp] = TRUE;
  for (sp = notgd; *sp; sp++)
    _gd[*sp] = FALSE;
  _wht[0] = _wht['\n'];
  _etk[0] = _etk['\n'];
  _btk[0] = _btk['\n'];
  _itk[0] = _itk['\n'];
  _gd[0] = _gd['\n'];
}

/*
 * This routine opens the specified file and calls the function
 * which finds the function and type definitions.
 */
void TEX_funcs (FILE *fi);
void Scheme_funcs (FILE *fi);
void L_funcs (FILE *fi);
void C_entries ();
void
find_entries (file)
     char *file;
{
  char *cp;

  if ((inf=fopen(file,"r")) == NULL)
    {
      fprintf (stderr, "%s: ", progname);
      perror(file);
      return;
    }
  curfile = savestr(file);
  cp = _rindex(file, '.');
  /* .tex, .aux or .bbl implies LaTeX source code */
  if (cp && (!strcmp (cp + 1, "tex") || !strcmp (cp + 1, "aux")
	     || !strcmp (cp + 1, "bbl")))
    {
      TEX_funcs(inf);
      fclose(inf);
      return;
    }
  /* .l or .el or .lisp (or .cl or .clisp or ...) implies lisp source code */
  if (cp && (!strcmp (cp + 1, "l") ||
	     !strcmp (cp + 1, "el") ||
	     !strcmp (cp + 1, "lsp") ||
	     !strcmp (cp + 1, "lisp") ||
	     !strcmp (cp + 1, "cl") ||
	     !strcmp (cp + 1, "clisp")))
    {
      L_funcs(inf);
      fclose(inf);
      return;
    }
  /* .scm or .sm or .scheme implies scheme source code */
  if (cp && (!strcmp (cp + 1, "sm")
	     || !strcmp (cp + 1, "scm")
	     || !strcmp (cp + 1, "scheme")
	     || !strcmp (cp + 1, "t")
	     || !strcmp (cp + 1, "sch")
	     || !strcmp (cp + 1, "SM")
	     || !strcmp (cp + 1, "SCM")
             /* The `SCM' or `scm' prefix with a version number */
             || (cp[-1] == 'm' && cp[-2] == 'c' && cp[-3] == 's')
             || (cp[-1] == 'M' && cp[-2] == 'C' && cp[-3] == 'S')))
    {
      Scheme_funcs(inf);
      fclose(inf);
      return;
    }
  /* if not a .c or .h or .y file, try fortran */
  if (cp && (cp[1] != 'c' && cp[1] != 'h' && cp[1] != 'y')
      && cp[2] == '\0')
    {
      if (PF_funcs(inf) != 0)
	{
	  fclose(inf);
	  return;
	}
      rewind(inf);	/* no fortran tags found, try C */
    }
  C_entries();
  fclose(inf);
}

/* Record a tag on the current line.
  name is the tag name,
  f is nonzero to use a pattern, zero to use line number instead. */

void put_entries (NODE *node);
void add_node (NODE *node, NODE *cur_node);
void
pfnote (name, f, linestart, linelen, lno, cno)
     char *name;
     logical f;			/* f == TRUE when function */
     char *linestart;
     int linelen;
     int lno;
     long cno;
{
  register char *fp;
  register NODE *np;
  char *altname;
  char tem[51];

  if ((np = (NODE *) malloc (sizeof (NODE))) == NULL)
    {
      fprintf(stderr, "%s: too many entries to sort\n", progname);
      put_entries(head);
      free_tree(head);
      head = NULL;
      np = (NODE *) xmalloc(sizeof (NODE));
    }
  /* Change name "main" to M<thisfilename>. */
  if (!eflag && !xflag && !strcmp(name, "main"))
    {
      fp = _rindex(curfile, '/');
      if (fp == 0)
	fp = curfile;
      else
	fp++;
      altname = concat ("M", fp, "");
      fp = _rindex(altname, '.');
      if (fp && fp[2] == 0)
	*fp = 0;
      name = altname;
    }
  np->name = savestr(name);
  np->file = curfile;
  np->f = f;
  np->lno = lno;
  np->cno = cno;
  np->left = np->right = 0;
  if (eflag)
    {
      linestart[linelen] = 0;
    }
  else if (xflag == 0)
    {
      sprintf (tem, strlen (linestart) < 50 ? "%s$" : "%.50s", linestart);
      linestart = tem;
    }
  np->pat = savestr (linestart);
  if (head == NULL)
    head = np;
  else
    add_node(np, head);
}

void
free_tree(node)
     NODE *node;
{
  while (node)
    {
      free_tree(node->right);
      free(node);
      node = node->left;
    }
}

void
add_node(node, cur_node)
     NODE *node,*cur_node;
{
  register int dif;

  dif = strcmp(node->name, cur_node->name);

  /* If this tag name matches an existing one, then
     unless -e was given, do not add the node, but maybe print a warning */
  if (!eflag && !dif)
    {
      if (node->file == cur_node->file)
	{
	  if (!wflag)
	    {
	      fprintf(stderr,"%s: Duplicate entry in file %s, line %d: %s\n",
		      progname, node->file,lineno,node->name);
	      fprintf(stderr,"Second entry ignored\n");
	    }
	  return;
	}
      if (!cur_node->been_warned)
	if (!wflag)
	  fprintf(stderr,"%s: Duplicate entry in files %s and %s: %s (Warning only)\n",
		  progname, node->file, cur_node->file, node->name);
      cur_node->been_warned = TRUE;
      return;
    } 

  /* Actually add the node */
  if (dif < 0) 
    {
      if (cur_node->left != NULL)
	add_node(node,cur_node->left);
      else
	cur_node->left = node;
      return;
    }
  if (cur_node->right != NULL)
    add_node(node,cur_node->right);
  else
    cur_node->right = node;
}

void
put_entries(node)
     reg NODE *node;
{
  reg char *sp;

  if (node == NULL)
    return;

  /* Output subentries that precede this one */
  put_entries (node->left);

  /* Output this entry */

  if (eflag)
    {
      fprintf (outf, "%s%c%d,%d\n",
	       node->pat, 0177, node->lno, node->cno);
    }
  else if (!xflag)
    {
      fprintf (outf, "%s\t%s\t",
	       node->name, node->file);

      if (node->f)
	{		/* a function */
	  putc (searchar, outf);
	  putc ('^', outf);

	  for (sp = node->pat; *sp; sp++)
	    {
	      if (*sp == '\\' || *sp == searchar)
		putc ('\\', outf);
	      putc (*sp, outf);
	    }
	  putc (searchar, outf);
	}
      else
	{		/* a typedef; text pattern inadequate */
	  fprintf (outf, "%d", node->lno);
	}
      putc ('\n', outf);
    }
  else if (vflag)
    fprintf (stdout, "%s %s %d\n",
	     node->name, node->file, (node->lno+63)/64);
  else
    fprintf (stdout, "%-16s%4d %-16s %s\n",
	     node->name, node->lno, node->file, node->pat);

  /* Output subentries that follow this one */
  put_entries (node->right);
}

/* Return total number of characters that put_entries will output for
 the nodes in the subtree of the specified node.
 Works only if eflag is set, but called only in that case.  */

int
total_size_of_entries(node)
     reg NODE *node;
{
  reg int total = 0;
  reg long num;

  if (node == NULL)
    return 0;

  /* Count subentries that precede this one */
  total = total_size_of_entries (node->left);

  /* Count subentries that follow this one */
  total += total_size_of_entries (node->right);

  /* Count this entry */

  total += strlen (node->pat) + 3;

  num = node->lno;
  while (num)
    {
      total++;
      num /= 10;
    }

  num = node->cno;
  if (!num) total++;
  while (num)
    {
      total++;
      num /= 10;
    }
  return total;
}

/*
 * This routine finds functions and typedefs in C syntax and adds them
 * to the list.
 */
#ifdef VMS
long vmslinecharno;
#define VMS_SET_LINECHARNO	(vmslinecharno = ftell(inf))
#else
#define VMS_SET_LINECHARNO
#endif

#define CNL_SAVE_NUMBER \
{ \
  VMS_SET_LINECHARNO; \
  linecharno = charno; lineno++; \
  charno += 1 + readline (&lb, inf); \
  lp = lb.buffer; \
}

#define CNL \
{ \
  CNL_SAVE_NUMBER; \
  number = 0; \
}

void e_getline (long atchar);
void
C_entries ()
{
  register int c;
  register char *token, *tp, *lp;
  logical incomm, inquote, inchar, midtoken;
  int level;
  char tok[BUFSIZ];

  lineno = 0;
  charno = 0;
  lp = lb.buffer;
  *lp = 0;

  number = 0;
  gotone = midtoken = inquote = inchar = incomm = FALSE;
  level = 0;

  while (!feof (inf))
    {
      c = *lp++;
      if (c == 0)
	{
	  CNL;
	  gotone = FALSE;
	}
      if (c == '\\')
	{
	  c = *lp++;
	  if (c == 0)
	    CNL_SAVE_NUMBER;
	  c = ' ';
	} 
      else if (incomm)
	{
	  if (c == '*')
	    {
	      while ((c = *lp++) == '*')
		continue;
	      if (c == 0)
		CNL;
	      if (c == '/')
		incomm = FALSE;
	    }
	}
      else if (inquote)
	{
	  /*
	  * Too dumb to know about \" not being magic, but
	  * they usually occur in pairs anyway.
	  */
	  if (c == '"')
	    inquote = FALSE;
	  continue;
	}
      else if (inchar)
	{
	  if (c == '\'')
	    inchar = FALSE;
	  continue;
	}
      else switch (c)
	{
	case '"':
	  inquote = TRUE;
	  continue;
	case '\'':
	  inchar = TRUE;
	  continue;
	case '/':
	  if (*lp == '*')
	    {
	      lp++;
	      incomm = TRUE;
	    }
	  continue;
	case '#':
	  if (lp == lb.buffer + 1)
	    number = 1;
	  continue;
	case '{':
	  if (tydef == tag_ok)
	    {
	      tydef=middle;
	    }
	  level++;
	  continue;
	case '}':
	  if (lp == lb.buffer + 1)
	    level = 0;	/* reset */
	  else
	    level--;
	  if (!level && tydef==middle)
	    {
	      tydef=end;
	    }
	  continue;
	}
      if (!level && !inquote && !incomm && gotone == FALSE)
	{
	  if (midtoken)
	    {
	      if (endtoken(c))
		{
		  int f;
		  char *buf = lb.buffer;
		  int endpos = lp - lb.buffer;
		  char *lp1 = lp;
		  int line = lineno;
		  long linestart = linecharno;
#ifdef VMS
		  long vmslinestart = vmslinecharno;
#endif
		  int tem = consider_token (&lp1, token, &f, level);
		  lp = lp1;
		  if (tem)
		    {
		      if (linestart != linecharno)
			{
#ifdef VMS
			  e_getline (vmslinestart);
#else
			  e_getline (linestart);
#endif
			  strncpy (tok, token + (lb1.buffer - buf),
				   tp-token+1);
			  tok[tp-token+1] = 0;
			  pfnote(tok, f, lb1.buffer, endpos, line, linestart);
			}
		      else
			{
			  strncpy (tok, token, tp-token+1);
			  tok[tp-token+1] = 0;
			  pfnote(tok, f, lb.buffer, endpos, line, linestart);
			}
		      gotone = f;	/* function */
		    }
		  midtoken = FALSE;
		  token = lp - 1;
		}
	      else if (intoken(c))
		tp++;
	    }
	  else if (begtoken(c))
	    {
	      token = tp = lp - 1;
	      midtoken = TRUE;
	    }
	}
      if (c == ';'  &&  tydef==end)	/* clean with typedefs */
	tydef=none;
    }
}

/*
 * This routine  checks to see if the current token is
 * at the start of a function, or corresponds to a typedef
 * It updates the input line * so that the '(' will be
 * in it when it returns.
 */
int
consider_token (lpp, token, f, level)
     char **lpp, *token;
     int *f, level;
{
  reg char *lp = *lpp;
  reg char c;
  static logical next_token_is_func;
  logical firsttok;	/* T if have seen first token in ()'s */
  int bad, win;

  *f = 1;			/* a function */
  c = lp[-1];
  bad = FALSE;
  if (!number)
    {		/* space is not allowed in macro defs	*/
      while (iswhite(c))
	{
	  c = *lp++;
	  if (c == 0)
	    {
	      if (feof (inf))
		break;
	      CNL;
	    }
	}
      /* the following tries to make it so that a #define a b(c)	*/
      /* doesn't count as a define of b.				*/
    }
  else
    {
      number++;
      if (number >= 4  || (number==2 && strncmp (token, "define", 6)))
	{
	  gotone = TRUE;
	badone:
	  bad = TRUE;
	  goto ret;
	}
    }
  /* check for the typedef cases		*/
  if (tflag && istoken(token, "typedef", 7))
    {
      tydef=begin;
      goto badone;
    }
  if (tydef==begin && (istoken(token, "struct", 6) ||
		       istoken(token, "union", 5) || istoken(token, "enum", 4)))
  {
    tydef=tag_ok;      
    goto badone;
  }
  if (tydef==tag_ok)
    {
      tydef=middle;
      goto badone;
    }
  if (tydef==begin)		/* e.g. typedef ->int<- */
    {
      tydef=end;
      goto badone;
    }
  if (tydef==middle && level == 0) /* e.g. typedef struct tag ->struct_t<- */
    {
      tydef=end;
    }
  if (tydef==end)
    {
      *f = 0;
      win = 1;
      goto ret;
    }
  /* Detect GNUmacs's function-defining macros. */
  if (!number && !strncmp (token, "DEF", 3))
	 
    {
      next_token_is_func = 1;
      goto badone;
    }
  if (next_token_is_func)
    {
      next_token_is_func = 0;
      win = 1;
      goto ret;
    }
  if (c != '(')
    goto badone;
  firsttok = FALSE;
  while ((c = *lp++) != ')')
    {
      if (c == 0)
	{
	  if (feof (inf))
	    break;
	  CNL;
	}
      /*
	* This line used to confuse ctags:
	*	int	(*oldhup)();
	* This fixes it. A nonwhite char before the first
	* token, other than a / (in case of a comment in there)
	* makes this not a declaration.
	*/
      if (begtoken(c) || c=='/') firsttok++;
      else if (!iswhite(c) && !firsttok) goto badone;
    }
  while (iswhite (c = *lp++))
    {
      if (c == 0)
	{
	  if (feof (inf))
	    break;
	  CNL;
	}
    }
  win = isgood (c);
ret:
  *lpp = lp - 1;
  return !bad && win;
}

void
e_getline (atchar)
     long atchar;
{
  long saveftell = ftell (inf);

  fseek (inf, atchar, 0);
  readline (&lb1, inf);
  fseek (inf, saveftell, 0);
}

/* Fortran parsing */

char	*dbp;
int	pfcnt;
void getit ();
void takeprec ();

int
PF_funcs(fi)
     FILE *fi;
{
  lineno = 0;
  charno = 0;
  pfcnt = 0;

  while (!feof (fi))
    {
      lineno++;
      linecharno = charno;
      charno += readline (&lb, fi) + 1;
      dbp = lb.buffer;
      if (*dbp == '%') dbp++ ;	/* Ratfor escape to fortran */
      while (isspace(*dbp))
	dbp++;
      if (*dbp == 0)
	continue;
      switch (*dbp |' ')
	{
	case 'i':
	  if (tail("integer"))
	    takeprec();
	  break;
	case 'r':
	  if (tail("real"))
	    takeprec();
	  break;
	case 'l':
	  if (tail("logical"))
	    takeprec();
	  break;
	case 'c':
	  if (tail("complex") || tail("character"))
	    takeprec();
	  break;
	case 'd':
	  if (tail("double"))
	    {
	      while (isspace(*dbp))
		dbp++;
	      if (*dbp == 0)
		continue;
	      if (tail("precision"))
		break;
	      continue;
	    }
	  break;
	}
      while (isspace(*dbp))
	dbp++;
      if (*dbp == 0)
	continue;
      switch (*dbp|' ')
	{
	case 'f':
	  if (tail("function"))
	    getit();
	  continue;
	case 's':
	  if (tail("subroutine"))
	    getit();
	  continue;
	case 'p':
	  if (tail("program"))
	    {
	      getit();
	      continue;
	    }
	  if (tail("procedure"))
	    getit();
	  continue;
	}
    }
  return (pfcnt);
}

int
tail(cp)
     char *cp;
{
  register int len = 0;

  while (*cp && (*cp&~' ') == ((*(dbp+len))&~' '))
    cp++, len++;
  if (*cp == 0)
    {
      dbp += len;
      return (1);
    }
  return (0);
}

void
takeprec()
{
  while (isspace(*dbp))
    dbp++;
  if (*dbp != '*')
    return;
  dbp++;
  while (isspace(*dbp))
    dbp++;
  if (!isdigit(*dbp))
    {
      --dbp;		/* force failure */
      return;
    }
  do
    dbp++;
  while (isdigit(*dbp));
}

void
getit()
{
  register char *cp;
  char c;
  char nambuf[BUFSIZ];

  while (isspace(*dbp))
    dbp++;
  if (*dbp == 0 || !isalpha(*dbp))
    return;
  for (cp = dbp+1; *cp && (isalpha(*cp) || isdigit(*cp)); cp++)
    continue;
  c = cp[0];
  cp[0] = 0;
  strcpy(nambuf, dbp);
  cp[0] = c;
  pfnote(nambuf, TRUE, lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
  pfcnt++;
}

/*
 * lisp tag functions
 * just look for (def or (DEF
 */

void L_getit ();
void
L_funcs (fi)
     FILE *fi;
{
  lineno = 0;
  charno = 0;
  pfcnt = 0;

  while (!feof (fi))
    {
      lineno++;
      linecharno = charno;
      charno += readline (&lb, fi) + 1;
      dbp = lb.buffer;
      while (isspace(*dbp)) dbp++;
      if (dbp[0] == '(' && 
	  (dbp[1] == 'D' || dbp[1] == 'd') &&
	    (dbp[2] == 'E' || dbp[2] == 'e') &&
	      (dbp[3] == 'F' || dbp[3] == 'f'))
	{
	  while (!isspace(*dbp)) dbp++;
	  while (isspace(*dbp)) dbp++;
	  L_getit();
	}
      if (dbp[0] == '(' && 
	  (dbp[1] == ':'))
	{
	  while (!isspace(*dbp)) dbp++;
	  while (isspace(*dbp)) dbp++;
	  L_getit();
	}

    }
}

void
L_getit()
{
  register char *cp;
  char c;
  char nambuf[BUFSIZ];

  if (*dbp == 0) return;
  for (cp = dbp+1; *cp && *cp != '(' && *cp != ' '; cp++)
    continue;
  c = cp[0];
  cp[0] = 0;
  strcpy(nambuf, dbp);
  cp[0] = c;
  pfnote(nambuf, TRUE, lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
  pfcnt++;
}

/*
 * Scheme tag functions
 * look for (def... xyzzy
 * look for (def... (xyzzy
 * look for (def ... ((...(xyzzy ....
 * look for (set! xyzzy
 */

void static get_scheme ();
void
Scheme_funcs (fi)
     FILE *fi;
{
  lineno = 0;
  charno = 0;
  pfcnt = 0;

  while (!feof (fi))
    {
      lineno++;
      linecharno = charno;
      charno += readline (&lb, fi) + 1;
      dbp = lb.buffer;
      if (dbp[0] == '(' && 
	  (dbp[1] == 'D' || dbp[1] == 'd') &&
	    (dbp[2] == 'E' || dbp[2] == 'e') &&
	      (dbp[3] == 'F' || dbp[3] == 'f'))
	{
	  while (!isspace(*dbp)) dbp++;
          /* Skip over open parens and white space */
          while (*dbp && (isspace(*dbp) || *dbp == '(')) dbp++;
	  get_scheme ();
	}
      if (dbp[0] == '(' && 
	  (dbp[1] == 'S' || dbp[1] == 's') &&
	    (dbp[2] == 'E' || dbp[2] == 'e') &&
	      (dbp[3] == 'T' || dbp[3] == 't') &&
                (dbp[4] == '!' || dbp[4] == '!') &&
                  (isspace(dbp[5])))
	{
	  while (!isspace(*dbp)) dbp++;
          /* Skip over white space */
          while (isspace(*dbp)) dbp++;
	  get_scheme ();
	}
    }
}

void
static
get_scheme()
{
  register char *cp;
  char c;
  char nambuf[BUFSIZ];

  if (*dbp == 0) return;
  /* Go till you get to white space or a syntactic break */
  for (cp = dbp+1; *cp && *cp != '(' && *cp != ')' && !isspace(*cp); cp++)
    continue;
  /* Null terminate the string there. */
  c = cp[0];
  cp[0] = 0;
  /* Copy the string */
  strcpy(nambuf, dbp);
  /* Unterminate the string */
  cp[0] = c;
  /* Announce the change */
  pfnote(nambuf, TRUE, lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
  pfcnt++;
}

/* Find tags in TeX and LaTeX input files.  */

/* TEX_toktab is a table of TeX control sequences that define tags.
   Each TEX_tabent records one such control sequence.  */

struct TEX_tabent
{
  char *name;
  int len;
};

struct TEX_tabent *TEX_toktab = NULL; /* Table with tag tokens */

/* Default set of control sequences to put into TEX_toktab.
   The value of environment var TEXTAGS is prepended to this.  */

static char *TEX_defenv =
  ":chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem:typeout";

struct TEX_tabent *TEX_decode_env (); 

static char TEX_esc = '\\';
static char TEX_opgrp = '{';
static char TEX_clgrp = '}';

/*
 * TeX/LaTeX scanning loop.
 */

void TEX_mode (FILE *f);
void TEX_getit (char *name, int len);
void
TEX_funcs (fi)
    FILE *fi;
{
  char *lasthit;

  lineno = 0;
  charno = 0;
  pfcnt = 0;

  /* Select either \ or ! as escape character.  */
  TEX_mode (fi);

  /* Initialize token table once from environment. */
  if (!TEX_toktab)
    TEX_toktab = TEX_decode_env ("TEXTAGS", TEX_defenv);

  while (!feof (fi))
    {
      lineno++;
      linecharno = charno;
      charno += readline (&lb, fi) + 1;
      dbp = lb.buffer;
      lasthit = dbp;

      while (!feof (fi))
	{	/* Scan each line in file */
	  lineno++;
	  linecharno = charno;
	  charno += readline (&lb, fi) + 1;
	  dbp = lb.buffer;
	  lasthit = dbp;
	  while (dbp = _index (dbp, TEX_esc)) /* Look at each escape in line */
	    {
	      register int i;

	      if (! *(++dbp))
		break;
	      linecharno += dbp - lasthit;
	      lasthit = dbp;
	      i = TEX_Token (lasthit);
	      if (0 <= i)
		{
		  TEX_getit (lasthit, TEX_toktab[i].len);
		  break;		/* We only save a line once */
		}
	    }
	}
    }
}

#define TEX_LESC '\\'
#define TEX_SESC '!'

/* Figure out whether TeX's escapechar is '\\' or '!' and set grouping */
/* chars accordingly. */

void
TEX_mode (f)
     FILE *f;
{
  int c;

  while ((c = getc (f)) != EOF)
    if (c == TEX_LESC || c == TEX_SESC)
      break;

  if (c == TEX_LESC)
    {
      TEX_esc = TEX_LESC;
      TEX_opgrp = '{';
      TEX_clgrp = '}';
    } 
  else
    {
      TEX_esc = TEX_SESC;
      TEX_opgrp = '<';
      TEX_clgrp = '>';
    }
  rewind (f);
}

/* Read environment and prepend it to the default string. */
/* Build token table. */

struct TEX_tabent *
TEX_decode_env (evarname, defenv)
     char *evarname;
     char *defenv;
{
  register char *env, *p;
  extern char *savenstr (), *_index ();

  struct TEX_tabent *tab;
  int size, i;

  /* Append deafult string to environment. */
  env = (char *) getenv (evarname);
  if (!env)
    env = defenv;
  else
    env = concat (env, defenv, "");

  /* Allocate a token table */
  for (size = 1, p=env; p;)
    if ((p = _index (p, ':')) && *(++p))
      size++;
  tab = (struct TEX_tabent *) xmalloc (size * sizeof (struct TEX_tabent));

  /* Unpack environment string into token table. Be careful about */
  /* zero-length strings (leading ':', "::" and trailing ':') */
  for (i = 0; *env;)
    {
      p = _index (env, ':');
      if (!p)			/* End of environment string. */
	p = env + strlen (env);
      if (p - env > 0)
	{	/* Only non-zero strings. */
	  tab[i].name = savenstr (env, p - env);
	  tab[i].len = strlen (tab[i].name);
	  i++;
	}
      if (*p)
	env = p + 1;
      else
	{
	  tab[i].name = NULL;	/* Mark end of table. */
	  tab[i].len = 0;
	  break;
	}
    }
  return tab;
}

/* Record a tag defined by a TeX command of length LEN and starting at NAME.
   The name being defined actually starts at (NAME + LEN + 1).
   But we seem to include the TeX command in the tag name.  */

void
TEX_getit (name, len)
    char *name;
    int len;
{
  char *p = name + len;
  char nambuf[BUFSIZ];

  if (*name == 0) return;

  /* Let tag name extend to next group close (or end of line) */
  while (*p && *p != TEX_clgrp)
    p++;
  strncpy (nambuf, name, p - name);
  nambuf[p - name] = 0;

  pfnote (nambuf, TRUE, lb.buffer, strlen (lb.buffer), lineno, linecharno);
  pfcnt++;
}

/* If the text at CP matches one of the tag-defining TeX command names,
   return the index of that command in TEX_toktab.
   Otherwise return -1.  */

/* Keep the capital `T' in `Token' for dumb truncating compilers
   (this distinguishes it from `TEX_toktab' */
int
TEX_Token (cp)
    char *cp;
{
  int i;

  for (i = 0; TEX_toktab[i].len > 0; i++)
    if (strncmp (TEX_toktab[i].name, cp, TEX_toktab[i].len) == 0)
      return i;
  return -1;
}

/* Initialize a linebuffer for use */

void
initbuffer (linebuffer)
     struct linebuffer *linebuffer;
{
  linebuffer->size = 200;
  linebuffer->buffer = (char *) xmalloc (200);
}

/* Read a line of text from `stream' into `linebuffer'.
 Return the length of the line.  */

long
readline (linebuffer, stream)
     struct linebuffer *linebuffer;
     register FILE *stream;
{
  char *buffer = linebuffer->buffer;
  register char *p = linebuffer->buffer;
  register char *pend = p + linebuffer->size;

  while (1)
    {
      int c = getc (stream);
      if (p == pend)
	{
	  linebuffer->size *= 2;
	  buffer = (char *) xrealloc (buffer, linebuffer->size);
	  p += buffer - linebuffer->buffer;
	  pend = buffer + linebuffer->size;
	  linebuffer->buffer = buffer;
	}
      if (c < 0 || c == '\n')
	{
	  *p = 0;
	  break;
	}
      *p++ = c;
    }

  return p - buffer;
}

char *
savestr(cp)
     char *cp;
{
  return savenstr (cp, strlen (cp));
}

char *
savenstr(cp, len)
    char *cp;
    int len;
{
  register char *dp;

  dp = (char *) xmalloc (len + 1);
  strncpy (dp, cp, len);
  dp[len] = '\0';
  return dp;
}

/*
 * Return the ptr in sp at which the character c last
 * appears; NULL if not found
 *
 * Identical to v7 rindex, included for portability.
 */

char *
_rindex(sp, c)
     char *sp, c;
{
  char *r;

  r = NULL;
  do
    {
      if (*sp == c)
	r = sp;
    } while (*sp++);
  return(r);
}

/*
 * Return the ptr in sp at which the character c first
 * appears; NULL if not found
 *
 * Identical to v7 index, included for portability.
 */

char *
_index(sp, c)
     register char *sp, c;
{
  do
    {
      if (*sp == c)
	return (sp);
    } while (*sp++);
  return (NULL);
}

/* Print error message and exit.  */

void error (char *s1, char *s2);
void
fatal (s1, s2)
     char *s1, *s2;
{
  error (s1, s2);
  exit (BAD);
}

/* Print error message.  `s1' is printf control string, `s2' is arg for it. */

void
error (s1, s2)
     char *s1, *s2;
{
  fprintf (stderr, "%s: ", progname);
  fprintf (stderr, s1, s2);
  fprintf (stderr, "\n");
}

/* Return a newly-allocated string whose contents concatenate those of s1, s2, s3.  */

char *
concat (s1, s2, s3)
     char *s1, *s2, *s3;
{
  int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  char *result = (char *) xmalloc (len1 + len2 + len3 + 1);

  strcpy (result, s1);
  strcpy (result + len1, s2);
  strcpy (result + len1 + len2, s3);
  *(result + len1 + len2 + len3) = 0;

  return result;
}

/* Like malloc but get fatal error if memory is exhausted.  */

int
xmalloc (size)
     int size;
{
  int result = (int)malloc (size);
  if (!result)
    fatal ("virtual memory exhausted", 0);
  return result;
}

int
xrealloc (ptr, size)
     char *ptr;
     int size;
{
  int result = (int)realloc (ptr, size);
  if (!result)
    fatal ("virtual memory exhausted");
  return result;
}