summaryrefslogtreecommitdiff
path: root/indexing/lamstex-index/index.c
blob: b2d5bcd647329e6a965f2d69a50104f3db30c36f (plain)
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
/************************************************************************/
/*   File:	Index.c            					*/
/************************************************************************/
/*   Developer:	TeXplorators Inc., Houston, Texas		        */
/*   PRODUCT  :	Index: Sort TeX index entries alphabetically		*/
/*   Module   :	index							*/
/*   Notes    :	This source code is compiled with Microsoft C 5.1       */
/************************************************************************/
/*
			SOFTWARE LICENSE AGREEMENT

1. PURPOSE
	This agreement recites the terms and conditions under which 
The TeXplorators Corporation ("TEXPLORATORS") agrees to grant you a 
free, nonexclusive, transferable license to use the INDEX software.

2. UNDERTAKINGS BY TEXPLORATORS
	2A. Ownership: Ownership of the INDEX software remains 
exclusively in TEXPLORATORS.
	2B. License Fee: TEXPLORATORS makes the INDEX software 
available to you free of any license fee.
	2C. Disclaimers: TEXPLORATORS DISCLAIMS ALL EXPRESS OR IMPLIED
WARRANTIES OF INDEX'S MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
PURPOSE.
	2D. Liability: TEXPLORATORS' LIABILITY, IF ANY, IS LIMITED TO 
THE DISTRIBUTION FEE YOU PAID, AND DOES NOT INCLUDE SPECIAL AND/OR
CONSEQUENTIAL DAMAGES ARISING OUT OF, OR IN CONNECTION WITH, THE USE 
OF INDEX.  SINCE SOME STATES DISALLOW LIMITATION OR EXCLUSION OF 
LIABILITY, THIS LIMITATION OR EXCLUSION MAY NOT APPLY TO YOU.

3. UNDERTAKINGS BY YOU.
	3A. Proper Use: You agree to use the INDEX software in
compliance with the terms and conditions hereof.
	3B. Notices on Authorized Copies: You agree to take reasonable
precautions to preserve the propriety of the INDEX software by
duplicating verbatim, on all copies thereof, the notices of TEXPLORATORS'
interests recited thereon.  You agree to note that source code is 
available upon request, if you do not distribute source code with the
INDEX software.
	3C. Distribution: You are encouraged to freely distribute the
INDEX software, including source code, on or through any common media
including diskettes and electronic bulletin board systems.  You agree to
distribute this license with each and every copy so distributed, and to 
either distribute source code therewith or make source code available upon
request. You may charge a distribution fee to cover the cost of diskettes,
handling and shipping.
	3D. Modifications: You are authorized to make modifications to
INDEX, but these modifications must be conspicuously noted and dated
therewith.
	3E. License Fee: You may not charge a license fee for the
INDEX software, either in its original or modified form.  However, you
may charge a license fee for your software which is broader in scope
than INDEX, whereby INDEX is not a primary functional unit thereof.

4. SCOPE
	This Software License Agreement constitutes the entire agreement
between TEXPLORATORS and you regarding the INDEX software, and shall
be construed under the laws of the State of TEXAS.

					The TeXplorators Corporation
					By: Michael Spivak, President

Page*/
/*
  HISTORY:
   [03/07/1991] - Index now operates on a single .ndx file - there will be
                  .npg file. An error message will be issued if a
                  \Page{...}{...}{...} does not follow each entry.
                  Each entry buffer size is expanded to 300 symbols.
*/

/* Configuration and defines for Unix 05/08/1991, P. A. MacKay */

/* System-dependent defines */
#include "config.h"

/*------------------------------*/
/*	includes		*/
/*------------------------------*/
#include  <stdio.h>
#include  <ctype.h>
#include  <malloc.h>	
#include  <string.h>
#ifdef ANSI
#include  <stdlib.h>
#endif
#include  <memory.h>

/*------------------------------*/
/*	defines			*/
/*------------------------------*/

#define TRUE        1
#define FALSE       0

#define MAX_STRING    5120
#define MAX_ENTRIES   15000
#define MAX_DEFINES   200
#define MAX_ABBREVS   200
#define MAX_PAGEORDER 200
#define MAX_PAGEENTRY 500

#define SPACE       32
#define COMMA       ','
#define STAR        '*'
#define DQUOTE      34
#define BAR         '|'
#define LBRACE      123
#define RBRACE      125
#define RSLASH	    '\\'
#define MINUS       '-'
#define PLUS        '+'
#define NL	    '\n'
#define LBRACKET    '['
#define RBRACKET    ']'
#define LPAREN      '('
#define RPAREN      ')'
#define QUOTE       39
#define DOLLAR      '$'
#define ATSIGN      '@'
#define TILDE       '~'
#define EXCLAIM     '!'
#define CARET       '^'
#define USCORE      '_'
#define EQUAL       '='
#define COLON       ':'
#define SEMI        ';'
#define LQUOTE      '`'
#define GREATER     '>'
#define LESS        '<'
#define QUESTION    '?'
#define SLASH       '/'
#define PERIOD      '.'

#define ZERO        '0'
#define ONE         '1'
#define TWO	    '2'
#define THREE       '3'
#define FOUR        '4'
#define FIVE        '5'

#define ENTRY1       1
#define ENTRY2       4
#define ENTRY3       7
#define ENTRY4      10
#define ENTRY5      13

#define PRE_TYPE     0
#define POST_TYPE    1
#define ALIAS_TYPE   2
#define ENTRY_TYPE   3
#define XREF_TYPE    4
#define CROSS_TYPE   5
#define OTHER_TYPE   6

#define LEVEL0        0
#define LEVEL1        1
#define LEVEL2        2
#define LEVEL3        3
#define LEVEL4        4
#define LEVEL5        5

#define E1            1
#define E1_PRE        2
#define E1_POST       3
#define E1_ALIAS     23
#define E1_CS        28

#define E2            4
#define E2_PRE        5
#define E2_POST       6
#define E2_ALIAS     24
#define E2_CS        29

#define E3            7
#define E3_PRE        8
#define E3_POST       9
#define E3_ALIAS     25
#define E3_CS        30

#define E4           10
#define E4_PRE       11
#define E4_POST      12
#define E4_ALIAS     26
#define E4_CS        31

#define E5           13
#define E5_PRE       14
#define E5_POST      15
#define E5_ALIAS     27
#define E5_CS        32

#define XREF         16
#define NUMBER       17
#define CSNAME       18
#define PREFIX       19
#define POSTFIX      20
#define PAGE_SPAN    21
#define LARGEST      22
#define CTRLSEQ      33
#define CROSS_REF    34

/*------------------------------*/
/*	typedefs		*/
/*------------------------------*/
#ifdef MICROSOFT_C
typedef unsigned int   WORD;
#else
typedef unsigned short   WORD;
#endif
typedef unsigned char  BYTE;

typedef struct
{
  char *fields[35];
} FieldType;

typedef struct
{
  FieldType *item;
} EntryType;

typedef struct
{
  char *astr;
  char *xstr;
} AbbrvType;

typedef struct
{
  char *style;
  char *pre;
  char *post;
  BYTE order;
  BYTE nstyle;
  BYTE npre;
  BYTE npost;
} PageOrderType;

/*------------------------------*/
/*	data structures		*/
/*------------------------------*/
EntryType Entry[MAX_ENTRIES];	/* entries		    */
char      *define[MAX_DEFINES];	/* defines		    */
AbbrvType *abbrev[MAX_ABBREVS];	/* abbrevs		    */
PageOrderType *PO[MAX_PAGEORDER];/*page orders		    */
int       SubPageOrder[MAX_PAGEENTRY];
int       SortingOrder[35];     /* sorting order indices    */
int       FirstOrder;		/* First Sorting Order entry*/
int       LastOrder;		/* Last Sorting Order entry */
int       PageOrder[10];        /* Page order indices       */
int       PageOrderFirst;	/* Fist page order entry    */
int       PageOrderLast;	/* Last page order entry    */
char      PageType;		
int       PageIndex;
int       PageSpan;
int       Tindex;		/* Topage Index 	    */
char	  string[300];		/* working string buffer    */
FILE      *ndxfile;		/* index file		    */
FILE      *xdxfile;		/* sorted file		    */
FILE      *xxxfile;		/* temporary file	    */
char      ndxname[80];		/* .ndx file name	    */
char      xdxname[80];		/* .xdx file name	    */
char      tmpname[80];		/* .@d@ file name	    */
char	  idxname[80];		/* .idx file name	    */
BYTE      alias;		/* alias flag		    */
BYTE      xref;			/* xref flag		    */
BYTE      crossref;		/* crossref flag            */
BYTE      curEntry;		/* type of entry appears    */
WORD      nitems;		/* number of input lines    */
WORD      ndef; 		/* number of defs	    */
WORD      nabb;			/* number of abbrevs	    */
WORD      npo;			/* number of pageorders	    */
char      curLetter;		/* current letter	    */
char      preLetter;		/* previous letter	    */
BYTE      FirstEntry;		/* first entry flag	    */
char      pagenum[80];		/* page number		    */
char      prevnum[80];		/* previous page number	    */
BYTE      skippage;		/* skip page flag	    */
char      *nullstr="";		/* NULL string		    */
char      *NULLPTR;		/* NULL pointer		    */
char      *delstr="D";		/* Delete string	    */
char      *DELPTR;		/* DEL pointer		    */
BYTE      idxfile;              /* make idxfile		    */
char      msgbuf[1024];         /* message buffer	    */
int       curIndex;		/* current index	    */
char      arg1[300], arg2[300], arg3[300], arg4[300], arg5[300];

/*------------------------------*/
/*	functions prototypes	*/
/*------------------------------*/
#ifdef ANSI /* Use ANSI C prototypes */
void  beep(void);
void  BuildProc(void);
void  BuildString(int);

char *CheckAbbrev(char s[], char *q);
void  CheckAlias(int);
BYTE  CheckLevel(int cur, int idx, BYTE level);
int   CompareStrings(int i,int j);
int   CompareStringsPO(int i,int j);
void  copyString(int,int,char *);

void  doNDX(int,char *);
void  doNPG(int,char *);
void  DoNormal(int idx,char arg[]);
void  DoVariant(int idx, char arg[]);
int   DupPageFormat(int idx, char arg[]);
int   DupEntry(int idx, int cur);
int   DupXref(int idx, int cur);

void  error(char *);
void  exit(int);

int   FindLastT( int idx );
void  FreeEntry( int idx );
void  FreeMem(void);

void  GetAbbrevSpace(int);
void  GetArg(int idx,char arg[],BYTE pre,BYTE cs,BYTE entry,
             BYTE post,BYTE alias);
void  GetArgs(int idx,char *arg1,char *arg2,char *arg3,
              char *arg4,char *arg5);
BYTE  GetD2(int cur,int idx);
void  GetFieldSpace(int);
BYTE  GetPageNum(int idx);
int   GetPageOrder(int);
void  GetPageOrderSpace(int);
char *GetStringSpace(char *);
int   GetSubLevel(int, int);

void  InitProc(void);

void  OutputProc(int idx,char *arg1,char *arg2,char *arg3,
                 char *arg4,char *arg5);

int  main(int argc, char *argv[]);
void  MoveEntry( int from, int to );

void  PreProc(void);
void  printMSG(char *);
void  PrintErrorMSG(void);
void  PutPageNum(int idx);
void  PutByte( char c, FILE *f );
void  PutString( char string[], FILE *f );

void  ReduceSpaces(char *);
void  RemoveDuplicates( void );
void  RemoveEmptySet(char *str);
void  RemoveSpaces(char *);
void  RemoveTrailingSpace(char *str);

void  ScanEntry( char line[] );
char *SkipSpaces(char *p);
void  SkipSpacesReverse(int len, char *p);
void  SortPageNumber( int beg, int end );
void  SortProc(void);
void  strCopy(char *,char *,int);
void  SwapStrings(int cur, int nxt);
void  syntax_error(char *);

void  TeXOut(void);
void  TeXPut(int idx);

void  xref_proc(int idx);
void  xxref_proc(int idx);
void  other_proc(int idx);
#else
/* Use old-style K&R function declarations */
void  beep();
void  BuildProc();
void  BuildString();

char *CheckAbbrev();
void  CheckAlias();
BYTE  CheckLevel();
int   CompareStrings();
int   CompareStringsPO();
void  copyString();

void  doNDX();
void  doNPG();
void  DoNormal();
void  DoVariant();
int   DupPageFormat();
int   DupEntry();
int   DupXref();

void  error();
void  exit();

int   FindLastT();
void  FreeEntry();
void  FreeMem();

void  GetAbbrevSpace();
void  GetArg();
void  GetArgs();
BYTE  GetD2();
void  GetFieldSpace();
BYTE  GetPageNum();
int   GetPageOrder();
void  GetPageOrderSpace();
char *GetStringSpace();
int   GetSubLevel();

void  InitProc();

void  OutputProc();

int main();
void  MoveEntry();

void  PreProc();
void  printMSG();
void  PrintErrorMSG();
void  PutPageNum();
void  PutByte();
void  PutString();

void  ReduceSpaces();
void  RemoveDuplicates();
void  RemoveEmptySet();
void  RemoveSpaces();
void  RemoveTrailingSpace();

void  ScanEntry();
char *SkipSpaces();
void  SkipSpacesReverse();
void  SortPageNumber();
void  SortProc();
void  strCopy();
void  SwapStrings();
void  syntax_error();

void  TeXOut();
void  TeXPut();

void  xref_proc();
void  xxref_proc();
void  other_proc();
#endif

/*------------------------------*/
/*	functions 		*/
/*------------------------------*/

void beep()
{
   printf("\007\b");
   return;
}

void FreeMem()
{
int i,j;
   for (i=0; i<=nitems; i++)
   {
     if ( Entry[i].item!=NULL )
     {
       for (j=E1; j<=CROSS_REF; j++)
       {
	if (Entry[i].item->fields[j]!=NULLPTR )
	    free( Entry[i].item->fields[j] );
       }
     }
   }
   for (i=0; i<MAX_DEFINES; i++)
	if ( define[i]!=NULL )
	     free( define[i] );
   for (i=0; i<MAX_ABBREVS; i++)
	if ( abbrev[i]!=NULL )
	{
	     if ( abbrev[i]->astr != NULL ) free( abbrev[i]->astr );
	     if ( abbrev[i]->xstr != NULL ) free( abbrev[i]->xstr );
	     free( abbrev[i] );
	}
	
   for (i=0; i<MAX_PAGEORDER; i++)
	if ( PO[i]!=NULL )
	{
	     if ( PO[i]->style !=NULL ) free( PO[i]->style );
	     if ( PO[i]->pre   !=NULL ) free( PO[i]->pre );
	     if ( PO[i]->post  !=NULL ) free( PO[i]->post );
	     free( PO[i] );
        }

   return;
}

void error(s)
char *s;
{
   beep();	
   printf("\n%s\n",s);
   FreeMem();
   exit(0);
}

void syntax_error(s)
char *s;
{ 
  sprintf(string,"syntax error! -> %s",s);
  error(string); 
}


void printMSG(s)
char *s;
{
   int i;
   printf("\r");
   for (i=0; i<78; i++)
       printf(" ");
   printf("\r");
   printf("%s",s);
   return;
}


void PutByte(c,f)
 char c; 
 FILE *f;
{
  fputc( c, f );
  if ( ferror(f) )
       error("! File write error - out of disk space");
} /* end - PutByte */


void PutString(s,f)
 char *s; 
 FILE *f;
{
   fputs( s, f );
   if ( ferror(f) )
       error("! File write error - out of disk space");
} /* end  - PutString */

/* Get Field Space */
void GetFieldSpace(idx)
int  idx;
{
int  i;
   
   /* Check for boundary conditions */
   if ( idx >= MAX_ENTRIES )
   {
      sprintf(string,"! number of entries (%d) exceeded MAXIMUM allowed (%d)",
	      idx,MAX_ENTRIES);
      error( string );
   }
   
   Entry[idx].item = (FieldType *) malloc( sizeof(FieldType) );
   if ( Entry[idx].item==NULL )
	error("! out of fields space");
   for (i=0; i<35; i++)
	Entry[idx].item->fields[i]=NULLPTR;
   return;
}


/* Get Abbrev Space */
void GetAbbrevSpace(idx)
int  idx;
{
   /* Check for boundary conditions */
   if ( idx >= MAX_ABBREVS )
   {
      sprintf(string,"! number of abbrevs (%d) exceeded MAXIMUM allowed (%d)",
	      idx,MAX_ABBREVS);
      error( string );
   }
   
   abbrev[idx] = (AbbrvType *) malloc( sizeof(AbbrvType) );
   if ( abbrev[idx]==NULL )
	error("! out of space");
   abbrev[idx]->astr = NULL;
   abbrev[idx]->xstr = NULL;
   return;
}

/* Get PageOrder Space */
void GetPageOrderSpace(idx)
int  idx;
{

   /* Check for boundary conditions */
   if ( idx >= MAX_PAGEORDER )
   {
      sprintf(string,
      "! number of pageorders directives (%d) exceeded MAXIMUM allowed (%d)",
	      idx,MAX_PAGEORDER);
      error( string );
   }
  
   PO[idx] = (PageOrderType *) malloc( sizeof(PageOrderType) );
   if ( PO[idx]==NULL )
	error("! out of space");
   PO[idx]->style = NULL;
   PO[idx]->pre   = NULL;
   PO[idx]->post  = NULL;
   PO[idx]->order    = 0;
   PO[idx]->nstyle   = 0;
   PO[idx]->npre     = 0;
   PO[idx]->npost    = 0;
   return;
}


/* Get String Space */
char * GetStringSpace(str)
char *str;
{
char *p;
int  i;
   i = strlen(str);
   p = (char *) malloc( i+1 );
   if ( p==NULL )
	error("! out of strings space");
   return(p);
}


void InitProc()
{
  int i;
  for (i=0; i<MAX_ENTRIES; i++)
       Entry[i].item = NULL;
  for (i=0; i<MAX_DEFINES; i++)
       define[i] = NULL;
  for (i=0; i<MAX_ABBREVS; i++)
       abbrev[i] = NULL;
  for (i=0; i<MAX_PAGEORDER; i++)
       PO[i] = NULL;
  FirstEntry = TRUE;	
  NULLPTR    = &nullstr[0];
  PageType   = 0;
  PageIndex  = 0;
  PageSpan   = FALSE;
  Tindex     = 0;
  
  SortingOrder[1] =E1;
  SortingOrder[2] =E1_ALIAS;
  SortingOrder[3] =E1_PRE;
  SortingOrder[4] =E1_POST;
  
  SortingOrder[5] =E2;
  SortingOrder[6] =E2_ALIAS;
  SortingOrder[7] =E2_PRE;
  SortingOrder[8] =E2_POST;
  
  SortingOrder[9] =E3;
  SortingOrder[10]=E3_ALIAS; 
  SortingOrder[11]=E3_PRE;
  SortingOrder[12]=E3_POST;
  
  SortingOrder[13]=E4;  
  SortingOrder[14]=E4_ALIAS;
  SortingOrder[15]=E4_PRE;
  SortingOrder[16]=E4_POST;
  
  SortingOrder[17]=E5;
  SortingOrder[18]=E5_ALIAS;  
  SortingOrder[19]=E5_PRE;  
  SortingOrder[20]=E5_POST;
  SortingOrder[21]=CROSS_REF;
 
  FirstOrder = 1;
  LastOrder  = 21;

  PageOrder[0] = CSNAME;
  PageOrder[1] = PREFIX;
  PageOrder[2] = NUMBER;
  PageOrder[3] = POSTFIX;
 
  PageOrderFirst = 0;
  PageOrderLast  = 3;
  
  return;
}

void ReduceSpaces(str)
char *str;
{
   char *p;
   char *q;

   p = str; q = str;
   while ( *p != 0 )
   {
      if ( (*p == SPACE) && (*(p+1) == SPACE) ) p++;
      else
          *q++ = *p++;
   }
   *q = *p;
   return;
}


void BuildString(idx)
int idx;
{
  int  i;
  char cbuf[300];
  char str[300];

  string[0] = 0;
  for (i=E1; i<NUMBER; i++)
  {
    switch( i )
    {
      case 2: case 5: case 8: case 11: case 14:
      case 3: case 6: case 9: case 12: case 15:	
	   if ( Entry[idx].item->fields[i]!=NULLPTR )
	   {
                memcpy(cbuf,Entry[idx].item->fields[i],
	               strlen(Entry[idx].item->fields[i])+1);
	   }
	   else cbuf[0]=0;
	   sprintf(str,"%s %c",cbuf,BAR);
	   strcat(string,str);
	   break;
      default:
	   if ( Entry[idx].item->fields[i]!=NULLPTR )
                memcpy(cbuf,Entry[idx].item->fields[i],
		       strlen(Entry[idx].item->fields[i])+1);
	   else cbuf[0] = 0;
	   sprintf(str,"%s %c",cbuf,BAR);
	   ReduceSpaces(&str[0]);    
	   strcat(string,str);
	   break;
      }
  }
  
  for (i=NUMBER; i<=CROSS_REF; i++)
  {
    if ( Entry[idx].item->fields[i]!=NULLPTR )
         memcpy(cbuf,Entry[idx].item->fields[i], 
	        strlen(Entry[idx].item->fields[i])+1);
    else cbuf[0]=0;
    sprintf(str,"%s%c",cbuf,BAR);
    ReduceSpaces(&str[0]);    
    strcat(string,str);
  }

  return;
}

int GetSubLevel(n,op)
int n,op;
{
int  cur;	
   switch ( op )
   {
     case 'a':   cur = 22 + n; curEntry = ALIAS_TYPE; alias = TRUE; 
          break;
     case MINUS: cur = n*3 -1; curEntry = PRE_TYPE; 
          break;
     case PLUS:  cur = n*3;    curEntry = POST_TYPE; 
          break;
     case 'e':   cur = 27 + n; curEntry = ENTRY_TYPE; 
          break;
     default:    cur = 0; 
          break;
   }
  return(cur);
}

void CheckAlias(idx)
int idx;
{
char *p;

   if ( Entry[idx].item->fields[E1_ALIAS]!=NULLPTR )
   {
       p = Entry[idx].item->fields[E1];
       Entry[idx].item->fields[E1] = Entry[idx].item->fields[E1_ALIAS];
       Entry[idx].item->fields[E1_ALIAS] = p;
   }

   if ( Entry[idx].item->fields[E2_ALIAS]!=NULLPTR )
   {
       p = Entry[idx].item->fields[E2];
       Entry[idx].item->fields[E2] = Entry[idx].item->fields[E2_ALIAS];
       Entry[idx].item->fields[E2_ALIAS] = p;
   }

   if ( Entry[idx].item->fields[E3_ALIAS]!=NULLPTR )
   {
       p = Entry[idx].item->fields[E3];
       Entry[idx].item->fields[E3] = Entry[idx].item->fields[E3_ALIAS];
       Entry[idx].item->fields[E3_ALIAS] = p;
   }

   if ( Entry[idx].item->fields[E4_ALIAS]!=NULLPTR )
   {
       p = Entry[idx].item->fields[E4];
       Entry[idx].item->fields[E4] = Entry[idx].item->fields[E4_ALIAS];
       Entry[idx].item->fields[E4_ALIAS] = p;
   }

   if ( Entry[idx].item->fields[E5_ALIAS]!=NULLPTR )
   {
       p = Entry[idx].item->fields[E5];
       Entry[idx].item->fields[E5] = Entry[idx].item->fields[E5_ALIAS];
       Entry[idx].item->fields[E5_ALIAS] = p;
   }
   return;	
}


void strCopy(d,s,len)
char *d, *s;
int  len;
{
int  i;
   for (i=0; i<=len; i++)
        *(d+i) = *(s+i);
   return;	
}

void copyString(idx,cur,str)
int  idx,cur;
char *str;
{
 if ( cur == 0 ) return;	
    Entry[idx].item->fields[cur] = GetStringSpace( str );
    strcpy(Entry[idx].item->fields[cur], str );
    return;	
}

char *SkipSpaces(p)
char *p;
{
   while ( *p==SPACE && *p!=0 ) p++;	
   return(p);	
}

void SkipSpacesReverse(len,q)
int  len;
char *q;
{
   char *r;

   r = q-2;
   while ( *r==SPACE && len>0 ) 
   { r--; len--; }
   r++; *r = 0;
   
   return;	
}

void RemoveSpaces(str)
char *str;
{
   char *p;
   char *q;

   p = q = str; 
   while ( *p != 0 )
   {
      if ( (*p == SPACE) ) p++;
      else
          *q++ = *p++;
   }
   *q = *p;
   return;
}

void RemoveEmptySet(str)
char *str;
{
   char *p;
   char *q;   

   if ( strlen(str) <= 2 ) return;
   p = str; q = str;
   while ( *p != 0 )
   {
      if ( (*p == LBRACE) && (*(p+1) == RBRACE) ) p+=2;
      else
          *q++ = *p++;
   }
   *q = *p;
   return;
}

void RemoveTrailingSpace(str)
char *str;
{
   char *p;
   char *q;

   p = str; q = str;
   while ( *p != 0 )
   {
      if ( (*p == SPACE) && (*(p+1) == RBRACE) ) p++;
      else
          *q++ = *p++;
   }
   *q = *p;
   return;
}

void doNDX(idx,str)
int  idx;
char str[];
{
   int  i,j;
   char *p, *q, *r;
   int  cur,e;
   BYTE done;

   j = strlen(str);
   p = &str[0]; p++; q = r = &string[0];
   i = 0; e = 1; cur = E1;
   xref = FALSE; alias = FALSE; crossref = FALSE;
   done = FALSE; curEntry = OTHER_TYPE;
   while ( !done && i<j )
   {
      switch ( *p )
      {
	case DQUOTE:
	     if ( *(p-1)==RSLASH ) 
                  *q++ = *p;		
	     else
		 done = TRUE;
	     break;
        case NL:
	     done = TRUE;
	     break;
        case STAR:
             *q++ = 0; 
             if ( cur!=0 )
	     {
               SkipSpacesReverse(j,q);
	       copyString(idx,cur,string); 
	       cur = 0;
             }
	     q = r; 
	     p++; i++;
             switch ( *p )
	     {
	       case ONE: case TWO: case THREE: case FOUR: case FIVE:
		    cur = GetSubLevel( (*p)-ZERO,*(p+1) ); p++; i++;
	            q = r;
		    break;
               case 'a':  
		    p++; i++; q = r;
		    curEntry = ALIAS_TYPE;
		    alias = TRUE;
		    cur = E1_ALIAS;
		    break;
 	       case MINUS:
		    p++; i++; q = r;
	            curEntry = PRE_TYPE;
		    cur = E1_PRE;
		    break;
 	       case PLUS:
		     p++; i++; q = r;
	             curEntry = POST_TYPE;
		     cur = E1_POST;
		     break;
	       case 'e': 
		    q = r;
		    curEntry = ENTRY_TYPE;
		    cur = E1_CS;
		    break;
	       case 'p': 
		    q = r;
	            cur = CTRLSEQ;
		    break;
	       case 'f':  
	       case 'F':
	       case 't': 
		    q = r;
		    *q++ = *p; *q++ = 0;
		    copyString(idx,PAGE_SPAN,string);
		    q = r;
		    break;
	       case 'x': 
		    if ( crossref )
		    {
		       sprintf(msgbuf,"%s\n *x and *X can't occur together\n",
			       str);
		       syntax_error(msgbuf);
	            }
	            strcpy(string,"x");    copyString(idx,XREF,string);
		    strcpy(string,"99999"); copyString(idx,NUMBER,string);
		    curEntry = XREF_TYPE; xref = TRUE;
		    q = r;
		    cur = CROSS_REF;
		    break;
	      case 'X':
		    if ( xref )
		    {
		       sprintf(msgbuf,"%s\n *x and *X can't occur together\n",
			       str);
		       syntax_error(msgbuf);
	            }
                   strcpy(string,"X");  copyString(idx,XREF,string);
		   crossref = TRUE;
	           cur = CROSS_REF; curEntry = XREF_TYPE;
		   q = r;
		   break;
	      case RSLASH:
		    cur = 0; break;
	      default: 
		    syntax_error(str);
		    cur = 0;
	            break;
	     }
	     break;
        case COMMA:
             p++; i++; *q++ = 0;
             copyString(idx,cur,string);
	     q = r;
	     e++; cur = e*3 - 2;
	     break;
       case LBRACE:
	    switch ( curEntry )
	    {
		case ALIAS_TYPE:	
		case PRE_TYPE:
		case POST_TYPE:
		case ENTRY_TYPE:
		case XREF_TYPE:
		case CROSS_TYPE:			
		     break;
	        default:
		     *q++ = *p; break;
	    }
	    break;
       case RBRACE: 
	    switch ( curEntry )
	    {
		case ALIAS_TYPE:	
		     alias = FALSE; 
		case PRE_TYPE:
		case POST_TYPE:
		case ENTRY_TYPE:
		case XREF_TYPE:
		case CROSS_TYPE:			
                     *q++ = 0; 
                     ReduceSpaces(string);
	             copyString(idx,cur,string); 
	             q = r; 
		     curEntry = OTHER_TYPE; cur = 0;
		     break;
	        default:
		     *q++ = *p; break;
	    }
	    break;
       case RSLASH:
	    if ( *(p+1) == COMMA)
            {
	       p++; i++; *q++ = *p;
	    }
	    else
	      *q++ = *p;
            break;
       default:
	    *q++ = *p;
	    break;
       }
       p++; i++;
    }
   
   *q++ = 0;
   if ( cur!=0 )
   {
      SkipSpacesReverse(j,q);
      copyString(idx,cur,string); 
      cur = 0;
   }
 
   /* post processing of ndxfile */
   /* largest j with <entry_j>    */
   sprintf(string,"%d",e);
   copyString(idx,LARGEST,string);

   CheckAlias(idx);
   
   return;	
}


void doNPG(idx,str)
int  idx;
char str[];
{
   int  i,j,k;
   char *p, *q, *r;
   int  cur;
   char num[10],outstr[10];

   j = strlen(str);
   p = &str[0]; p++; q = r = &string[0]; i = 0; 
   while ( *p != RBRACE && i<j ) 
   {
      num[i++] = *p++;
   }
   num[i] = 0;
   strcpy(outstr,"0000");
   for (k=i; k>=0; k--)
   outstr[4-i+k] = num[k];
   for (k=0; k<5; k++)
   outstr[k];
   copyString(idx,NUMBER,outstr);

   p++; i++; cur = CSNAME; 
   while ( i<j && *p != NL )
   {
      switch ( *p )
      {
       case LBRACE:
	    if ( *(p+1) != RBRACE )
	         q = r;
	    else { p++; i++; cur++; }
	    break;
       case RBRACE: 
	    *q++ = 0;
	    copyString(idx,cur,string);
	    cur++;
	    break;
       default:
	    *q++ = *p;
	    break;
       }
       p++; i++;
   }
   return;	
}

char * CheckAbbrev(s,q)
char s[];
char *q;
{
  int  i,j,len;
  BYTE found;
  char *p;
  
  for (i=0, found=FALSE; i<nabb && !found; i++)
  {
    if ( stricmp(s,abbrev[i]->astr)==0 )
    {
	found = TRUE; p = abbrev[i]->xstr; len = strlen(abbrev[i]->xstr); 
	j = 0;
	while ( *p!=0 && j<len) 
	{
	   *q++ = *p++; j++;
	}
    }
  }
  if ( !found )
  { sprintf(string,"syntax error! '%s' - not an \\abbrev",s); error(string); }
  return ( q );
}



/* preprocess NDX file for defines, abbrevs, page orders */
void PreProc()
{
   char buf[300],str[300];
   int	i,j,len;
   char *p, *q, *r;
   BYTE done, status;

   printMSG("preprocessing...");
   ndef = nabb = npo = 0 ;
   fgets(buf,300,ndxfile);
   while ( !feof(ndxfile) )
   {  
     len = strlen(buf);
     p = &buf[0];
     if ( strnicmp(p,"\\define",7)==0 )
     {
       buf[len-1]=0;
       if ( ndef >= MAX_DEFINES )
       {
	  sprintf(string,
		  "! number of defines (%d) exceeded MAXIMUM allowed (%d)",
		  ndef,MAX_DEFINES);
	  error( string );
       }
       define[ndef] = GetStringSpace(p);
       strcpy(define[ndef],p);
       ndef++;
     }
     else
     {
	if ( strnicmp(p,"\\abbrev",7)==0 )
	{
	   buf[len-1]=0; p+=7;
	   GetAbbrevSpace(nabb);
	   j=0; q  = &buf[len-1];

	   i=0;  /* remove spaces */
	   while ( *p==SPACE && i<len )
	   { p++; i++; }

	   while ( *(p+j)!=LBRACE && *(p+j)!=SPACE && (p+j)<q ) j++; 
	   *(p+j) = 0;
	   abbrev[nabb]->astr = GetStringSpace(p);
	   strcpy(abbrev[nabb]->astr,p);

	   p += j+1; j = len-1;
	   i=0;  /* remove spaces */
	   while ( *p==SPACE && i<len )
	   { p++; i++; }

	   if ( *p==LBRACE ) p++;
	   
	   while ( *q!=RBRACE && q>p ) q--;
	   *q = 0;
	   abbrev[nabb]->xstr = GetStringSpace(p);
	   strcpy(abbrev[nabb]->xstr,p);
	   nabb++;
	}
	else
	{
           i=0;  /* remove spaces */
	   while ( *p==SPACE && i<len )
	   { p++; i++; }
	 
	   if ( strnicmp(p,"\\pageorder",10)==0 )
	   {
	     buf[len-1]=0; 
	     p+=10;
	     RemoveSpaces(p);
	     GetPageOrderSpace(npo);
	     /* get style */
	     j=0; q  = &buf[len-1];
	     while ( *(p+j)!=LBRACE && (p+j)<q ) 
	     {   j++; }
	     if ( (p+j) >= q )
	       syntax_error(buf);
	     *(p+j) = 0;
	     PO[npo]->style = GetStringSpace(p);
	     strcpy(PO[npo]->style,p);
	     PO[npo]->nstyle = (BYTE) strlen(p);

	     /* get pre page material */
	     p += j+1; j=0;
	     while ( *(p+j)!=RBRACE && (p+j)<q ) j++; 
	     if ( (p+j) >= q )
		syntax_error(buf);
	     *(p+j) = 0;
	     if ( j==0 )
	     { PO[npo]->pre = NULLPTR;  }
	     else
	     { PO[npo]->pre = GetStringSpace(p); strcpy(PO[npo]->pre,p); }
	     PO[npo]->npre = (BYTE) strlen(p);

	     /* get post page material */
	     p += j+2; j=0;
	     while ( *(p+j)!=RBRACE && (p+j)<q ) j++; 
	     if ( (p+j) >= q )
		syntax_error(buf);
	     *(p+j) = 0;
	     if ( j==0 )
	     { PO[npo]->post = NULLPTR; }
	     else
	     { PO[npo]->post = GetStringSpace(p); strcpy(PO[npo]->post,p); }
	     PO[npo]->npost = (BYTE) strlen(p);
	     
	     /* get page order */
	     p += j+1; 
	     if ( *p==LBRACE ) 
	     {	p++; q--; *q=0;  }
	     PO[npo]->order =(BYTE) atoi(p);
	     npo++;
           } /* endif page order */
	   else
	   {
	    if ( *p!=NL && *p!=SPACE )
	    {
	     q = &string[0];
	     done = FALSE; status = FALSE; i = 0;
	     *q++ = *p++;
	     while ( i<len )
	     {
	     switch ( *p )
	     {
	       case STAR:
		    if ( *(p+1)==RSLASH )
		    {
		      r = &str[0]; done = FALSE;
		      *r++ = *p++; *r++ = *p++;
		      while ( !done )
		      {
		       switch ( *p )
	               {
			case SPACE: case DQUOTE: case COMMA: case LBRACE:
			case RBRACE: case LBRACKET: case RBRACKET:
			case LPAREN: case RPAREN: case QUOTE: case DOLLAR:
			case TILDE: case EXCLAIM: case CARET:
			case MINUS: case USCORE: case PLUS: case EQUAL:
			case COLON: case SEMI: case LQUOTE: case GREATER:
			case LESS: case QUESTION: case SLASH: case BAR:
			case STAR: case RSLASH: case PERIOD:
			     *r++=0;
			     done = TRUE;
			     break;
		        default:
			     *r++ = *p++; i++;
		             break;
	               } /* switch */
	              }  /* while */
		      q=CheckAbbrev(str,q);
		    } /* if */
		    else
		    {  *q++ = *p++; i++; }
		    break;
	       default:
		    *q++ = *p++; i++;
		    break;
	     } /* switch */
          } /* while */
	  *q++ = 0;
	  PutString( string, xxxfile );
          } /* not NL or SPACE */
        } /* others */
       } /* else pageorders */
     } /* else abbrevs */
     fgets(buf,300,ndxfile);
   } /* while */
   return;	
}




/**********************************************************************/
/* BuildProc: read in contents of .ndx file into internal data buffers*/
/* Inputs   : .ndx file handle                                        */
/* Output   : Entries                                                 */
/**********************************************************************/
#ifndef SEEK_END
#define SEEK_END 2
#define SEEK_CUR 1
#define SEEK_SET 0
#endif
void BuildProc( void )
{
   char abuf[300];
   char bbuf[300];
   int  i;

   fseek(xxxfile, 0L, SEEK_SET);
   nitems = 0;
   fgets(abuf,300,xxxfile);
   while( !feof(xxxfile) )
   {
      nitems++;
      fgets( abuf,300,xxxfile );
   }

   nitems/=2;
   fseek(xxxfile, 0L, SEEK_SET);
   GetFieldSpace(0);

   for (i=1; i<=nitems; i++ )
   {
     fgets(abuf,300,xxxfile);
     fgets(bbuf,300,xxxfile);
     
     if ( bbuf[0]!='{' )
     {
          sprintf( msgbuf,"\n! Entry ->\n%s does not have a following \"{...}{...}{...}\" line.", abuf );
	  error( msgbuf );
     }
     
     GetFieldSpace(i);
     ScanEntry( abuf );
     doNDX(i,abuf);	
     doNPG(i,bbuf);
     
   };

   return;
}



/**********************************************************************/
/* ScanEntry: scan entry line and delete entry delimiters             */
/* Inputs   : line                                                    */
/* Output   : line                                                    */
/**********************************************************************/
void ScanEntry( char line[] )
{
int   len,i;
  if ( line[0] == RSLASH )
  {
     sprintf( msgbuf,"Entry ->\n%s begins with a '\\'.", line );
     error( msgbuf );
  }
  else
    line[0] = SPACE;
  
  len = strlen( line );
  i = strlen(line) - 2;
  while( i>0 && line[i] == SPACE )
  {
    i--;
  }
  line[i] = SPACE;
  line[i] = NL;
  return;
  
}



int PageOrderSort(i,j)
int i, j;
{
int stat,n,k;
int i_order, j_order;

    i_order=GetPageOrder(i);
    j_order=GetPageOrder(j);

    stat = 0;
    for (n=PageOrderFirst; n<=PageOrderLast && stat==0; n++)
    {
	 k = PageOrder[n];
	 stat=strcmp(Entry[i].item->fields[k],Entry[j].item->fields[k]);
	 switch ( k )
	 {	
           case CSNAME:
	   case PREFIX:
	     if ( stat!= 0 ) 
	     {
	       if ( i_order < j_order ) return( -1 );
	       if ( i_order > j_order ) return(  1 );
	       return ( stat );
             }
             break;
	   case NUMBER:
	     if ( stat != 0 ) 
	     {
		  if ( (i_order == j_order) && (i_order == MAX_PAGEORDER) )
		       return( stat );
		  if ( (i_order == MAX_PAGEORDER) && (j_order < i_order) )
		       return( 1 );
	          if ( (j_order == MAX_PAGEORDER) && (i_order < j_order) )
		       return( -1 );
		  return( stat );
	     }
	     else
	     {
	        if ( i_order < j_order ) return( -1 );
	        if ( i_order > j_order ) return(  1 );
	     }
	     break;
	   case POSTFIX:
	     if ( stat!= 0 ) 
	     {
	       if ( i_order < j_order ) return( -1 );
	       if ( i_order > j_order ) return(  1 );
	       return ( stat );
             }
             break;
	   default:
             break;
        } /* switch */

     } /* for */
   return( stat );	
}

int CompareStrings(i,j)
int  i,j;
{
int n,k;	
int stat;

   stat=0;
   for (n=FirstOrder; n<=LastOrder && stat==0; n++)
   {
     k = SortingOrder[n];
     stat=stricmp(Entry[i].item->fields[k],Entry[j].item->fields[k]);
   }

   if ( stat==0 )
   {
      stat = PageOrderSort(i,j);
   } /* if */
   
   return( stat );
}


int GetPageOrder(idx)
int idx;
{
int i,done;	
int order;
   order = MAX_PAGEORDER;
   for (i=0,done=FALSE; i<npo && !done; i++)
   {
     if (  strncmp(Entry[idx].item->fields[CSNAME],PO[i]->style,
	            PO[i]->nstyle)==0
	&& strncmp(Entry[idx].item->fields[PREFIX],PO[i]->pre,
		    PO[i]->npre)==0
	&& strncmp(Entry[idx].item->fields[POSTFIX],PO[i]->post,
		    PO[i]->npost)==0 )
     {
       order = PO[i]->order; done = TRUE;
     }
   }
   return(order);
}


void SwapStrings(cur,nxt)
int  cur,nxt;
{
   int   k;
   char *p;
   for (k=E1; k<=CROSS_REF; k++)
   {
	p = Entry[cur].item->fields[k];
	Entry[cur].item->fields[k] = Entry[nxt].item->fields[k];
	Entry[nxt].item->fields[k] = p;
   }
   return;
}

void SortProc()
{
int  i,j,n;
FILE *f;
int  gap;

  printMSG("sorting...");
  
  /* Shell sort */
  n = nitems+1;
  for ( gap=n/2; gap>0; gap/=2 )
  {
     for ( i=gap; i<n; i++ )
     {
	for ( j=i-gap; j>0 && CompareStrings(j,j+gap) > 0; j-=gap )
	{
	    SwapStrings(j,j+gap);
	}
     }
  }
  
  /* write out sorted list - this is for debugging only */
  if ( idxfile )
  {
    f = fopen(idxname,"w");
    if ( f==NULL )
    { sprintf(string,"File write error %s",idxname); error(string); }
    for (i=1; i<=nitems; i++)
    { 
	BuildString(i); 
	PutString( string, f ); PutByte( NL, f);
    }
    fclose(f);
  }

  return;	
}


int CompareStringsPO(i,j)
int  i,j;
{
int stat;
   stat = PageOrderSort(i,j);
   return( stat );
}


/**********************************************************************/
/* Sort Page Numbers		                                      */
/* Inputs: beginning entry, ending entry                              */
/* Output: Sorted list of page numbers entries                        */
/**********************************************************************/
void SortPageNumber(beg,end)
 int beg, end;
{
int  i,j,k,n;
int  change,status;

  /* Check for boundary conditions */
  if ( ( end - beg )  >= MAX_PAGEENTRY )
  {
     sprintf(string,"! page line entries (%d) exceeded MAXIMUM allowed (%d)",
	     end-beg,MAX_PAGEENTRY );
     error( string );
  }
  
  n = 0;
  for (i=beg; i<end; i++)
  {
     if ( *(Entry[i].item->fields[XREF])!='x' )
     {
       SubPageOrder[n] = i; n++;
     }
  }

  /* Refined Bubble sort - for simplicity  
     Note: we only need to sort a subset of the entries. 
           Sorting is done using an array of indices without
	   physically swapping entries. */
  change = TRUE;	
  for (i=0; i<n && change; i++)
  {
     change = FALSE;
     for (j=0;j<n-1;j++)
     {
       status = CompareStringsPO(SubPageOrder[j],SubPageOrder[j+1]);
       if ( status>0 )
       { 
	 k = SubPageOrder[j+1];
	 SubPageOrder[j+1] = SubPageOrder[j];
	 SubPageOrder[j] = k;
	 change=TRUE; }
     }
  }

  return;
}


BYTE CheckLevel(cur,idx,level)
int  cur,idx;
BYTE level;
{
BYTE entry_i, pre_i, post_i, alias_i, cs_i;

  switch ( level )
  {
     case LEVEL1:
          entry_i = E1; pre_i = E1_PRE; post_i = E1_POST;
          alias_i = E1_ALIAS; cs_i = E1_CS;
	  break;
     case LEVEL2:
          entry_i = E2; pre_i = E2_PRE; post_i = E2_POST;
          alias_i = E2_ALIAS; cs_i = E2_CS;
	  break;
     case LEVEL3:
          entry_i = E3; pre_i = E3_PRE; post_i = E3_POST;
          alias_i = E3_ALIAS; cs_i = E3_CS;
	  break;
     case LEVEL4:
          entry_i = E4; pre_i = E4_PRE; post_i = E4_POST;
          alias_i = E4_ALIAS; cs_i = E4_CS;
	  break;
     case LEVEL5:
          entry_i = E5; pre_i = E5_PRE; post_i = E5_POST;
          alias_i = E5_ALIAS; cs_i = E5_CS;
	  break;
  }
 
  if (  strcmp(Entry[cur].item->fields[entry_i],
	Entry[idx].item->fields[entry_i])==0
     && strcmp(Entry[cur].item->fields[pre_i],
	Entry[idx].item->fields[pre_i])  ==0
     && strcmp(Entry[cur].item->fields[post_i],
	Entry[idx].item->fields[post_i]) ==0
     && strcmp(Entry[cur].item->fields[alias_i],
	Entry[idx].item->fields[alias_i])==0
     && strcmp(Entry[cur].item->fields[cs_i],
	Entry[idx].item->fields[cs_i])   ==0
     )
     return(TRUE); 
  else
     return(FALSE);
}


BYTE GetD2(cur,idx)
int  cur;
int  idx;
{
  if ( CheckLevel( cur,idx,LEVEL1 ) )
  {
      if ( CheckLevel( cur,idx,LEVEL2 ) )	
      {
          if ( CheckLevel( cur,idx,LEVEL3)  )
	  {
	     if ( CheckLevel( cur,idx,LEVEL4 ) )
	     {
		 if ( CheckLevel ( cur,idx,LEVEL5 ) )
		      return(LEVEL5);
	         else return(LEVEL4);
	     }
	     else return(LEVEL3);
	  }
	  else return(LEVEL2);
      }
      else return(LEVEL1);
   }
   else return(LEVEL0);

   return(LEVEL0);	
}




void GetArg(idx,arg,pre,cs,entry,post,alias)
int  idx;
char arg[];
BYTE pre,cs,entry,post,alias;
{
   if ( Entry[idx].item->fields[alias]!=NULLPTR )
	 entry = alias;

   if ( Entry[idx].item->fields[cs]==NULLPTR )
   {
       if ( Entry[idx].item->fields[pre]==NULLPTR
	 && Entry[idx].item->fields[post]==NULLPTR )
            sprintf(arg,"{%s}",Entry[idx].item->fields[entry]);
       else
           sprintf(arg,"{{%s}{%s}{%s}}",Entry[idx].item->fields[pre],
	       Entry[idx].item->fields[entry],Entry[idx].item->fields[post]);
   }
   else
   {
       sprintf(arg,"{{%s}{%s{%s}}{%s}}",Entry[idx].item->fields[pre],
	       Entry[idx].item->fields[cs],
	       Entry[idx].item->fields[entry],Entry[idx].item->fields[post]);
   }

   RemoveEmptySet(arg);

   return;
}


void DoNormal(idx,arg)
int  idx;
char arg[];
{
char *p;
char str[80];
int  pn;

   pn = atoi(Entry[idx].item->fields[NUMBER]);
   strcpy( str, Entry[idx].item->fields[CSNAME] );
   p = &str[0];
   if ( strncmp(p,"\\arabic",7)==0 ) *p=0;

   if ( Entry[idx].item->fields[CTRLSEQ]==NULLPTR )
   {
      if ( Entry[idx].item->fields[PREFIX]==NULLPTR
	&& Entry[idx].item->fields[POSTFIX]==NULLPTR )
      {
	  if ( *p==0 )
  	       sprintf(arg,"{%d}",pn);
          else
  	       sprintf(arg,"{%s{%d}}",p,pn);		  
      }
      else
      {  
	  if ( *p==0 )
              sprintf(arg,"{{%s}{%d}{%s}}",
	              Entry[idx].item->fields[PREFIX],pn,
		      Entry[idx].item->fields[POSTFIX]);
	  else
              sprintf(arg,"{{%s}{%s{%d}}{%s}}",
                      Entry[idx].item->fields[PREFIX],p,pn,
		      Entry[idx].item->fields[POSTFIX]);
      }
   }
   else
   {
      if ( Entry[idx].item->fields[PREFIX]==NULLPTR 
	&& Entry[idx].item->fields[POSTFIX]==NULLPTR )
      {
	  if ( *p == 0 )
               sprintf(arg,"{%s{%d}}",Entry[idx].item->fields[CTRLSEQ],pn);
          else
               sprintf(arg,"{%s{%s{%d}}}",Entry[idx].item->fields[CTRLSEQ],
		       p,pn);
      }
      else
      {
	  if ( *p == 0 )
              sprintf(arg,"{%s{{%s}{%d}{%s}}}",
	              Entry[idx].item->fields[CTRLSEQ],
                      Entry[idx].item->fields[PREFIX],pn,
		      Entry[idx].item->fields[POSTFIX]);
	  else
             sprintf(arg,"{%s{{%s}{%s{%d}}{%s}}}",
		     Entry[idx].item->fields[CTRLSEQ],
                     Entry[idx].item->fields[PREFIX],p,pn,
		     Entry[idx].item->fields[POSTFIX]);
      }
   }
   return;
}


void DoVariant(idx,arg)
int  idx;
char arg[];
{
char *p;
int  pn;
char str[80];

   pn = atoi(Entry[idx].item->fields[NUMBER]);
   strcpy(str,Entry[idx].item->fields[CSNAME]);
   p = &str[0];
   if ( strncmp(p,"\\arabic",7)==0 ) *p=0;

   if ( Entry[idx].item->fields[PREFIX]==NULLPTR 
     && Entry[idx].item->fields[POSTFIX]==NULLPTR )
   {
      if ( *p==0 )
  	   sprintf(arg,"{%s }{%d}",Entry[idx].item->fields[CTRLSEQ],pn);
      else
  	   sprintf(arg,"{%s }{%s{%d}}",Entry[idx].item->fields[CTRLSEQ],p,pn);
   }
   else
   {  
      if ( *p==0 )
           sprintf(arg,"{%s }{{%s}{%d}{%s}}",
	           Entry[idx].item->fields[CTRLSEQ],
                   Entry[idx].item->fields[PREFIX],pn,
	           Entry[idx].item->fields[POSTFIX]);
      else
           sprintf(arg,"{%s }{{%s}{%s{%d}}{%s}}",
	           Entry[idx].item->fields[CTRLSEQ],
		   Entry[idx].item->fields[PREFIX],
	           p,pn,Entry[idx].item->fields[POSTFIX]);
   }
   return;
}


void  PrintErrorMSG()
{
int i;

   PutString( "%% ",xdxfile );
   for (i=0; i<72; i++) 
	PutByte('/',xdxfile);
   PutByte( NL, xdxfile );
   PutString("%%\n",xdxfile);
   PutString( msgbuf,xdxfile );
   PutString("%%\n",xdxfile);
   PutString("%% ",xdxfile); 
   for (i=0; i<72; i++) 
	PutByte('\\',xdxfile);
   PutByte( NL, xdxfile);

   return;
}


int DupPageFormat(idx,arg)
int idx;
char arg[];
{
int  i,level;
BYTE done;
char tmpbuf[300];

  for (i=idx-1, done=FALSE; i>0 && !done; i--)
  {
    level = GetD2(i,idx);
    if ( level==LEVEL5 ) 
    {
      if ( strcmp(Entry[idx].item->fields[NUMBER],
	        Entry[i].item->fields[NUMBER])==0 
	&&  strcmp(Entry[idx].item->fields[CTRLSEQ],
	           Entry[i].item->fields[CTRLSEQ])!=0 )
      {
       RemoveEmptySet(arg);
       sprintf(msgbuf,"%%  \\Page %s\n",arg);
       sprintf(tmpbuf,
	    "%%  Duplicate page number formatted differently\n");
       strcat(msgbuf,tmpbuf);
       PrintErrorMSG();
       done = TRUE;
       return( FALSE );
     } /* if */
   } /* if - level */
   else 
      done = TRUE;
  } /* for */
  return(TRUE);
}


/**********************************************************************/
/* Find The Last matching t entry                                     */
/* Inputs: index into current entry                                   */
/* Output: TRUE if found, FALSE if not                                */
/**********************************************************************/
int FindLastT(idx)
int idx;
{
int i,level,done;

  Tindex = 0; done = FALSE; 
  level = GetD2(idx-1,idx);
  for ( i=idx-1;
        ( i>0 ) && ( level==LEVEL5 ) && !done ;
	i-- )
  {
    done = TRUE;
    if (   strcmp(Entry[idx].item->fields[NUMBER],
                 Entry[i].item->fields[NUMBER])==0 
	&& strcmp(Entry[idx].item->fields[PAGE_SPAN],
                 Entry[i].item->fields[PAGE_SPAN])==0 )
    {
       Tindex = i; done = FALSE;
    }
    level = GetD2(i-1,idx);
    
  }

  if ( Tindex != 0 )
       return( TRUE );
  else
       return( FALSE );

}



BYTE GetPageNum(idx)
int  idx;
{
char type;
char arg[300];
int  status;
char tmpbuf[300];

   type = *(Entry[idx].item->fields[PAGE_SPAN]); skippage = FALSE;
   switch ( type )
   {
     case 'F':
	DoVariant(idx,arg);
	if ( PageType=='f' || PageType=='F' )
	{
          sprintf(msgbuf,"%%  \\Pagespan %s\n",arg);
	  sprintf(tmpbuf,
	          "%%  Page span starting at %s within span starting at %d\n",
		  arg,atoi(Entry[PageIndex].item->fields[NUMBER]));	
	  strcat(msgbuf,tmpbuf);
	  PrintErrorMSG();
	  skippage = TRUE;
	  return(FALSE);
	}
	
	PageType = type ; PageIndex = idx;
        PageSpan = TRUE;
    break;
  case 'f': 
      DoNormal(idx,arg);	  
      if ( PageType=='f' || PageType=='F' )
      {
       sprintf(msgbuf,"%%  \\Pagespan %s\n",arg);
       sprintf(tmpbuf,
	       "%%  Page span starting at %s within span starting at %d\n",
	        arg,atoi(Entry[PageIndex].item->fields[NUMBER]));	
       strcat(msgbuf,tmpbuf);
       PrintErrorMSG();
       skippage = TRUE;
       return(FALSE);
      }
      
      PageType = type ; PageIndex = idx;
      PageSpan = TRUE;
    break;
  case 't':
    switch ( PageType ) 
    {
      case 'F': 
	DoVariant(idx,arg); 
        break;
      case 'f': 
	DoNormal(idx,arg); 
        break;
      default: 
	DoNormal(idx,arg); 

        if ( FindLastT(idx)  )
	{
	 sprintf(msgbuf,"%%  \\Topage %s\n",arg);
	 sprintf(tmpbuf,
	        "%%  Span ending at %s also ending at {%s {%d}}\n",
		arg,
		Entry[Tindex].item->fields[CTRLSEQ],
		atoi(Entry[Tindex].item->fields[NUMBER]));
	 strcat(msgbuf,tmpbuf);
	 PrintErrorMSG();
	 skippage = TRUE;
         PageType = 0; PageIndex = 0; PageSpan = FALSE;
	 return(FALSE); 
	}
	
	sprintf(msgbuf,"%%  \\Topage %s\n",arg);
	sprintf(tmpbuf,
	        "%%  Page span ending at %s has no starting page\n",
		arg);
	strcat(msgbuf,tmpbuf);
	PrintErrorMSG();
	skippage = TRUE;
        PageType = 0; PageIndex = 0; PageSpan = FALSE;	   
	return(FALSE); 
      break;
    } /* switch */

    break;
  default: 
     DoNormal(idx,arg); 
     if ( PageSpan )
     {
       /* Drop it if within page span */
       status = stricmp(Entry[idx].item->fields[CTRLSEQ],
	                Entry[PageIndex].item->fields[CTRLSEQ]);
       if ( status == 0 )
	  return( FALSE );
       else
       {
         sprintf(msgbuf,
	         "%%  Page %s%s within span starting at {%s {%d}}\n",
		 Entry[idx].item->fields[CTRLSEQ],arg,
		 Entry[PageIndex].item->fields[CTRLSEQ],
		 atoi(Entry[PageIndex].item->fields[NUMBER]));
	PrintErrorMSG();
	skippage = TRUE;	
	return( FALSE );
       } /* else */
     } /* if */
     status = DupPageFormat(idx,arg);
     if ( !status )
	   return( FALSE );
     break;
  } /* switch */
   
  RemoveEmptySet(arg);

  strcpy(prevnum,pagenum);
  strcpy(pagenum,arg);
   
  return(TRUE);
 
}


void PutPageNum(idx)
int  idx;
{
char c;
char str[80];

   if ( skippage ) return;
   
   c =  *(Entry[idx].item->fields[PAGE_SPAN]) ;
   switch ( c )
   {
      case 'f':
	   sprintf(str,"\\Pagespan %s\n",pagenum);
	   PutString( str, xdxfile );
	   break;
      case 'F':
	   sprintf(str,"\\PageSpan %s\n",pagenum);
	   PutString( str, xdxfile );
	   break;
      case 't':
	   sprintf(str,"\\Topage %s\n",pagenum);
	   PutString( str, xdxfile );
	   if ( strcmp( Entry[idx].item->fields[CTRLSEQ],
		        Entry[PageIndex].item->fields[CTRLSEQ] ) !=0 )
	   {
		sprintf(msgbuf,"%%  \\Page span from {%s {%d}} to %s\n",
			Entry[PageIndex].item->fields[CTRLSEQ],
			atoi(Entry[PageIndex].item->fields[NUMBER]),
			pagenum);
		PrintErrorMSG();
	   }
           PageType = 0; PageIndex = 0; PageSpan = FALSE;
	   break;	      
        default:	      
	   sprintf(str,"\\Page %s\n",pagenum);
	   PutString( str, xdxfile );
           break;
   }
   return;
}


void GetArgs(idx,arg1,arg2,arg3,arg4,arg5)
int  idx;
char *arg1, *arg2, *arg3, *arg4, *arg5;
{
   GetArg(idx,arg1,E1_PRE,E1_CS,E1,E1_POST,E1_ALIAS);
   GetArg(idx,arg2,E2_PRE,E2_CS,E2,E2_POST,E2_ALIAS);
   GetArg(idx,arg3,E3_PRE,E3_CS,E3,E3_POST,E3_ALIAS);
   GetArg(idx,arg4,E4_PRE,E4_CS,E4,E4_POST,E4_ALIAS);
   GetArg(idx,arg5,E5_PRE,E5_CS,E5,E5_POST,E5_ALIAS);
   return;
}


int DupEntry( idx, cur )
int idx,cur;
{
  int i,k,stat;
  
 
  for (i=cur; i<idx; i++)
  {
    stat=0;
    
    for (k=E1; k<=CROSS_REF && stat==0; k++)
    {
     stat=stricmp(Entry[i].item->fields[k],Entry[idx].item->fields[k]);
    }
    
    if ( stat == 0 )
	 return( TRUE );
    
  } /* for */
  
  if ( stat == 0 )
       return( TRUE );
  else return ( FALSE );
  
} /* end - DupEntry */


int DupXref( idx, cur )
int idx,cur;
{
  int i;
  for (i=idx; i<cur; i++)
  {
     if ( stricmp( Entry[i].item->fields[CROSS_REF], 
	           Entry[cur].item->fields[CROSS_REF] ) == 0 )
	  return( TRUE );
  }
  
  return ( FALSE );
  
} /* end - DupXref */


void xxref_proc(idx)
int  idx;
{
int  i,d2,nxt,level,n;
BYTE done;
char xtype;
int  status;

   /* put out 1 cross reference */
   GetArgs(idx,arg1,arg2,arg3,arg4,arg5);
   d2 = GetD2(idx,idx-1);
   sprintf(msgbuf,"\\Entry %s%d%s%s%s%s%s\n",
           Entry[idx].item->fields[LARGEST],d2,arg1,arg2,arg3,arg4,arg5);
   PutString( msgbuf, xdxfile );
   
   sprintf(msgbuf,"\\Xref {\\See {%s}}\n",
	   Entry[idx].item->fields[CROSS_REF]);
   PutString( msgbuf, xdxfile );
   
   
   /* Gather all the cross references */
   nxt = 1; done = FALSE;
   while ( !done && (idx+nxt)<=nitems )
   {
     level = GetD2(idx,idx+nxt);
     xtype = (char) *(Entry[idx+nxt].item->fields[XREF]);
     if ( level==LEVEL5 && ( xtype=='X' || xtype=='x' ) )
     {
       if ( !DupXref(idx, idx+nxt) )
       {
            sprintf(msgbuf,"\\Morexref {\\See {%s}}\n",
	            Entry[idx+nxt].item->fields[CROSS_REF]);
	    PutString( msgbuf, xdxfile );
       }
       nxt++;
     }
     else
     {
        done = TRUE;
     }
   }

   SortPageNumber(idx,idx+nxt);
   n = 0;
   for ( i=idx; i<idx+nxt; i++)
   {
     xtype = (char) *(Entry[i].item->fields[XREF]);
     if ( xtype != 'x' )
     {
       status = GetPageNum(SubPageOrder[n]);
       if ( status ) PutPageNum(SubPageOrder[n]);
       n++;
     }
   }

   /* put out cross references again */
   sprintf(msgbuf,"\\Xref {\\See {%s}}\n",
           Entry[idx].item->fields[CROSS_REF]);
   PutString( msgbuf, xdxfile );
     
     
   for ( i=idx+1; i<idx+nxt; i++)
   {
     level = GetD2(i,idx);
     xtype = (char) *(Entry[i].item->fields[XREF]);
     if ( level==LEVEL5 && ( xtype=='X' || xtype=='x' ) )
     {
       if ( !DupXref(idx,i) )
       {
            sprintf(msgbuf,"\\Morexref {\\See {%s}}\n",
	            Entry[i].item->fields[CROSS_REF]);
	    PutString( msgbuf, xdxfile );
       }
     } /* if */
   } /* for */
   
   curIndex = idx + nxt;
   return;
} /* xxref_proc */


void xref_proc(idx)
int  idx;
{
int  nxt,level,d2,i;
BYTE done;
char xtype;
BYTE ctype;
   
   /* CASE I or CASE II */
   nxt = 1; done = FALSE; ctype = 1;
   while ( !done && (idx+nxt)<=nitems )
   {
     level = GetD2(idx+nxt,idx);
     xtype = (char) *(Entry[idx+nxt].item->fields[XREF]);
     if ( level==LEVEL5 && ( xtype=='X' || xtype =='x') )
     {
       if ( xtype == 'X' )
            ctype = 2;
       nxt++;
     }
     else
     {
        done = TRUE;
     }
   } /* while */

 /* CASE I */
 if ( ctype == 1 )
 {
   /* put out 1 cross reference */
   GetArgs(idx,arg1,arg2,arg3,arg4,arg5);
   d2 = GetD2(idx,idx-1);
   
   sprintf(msgbuf,"\\Entryxref %s%d%s%s%s%s%s{\\See {%s}}\n",
           Entry[idx].item->fields[LARGEST],d2,arg1,arg2,arg3,arg4,arg5,
 	   Entry[idx].item->fields[CROSS_REF]); 
   PutString( msgbuf, xdxfile );
   

   /* Gather up all the cross references */
   for ( i=idx+1; i<idx+nxt; i++ )
   {
     level = GetD2(i,idx);
     xtype = (char) *(Entry[i].item->fields[XREF]);
     if ( level==LEVEL5 && xtype=='x' )
     {
       if ( !DupXref(idx,i) )
       {
               sprintf(msgbuf,"\\Morexref {\\See {%s}}\n",
		       Entry[i].item->fields[CROSS_REF]);
	       PutString( msgbuf, xdxfile );
       }
     }
     else
     {
        done = TRUE;
     }
   } /* while */
   
   curIndex = idx + nxt;
   
 } /* if */
 
 /* CASE II */
 else
 {
   xxref_proc( idx );
 }
 
   return;
} /* end  - xref_proc */


void OutputProc(idx,arg1,arg2,arg3,arg4,arg5)
int  idx;
char *arg1, *arg2, *arg3, *arg4, *arg5;
{
int d2, status;

   d2 = GetD2(idx,idx-1);
   if ( d2==LEVEL5 )
   {
      if ( !DupEntry( idx, idx-1 ) )
      {
        status = GetPageNum(idx);
        if ( status )  PutPageNum(idx);
      }
   }
   else
   {
     sprintf(msgbuf,"\\Entry %s%d%s%s%s%s%s\n",
             Entry[idx].item->fields[LARGEST],d2,arg1,arg2,arg3,arg4,arg5);
     PutString( msgbuf, xdxfile );
     status = GetPageNum(idx);
     if ( status ) PutPageNum(idx);
   }
   return;	
} /* end - OutputProc */


void other_proc(idx)
int  idx;
{
int  i,d2,nxt,level,n;
BYTE done,first;
char xtype,ctype;
int  status;


   /* this is the last line */
   if ( idx+1 > nitems )
   {
     /* finish up and exits */
     GetArgs(idx,arg1,arg2,arg3,arg4,arg5);
     OutputProc(idx,arg1,arg2,arg3,arg4,arg5);
     curIndex++;
     return;
   }

   /* Get all the LEVEL5 entries */
   nxt = 1; done = FALSE; ctype = FALSE;
   while ( !done && (idx+nxt)<=nitems )
   {
     level = GetD2(idx+nxt,idx);
     xtype = (char) *(Entry[idx+nxt].item->fields[XREF]);
     if ( level==LEVEL5 )
     {
	if ( xtype == 'X' || xtype == 'x' )
	   ctype = TRUE;
        nxt++;
     }
     else
     {
        done = TRUE;
     }
   }

   if ( !ctype )
   {
     /* Not a cross reference, so we output line and return */
     GetArgs(idx,arg1,arg2,arg3,arg4,arg5);
     OutputProc(idx,arg1,arg2,arg3,arg4,arg5);
     curIndex++;
     return;
   }
   
   /* put out entry first */
   GetArgs(idx,arg1,arg2,arg3,arg4,arg5);
   d2 = GetD2(idx,idx-1);
   sprintf(msgbuf,"\\Entry %s%d%s%s%s%s%s\n",
           Entry[idx].item->fields[LARGEST],d2,arg1,arg2,arg3,arg4,arg5);
   PutString( msgbuf, xdxfile );

   /* Gather all the cross references */
   first = TRUE;
   for (i=idx+1; i<idx+nxt; i++ )
   {
     level = GetD2(i,idx);
     xtype = (char) *(Entry[i].item->fields[XREF]);
     if ( level==LEVEL5 && ( xtype=='X' || xtype=='x' ) )
     {
       if ( !DupXref(idx,i) )
       {
         if ( first )
         {
	   first = FALSE;
           sprintf(msgbuf,"\\Xref {\\See {%s}}\n",
	           Entry[i].item->fields[CROSS_REF]);
	   PutString( msgbuf, xdxfile );
         } /* if */
         else
	 {
           sprintf(msgbuf,"\\Morexref {\\See {%s}}\n",
	           Entry[i].item->fields[CROSS_REF]);
	   PutString( msgbuf, xdxfile );
         } /* else */
       } /* if - dupXref */
     } /* if - level */
   } /* for */


   /* We need to sort a subset of the entries base on page order,
      viz, entries with LEVEL5 */
   SortPageNumber(idx,idx+nxt);
   
   n = 0;
   for ( i=idx; i<idx+nxt; i++)
   {
     xtype = (char) *(Entry[i].item->fields[XREF]);
     switch ( xtype )
     {
      case 'x':
	   break;
      case 'X':
      default:
        status = GetPageNum(SubPageOrder[n]);
        if ( status ) PutPageNum(SubPageOrder[n]);
	n++;
	break;
    } /* switch */
   } /* for */

   /* put out cross references again */
   first  = TRUE;
   for ( i=idx+1; i<idx+nxt; i++)
   {
     level = GetD2(i,idx);
     xtype = (char) *(Entry[i].item->fields[XREF]);
     if ( level==5 && ( xtype=='X' || xtype=='x' ) )
     {
       if ( !DupXref(idx,i) )
       {
         if ( first )
         {
          sprintf(msgbuf,"\\Xref {\\See {%s}}\n",
	          Entry[i].item->fields[CROSS_REF]);
	  PutString( msgbuf, xdxfile );
	  first = FALSE;
         } /* if */
         else
	 {
          sprintf(msgbuf,"\\Morexref {\\See {%s}}\n",
	          Entry[i].item->fields[CROSS_REF]);
	  PutString( msgbuf, xdxfile );
         } /* else */
       } /* if */
      } /* if */
   } /* for */

   curIndex = idx + nxt;
   return;
} /* end - other_proc */


void TeXPut(idx)
int  idx;
{
char xtype;

    curLetter = (char) toupper(*(Entry[idx].item->fields[E1]));
    if ( curLetter != preLetter )
    {
         sprintf(msgbuf,"\n\\LETTER %c\n\n",curLetter);
	 PutString( msgbuf, xdxfile );
         preLetter = curLetter;
    }

    xtype = (char) *(Entry[idx].item->fields[XREF]);
    
    switch( xtype )
    {
       case 'x':
	    xref_proc(idx);
	    break;
       case 'X':
	    xxref_proc(idx);
	    break;
       default:
	    other_proc(idx);
	    break;
    }
    
    return;
} /* end - TeXPut */



void TeXOut()
{
  int  i;
  
  printMSG("writing output...");
  preLetter = 0;
  for (i=0; i<ndef; i++)
  {
     sprintf(msgbuf,"%s\n",define[i]);
     PutString( msgbuf, xdxfile );
  } /* for */

  curIndex = 1;
  while ( curIndex <= nitems )
  {
     TeXPut( curIndex ); 
  }
  return;
} /* end - TexOut */


/**********************************************************************/
/* Move Entries			                                      */
/* Inputs: from, to			                              */
/* Output: none					                      */
/**********************************************************************/
void MoveEntry(from,to)
 int from,to;
{
int k;

  /* return if both are the same entry */
  if ( from == to )
       return;

  for (k=E1; k<=CROSS_REF; k++)
  {
     Entry[to].item->fields[k] = Entry[from].item->fields[k];
  }
  
  return;
} /* end - MoveEntry */


/**********************************************************************/
/* Free Entry			                                      */
/* Inputs: idx				                              */
/* Output: none					                      */
/**********************************************************************/
void FreeEntry(idx)
 int idx;
{
int j;

  if ( Entry[idx].item!=NULL )
  {
    for ( j=E1; j<=CROSS_REF; j++ )
    {
     if ( Entry[idx].item->fields[j]!=NULLPTR )
	  free( Entry[idx].item->fields[j] );
     Entry[idx].item->fields[j] = NULLPTR;
    }
  }
  
  return;
  
} /* end - FreeEntry */


/**********************************************************************/
/* Remove Duplicates Entries	                                      */
/* Inputs: none				                              */
/* Output: modified nitems			                      */
/**********************************************************************/
void RemoveDuplicates()
{
  int i,j,cur,level;

  cur = 1;
  for ( i=2; i<=nitems; i++ )
  {
     if ( DupEntry( i, cur ) )
     {
	Entry[i].item->fields[0] = DELPTR;
     }
     level = GetD2(i,cur);
     if ( level!=LEVEL5 )
	  cur = i;
  }

  for ( i=1,j=1; i<=nitems; i++ )
  {
     if ( Entry[i].item->fields[0]==DELPTR )
     {
	FreeEntry(i);
     }
     else
     {
	MoveEntry(i,j);
	j++;
     }
  }
  
  nitems = --j;
  
  return;
} /* end - RemoveDuplicates */

/* make main() an int so it returns something predictable to the OS */
int main(argc, argv)
int  argc;
char *argv[];
{
	
  if ( argc<2 )
   {
      printf("\n\tUsage: index filename\n");
      exit(0);
   }
 
   printf("\n\tnewindex 1.10    All Rights Reserved.");
   printf("\n\tCopyright (c) 1989-91 The TeXplorators Corporation.\n");
      
   strcpy(ndxname,argv[1]); strcat(ndxname,".ndx");
   strcpy(tmpname,argv[1]); strcat(tmpname,".@d@");
   strcpy(xdxname,argv[1]); strcat(xdxname,".xdx");
   strcpy(idxname,argv[1]); strcat(idxname,".idx");

   idxfile = FALSE;
   if ( argc > 2 )
   {
      if ( strnicmp(argv[2],"-i",2)==0 )
	   idxfile = TRUE;
   }
    
   if ( ( ndxfile = fopen(ndxname,"r") )==NULL )
   {
      printf("File %s not found\r\n",ndxname);
      beep();
      exit(0);
   }
  
   if ( ( xxxfile = fopen(tmpname,"w+") )==NULL )
   {
     printf("File %s cannot be opened\r\n",tmpname);
     beep();
     exit(0);
   }

   if ( ( xdxfile = fopen(xdxname,"w") )==NULL )
   {
     printf("File %s cannot be opened\r\n",xdxname);
     beep();
     exit(0);
   }
   
   InitProc();

   PreProc();

   BuildProc();
   
   fclose(ndxfile);

   SortProc();
   
   RemoveDuplicates();

   TeXOut();
   
   fclose(xdxfile);
   fclose(xxxfile);
#ifdef MICROSOFTC
   fcloseall();
#endif

   unlink(tmpname);
   FreeMem();
   
   printMSG("");
   printf("\r\n");
   
   return(0);
}


/* ############################### END OF FILE ########################### */