aboutsummaryrefslogtreecommitdiff
path: root/contrib/texmacs/src/texbreaker.c
blob: 49a5966c37aea532396196418178405bd13ad4ac (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
/* Released under the Modified BSD license attached to Axiom sources.
 * TeX Display Math Mode Line Breaking Program
 *
 * Author: Robert S. Sutor
 *
 * Date:   1991
 *
 * Change History:
 *
 * 01/19/92   RSS   Change to use \[ \] instead of $$ $$
 *
 * 09/01/92   RSS   Format and fix =-.
 *
 * Operation:
 *
 * This program reads standard input and writes to standard output. Display math
 * mode starts with \[ at the beginning of a line and ends with \]. All lines
 * not in display math mode are simply printed on standard output.  The
 * expressions in display math mode are broken so that they fit on a page
 * better (line breaking).
 *
 * The array stuff is being converted to use the array node type.
 *
 * Restrictions:
 *
 * 1.  Assume \[ and \] start in column 1 and are the only things on the lines.
 *
 * 2.  Comments in display math mode are not preserved.
 *
 * 3. This is meant to deal with output from the AXIOM computer algebra system.
 * Unpredictable results may occur if used with hand-generated TeX code or
 * TeX code generated by other programs.
 */

/*
 * Include files and #defines.
 */
#include "useproto.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MATHBUFLEN     8*8192
#define MAXMATHTOKEN   80
#define MAXCHARSINLINE 60
#define FATDELIMMULT   2

#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif
#ifndef min
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif

#define TRUE 1
#define FALSE 0

#define STRCHREQ(str,char) (str[0] == char)

/*
 * Type declarations.
 */

enum nodeTypes {
    N_NODE,
    N_TEXT,
    N_ARRAY
};

typedef struct listNodeStruct {
    struct listNodeStruct *nextListNode;
    struct listNodeStruct *prevListNode;
    enum nodeTypes nodeType;
    long width;
    long realWidth;
    union {
        char *text;
        struct listNodeStruct *node;
        struct arrayNodeStruct *array;
    }   data;
}   listNode;

typedef struct arrayNodeStruct {
    int cols;
    listNode *argsNode;
    listNode *entries;          /* linked list of nodes, each pointing to a
                                 * row */
}   arrayNode;


/*
 * Global Variables.
 */

char line[1024];
char blanks[] = "                                                   ";
char lastPrinted = '\0';
int indent = 0;
char mathBuffer[MATHBUFLEN], mathToken[MAXMATHTOKEN];
char bufout[2*MATHBUFLEN];
int lineLen, mathBufferLen, mathBufferPtr, mathTokenLen;
listNode *mathList;
int charsOut, fatDelimiter;
int maxLineWidth = 4500;        /* 4.5  inches * 1000    */
int maxLineSlop = 0;            /* 0.0  inches * 1000    */
int charTable[256];
int avgCharWidth;
int spaceWidths[5], extraOverWidth;
int arrayDepth = 0, arrayMaxDepth = 3;
int charMultNum, charMultDenom;
int sinWidth, cosWidth, tanWidth, erfWidth;
long outLineNum = 0L;

/*
 * Function Prototypes.
 */
#ifndef _NO_PROTO
void        arrayTooDeep();
int         breakFracProd(listNode *, long, char *, char *, int);
int         breakFunction(listNode *, long);
int         breakList(listNode *, long);
int         breakMathList(listNode *, long);
int         breakNumber(listNode *, long);
int         breakPMEB(listNode *, long);
int         breakParen(listNode *, long);
int         bufferMathLines();
void        buildMathList();
int         charWidth(char);
void        computeNodeWidth(listNode *);
long        computeWidth(listNode *);
void        displaySplitMsg(char *, int);
void        error(char *, char *);
void        freeMathList(listNode *);
void        getOptions(int, char **);
void        initCharTable();
listNode   *insertStringAfter(char *, listNode *);
listNode   *insertStringAtBack(char *, listNode *);
listNode   *insertStringAtFront(char *, listNode *);
int         newLineIfNecessary(int);
listNode   *newListNode(enum nodeTypes);
int         nextMathToken();
int         printChar(char);
int         printMathList(listNode *, int);
int         printString(char *);
void        putcBuf(char, char []);
void        putsBuf(char [], char []);
void        resetCharMults();
listNode   *string2NodeList(char *, listNode *);
void        ttCharMults();
#else
void        arrayTooDeep();
int         breakFracProd();
int         breakFunction();
int         breakList();
int         breakMathList();
int         breakNumber();
int         breakPMEB();
int         breakParen();
int         bufferMathLines();
void        buildMathList();
int         charWidth();
void        computeNodeWidth();
long        computeWidth();
void        displaySplitMsg();
void        error();
void        freeMathList();
void        getOptions();
void        initCharTable();
listNode   *insertStringAfter();
listNode   *insertStringAtBack();
listNode   *insertStringAtFront();
int         newLineIfNecessary();
listNode   *newListNode();
int         nextMathToken();
int         printChar();
int         printMathList();
int         printString();
void        putsBuf();
void        putcBuf();
void        resetCharMults();
listNode   *string2NodeList();
void        ttCharMults();
#endif


/*
 * Function Definitions.
 */

int
#ifndef _NO_PROTO
texbreak(char bufinp[])
#else
texbreak(bufinp)
char bufinp[];
#endif
{
    initCharTable();
    strcpy(bufout,"");
    mathBufferLen=strlen(bufinp);
    if (mathBufferLen > MATHBUFLEN) {
       fprintf(stderr, "mathBuffer too small. Need: %d\n", mathBufferLen);
       return 0;
    };
    mathBufferPtr = 0;
    strcpy(mathBuffer,bufinp);
/*  fprintf(stderr, "bufinp: %s\n", mathBuffer); */
    fatDelimiter = 1;
    arrayDepth = 0;
    mathList = newListNode(N_NODE);
    buildMathList(mathList);
    resetCharMults();
    computeWidth(mathList);
/*  if (mathList->width > maxLineWidth)
       fprintf(stderr, "Width = %ld units, Output line = %ld.\n", mathList->width, outLineNum); */
    breakMathList(mathList, maxLineWidth);
    charsOut = 0;
    printMathList(mathList->data.node, TRUE);
    freeMathList(mathList);
    return 1;
}

/*
 * breakFracProd:
 *
 * Arguments:
 *
 * n : the starting node at which we are to try to break
 *
 * lineWidth : the maximum width of a line
 *
 * match :  either "\\over" or "\\ "
 *
 * label :  either "quotient" or "product"
 *
 * paren :  add parentheses (TRUE or FALSE)
 *
 *
 * Returns: TRUE or FALSE, depending on whether the expression was broken
 *
 *
 * Function: Tries to break up a quotient t1 \over t2 or a product t1 \ t2 by
 * splitting and parenthesizing the numerator and/or the denominator.
 */

int
#ifndef _NO_PROTO
breakFracProd(listNode * n, long lineWidth, char *match, char *label, int paren)
#else
breakFracProd(n,lineWidth,match,label,paren)
listNode * n; 
long lineWidth; 
char *match; 
char *label; 
int paren;
#endif
{

    listNode *rootNode, *lastNode, *t1, *t2;
    int ok;
    long workWidth1, workWidth2;

    if (n->nodeType != N_NODE)
        return FALSE;

    rootNode = n;

    ok = FALSE;
    t1 = n = rootNode->data.node;
    n = n->nextListNode;
    if (n) {
        if ((n->nodeType == N_TEXT) &&
            (0 == strcmp(n->data.text, match))) {
            t2 = n->nextListNode;
            if (t2 && (NULL == t2->nextListNode))
                ok = TRUE;
        }
    }

    displaySplitMsg(label, ok);

    if (ok) {

        /* for products, determine rough widths for the two factors */

        if (0 == strcmp(label, "product")) {
            computeNodeWidth(t1);
            computeNodeWidth(t2);
            workWidth1 = lineWidth - charWidth(' ');

            if (workWidth1 / 2 > t1->realWidth) {
                workWidth2 = workWidth1 - t1->realWidth;
                workWidth1 = t1->realWidth;
            }
            else if (workWidth1 / 2 > t2->realWidth) {
                workWidth1 = workWidth1 - t2->realWidth;
                workWidth2 = t2->realWidth;
            }
            else
                workWidth1 = workWidth2 = workWidth1 / 2;

            if (paren) {
                if (t1->realWidth > workWidth1)
                    workWidth1 = workWidth1 - 4 * FATDELIMMULT * charWidth('(');
                if (t2->realWidth > workWidth2)
                    workWidth2 = workWidth2 - 4 * FATDELIMMULT * charWidth('(');
            }
        }
        else                    /* "quotient" */
            workWidth1 = workWidth2 =
                lineWidth - paren * 4 * FATDELIMMULT * charWidth('(');

        if ((t1->nodeType == N_NODE) && (t1->realWidth > workWidth1)) {
            t1->width = t1->realWidth;

            if (breakMathList(t1, workWidth1) && paren) {
                /* insert the \left( */
                lastNode = insertStringAtFront("\\left(", t1);

                while (lastNode->nextListNode)
                    lastNode = lastNode->nextListNode;

                /* insert the \right) */
                insertStringAtBack("\\right)", lastNode);
            }
        }

        if ((t2->nodeType == N_NODE) && (t2->realWidth > workWidth2)) {
            t2->width = t2->realWidth;

            if (breakMathList(t2, workWidth2) && paren) {
                /* insert the \left( */
                lastNode = insertStringAtFront("\\left(", t2);

                while (lastNode->nextListNode)
                    lastNode = lastNode->nextListNode;

                /* insert the \right) */
                insertStringAtBack("\\right)", lastNode);
            }
        }

        return TRUE;
    }
    return FALSE;
}


int
#ifndef _NO_PROTO
breakFunction(listNode * n, long lineWidth)
#else
breakFunction(n,lineWidth)
listNode * n; 
long lineWidth;
#endif
{
    listNode *rootNode, *tmpNode, *lastNode, *t1, *t2, *t3;
    int ok = FALSE;
    long workWidth, maxWidth = 0;

    if (n->nodeType != N_NODE)
        return FALSE;

    n = n->data.node;

    if (n->nodeType == N_NODE)
        return FALSE;

    if ((0 == strcmp(n->data.text, "\\sin")) ||
        (0 == strcmp(n->data.text, "\\cos")) ||
        (0 == strcmp(n->data.text, "\\tan")) ||
        (0 == strcmp(n->data.text, "\\log")) ||
        (0 == strcmp(n->data.text, "\\arctan")) ||
        (0 == strcmp(n->data.text, "\\erf"))) {
        computeNodeWidth(n);
        ok = TRUE;
    }

    displaySplitMsg("function", ok);

    if (ok) {
        t2 = newListNode(N_NODE);
        t2->data.node = n->nextListNode;
        t2->prevListNode = n;
        n->nextListNode = t2;
        ok = breakMathList(t2, lineWidth - n->realWidth);
    }

    return ok;
}

/*
 * breakList:
 *
 * Arguments:
 *
 * n : the starting node at which we are to try to break
 *
 * lineWidth : the maximum width of a line
 *
 *
 * Returns: TRUE or FALSE, depending on whether the expression was broken
 *
 *
 * Function: Tries to split an expression that is bracketed by \left[ and
 * \right] (or \left\{ and \right\} and contains at least one comma.
 */

int
#ifndef _NO_PROTO
breakList(listNode * n, long lineWidth)
#else
breakList(n,lineWidth)
listNode * n; 
long lineWidth;
#endif
{
    listNode *rootNode, *tmpNode, *lastNode, *t1, *t2, *t3;
    int ok, comma;
    long workWidth, maxWidth = 0;

    if (n->nodeType != N_NODE)
        return FALSE;

    rootNode = n;

    t1 = n = rootNode->data.node;
    comma = ok = FALSE;

    if ((t1->nodeType == N_TEXT) &&
        (0 == strcmp(t1->data.text, "\\left")) &&
        (t1->nextListNode) &&
        (t1->nextListNode->nodeType == N_TEXT) &&
        ((0 == strcmp(t1->nextListNode->data.text, "[")) ||
         (0 == strcmp(t1->nextListNode->data.text, "\\{")))) {

        t1 = t1->nextListNode->nextListNode;

        /*
         * Check for a special case: sometimes the whole body of the list is
         * a node. Flatten this, if possible.
         */

        if ((t1->nodeType == N_NODE) &&
            (t1->nextListNode->nodeType == N_TEXT) &&
            (0 == strcmp(t1->nextListNode->data.text, "\\right"))) {
            tmpNode = t1->prevListNode;
            t2 = t1->nextListNode;
            t3 = t1->data.node;
            tmpNode->nextListNode = t3;
            t3->prevListNode = tmpNode;
            while (t3->nextListNode)
                t3 = t3->nextListNode;
            t3->nextListNode = t2;
            t2->prevListNode = t3;
            free(t1);
            t1 = tmpNode->nextListNode;
        }

        while (t1->nextListNode && !ok) {
            if ((t1->nodeType == N_TEXT) &&
                (0 == strcmp(t1->data.text, ",")))
                comma = TRUE;
            else if ((t1->nodeType == N_TEXT) &&
                     (0 == strcmp(t1->data.text, "\\right")) &&
                     (t1->nextListNode->nodeType == N_TEXT) &&
                     ((0 == strcmp(t1->nextListNode->data.text, "]")) ||
                      (0 == strcmp(t1->nextListNode->data.text, "\\}"))) &&
                     (NULL == t1->nextListNode->nextListNode)) {
                ok = comma;
                tmpNode = t1->nextListNode;
            }
            t1 = t1->nextListNode;
        }
    }

    displaySplitMsg("list", ok);

    if (ok) {
        if (arrayDepth >= arrayMaxDepth) {
            arrayTooDeep();
            return FALSE;
        }

        /*
         * Create array environment
         */

        lastNode = insertStringAtFront("\\begin{array}{@{}l}\\displaystyle", rootNode);
        arrayDepth++;
        insertStringAtBack("\\end{array}", tmpNode);

        /*
         * Now break at best place short of width.        Start after the
         * environment begins and after the \left(
         */

        n = lastNode->nextListNode->nextListNode->nextListNode;

        /*
         * try to split the first expression if too big
         */

        tmpNode = n->nextListNode;
        if (breakMathList(n, lineWidth)) {
            workWidth = n->width;
            n = tmpNode;
        }
        else
            workWidth = n->width;
        maxWidth = workWidth;

        while (n->nextListNode) {
            if ((n->nodeType == N_TEXT) &&
                ((0 == strcmp(n->data.text, ",")) ||
                 (0 == strcmp(n->data.text, "\\:"))) &&
                (workWidth + n->nextListNode->width > lineWidth)) {
                maxWidth = max(maxWidth, workWidth);
                n = insertStringAfter("\\right. \\\\ \\\\ \\displaystyle \\left.", n);

                /*
                 * try to split the next expression if too big
                 */

                tmpNode = n->nextListNode;
                if (breakMathList(n, lineWidth)) {
                    workWidth = n->width;
                    n = tmpNode;
                }
                else
                    workWidth = n->width;
            }
            else {
                workWidth += n->nextListNode->width;
                n = n->nextListNode;
            }
        }

        rootNode->width = rootNode->realWidth =
            rootNode->data.node->width = rootNode->data.node->realWidth =
            maxWidth;
        arrayDepth--;

        return TRUE;
    }

    return FALSE;
}

/*
 * breakNumber:
 *
 * Arguments:
 *
 * rootNode : the starting node at which we are to try to break
 *
 * lineWidth : the maximum width of a line
 *
 *
 * Returns: TRUE or FALSE, depending on whether the expression was broken
 *
 *
 * Function: Tries to break an expression that contains only digits and possibly
 * a decimal point.
 */

int
#ifndef _NO_PROTO
breakNumber(listNode * rootNode, long lineWidth)
#else
breakNumber(rootNode,lineWidth)
listNode * rootNode; 
long lineWidth;
#endif
{
    int ok = TRUE;
    listNode *n, *arrNode, *rowNode, *colNode;
    long workWidth, maxWidth = 0;

    if (rootNode->nodeType != N_NODE)
        return FALSE;

    n = rootNode->data.node;
    while (n && ok) {
        if ((n->nodeType == N_TEXT) &&
            (n->data.text[1] == '\0') &&
            (isdigit(n->data.text[0]) || ('.' == n->data.text[0]))) {
            n = n->nextListNode;
        }
        else
            ok = FALSE;
    }

    displaySplitMsg("number", ok);

    if (ok) {
        if (arrayDepth >= arrayMaxDepth) {
            arrayTooDeep();
            return FALSE;
        }

        arrayDepth++;
        arrNode = newListNode(N_ARRAY);
        arrNode->data.array->entries = rowNode = newListNode(N_NODE);
        arrNode->data.array->cols = 1;
        arrNode->data.array->argsNode = newListNode(N_NODE);
        string2NodeList("{@{}l}", arrNode->data.array->argsNode);

        n = rootNode->data.node;
        computeWidth(n);
        maxWidth = workWidth = n->width;
        rowNode->data.node = colNode = newListNode(N_NODE);
        colNode->data.node = n;
        n = n->nextListNode;

        while (n) {
            computeWidth(n);

            if (workWidth + n->width > lineWidth) {
                maxWidth = max(maxWidth, workWidth);

                /*
                 * time to start a new row
                 */

                n->prevListNode->nextListNode = NULL;
                n->prevListNode = NULL;
                workWidth = n->width;
                rowNode->nextListNode = newListNode(N_NODE);
                rowNode = rowNode->nextListNode;
                rowNode->data.node = colNode = newListNode(N_NODE);
                colNode->data.node = n;
            }
            else
                workWidth += (n->nextListNode) ? n->nextListNode->width :0 ;

            n = n->nextListNode;
        }

        rootNode->data.node = arrNode;
        rootNode->width = rootNode->realWidth =
            arrNode->width = arrNode->realWidth = maxWidth;
        arrayDepth--;

        return TRUE;
    }

    return FALSE;
}

void
#ifndef _NO_PROTO
resetWidths(listNode * n)
#else
resetWidths(n)
listNode * n;
#endif
{
    if (n) {
        n->width = -1;
        n->realWidth = 0;
        if (n->nodeType == N_NODE)
            resetWidths(n->data.node);
        resetWidths(n->nextListNode);
    }
}

/*
 * breakParen:
 *
 * Arguments:
 *
 * n : the starting node at which we are to try to break
 *
 * lineWidth : the maximum width of a line
 *
 *
 * Returns: TRUE or FALSE, depending on whether the expression was broken
 *
 *
 * Function: Tries to split an expression that is bracketed by left( and \right)
 * (e.g., a factor).
 */

int
#ifndef _NO_PROTO
breakParen(listNode * n, long lineWidth)
#else
breakParen(n,lineWidth)
listNode * n;
long lineWidth;
#endif
{
    listNode *tmpNode, *workNode;
    int ok = FALSE;

    if (n->nodeType != N_NODE)
        goto say_msg;

    tmpNode = n->data.node;

    /*
     * check for \left
     */

    if ((tmpNode == NULL) ||
        (tmpNode->nodeType == N_NODE) ||
        (0 != strcmp(tmpNode->data.text, "\\left")))
        goto say_msg;

    /*
     * check for '('
     */

    tmpNode = tmpNode->nextListNode;

    if ((tmpNode == NULL) ||
        (tmpNode->nodeType == N_NODE) ||
        ('(' != tmpNode->data.text[0]))
        goto say_msg;

    /*
     * now move to the end
     */

    tmpNode = tmpNode->nextListNode;

    if (tmpNode != NULL) {
        while (tmpNode->nextListNode)
            tmpNode = tmpNode->nextListNode;
        tmpNode = tmpNode->prevListNode;
    }

    /*
     * check for \right
     */

    if ((tmpNode == NULL) ||
        (tmpNode->nodeType == N_NODE) ||
        (0 != strcmp(tmpNode->data.text, "\\right")))
        goto say_msg;

    /*
     * check for ')'
     */

    tmpNode = tmpNode->nextListNode;

    if ((tmpNode == NULL) ||
        (tmpNode->nodeType == N_NODE) ||
        (')' != tmpNode->data.text[0]))
        goto say_msg;

    ok = TRUE;

say_msg:
    displaySplitMsg("parenthesized expression", ok);

    if (ok) {

        /*
         * nest the whole inside if necessary, i.e., there is more than one
         * term between the ( and the \right
         */

        if (tmpNode->prevListNode->prevListNode !=
            n->data.node->nextListNode->nextListNode) {
            workNode = newListNode(N_NODE);
            workNode->data.node = n->data.node->nextListNode->nextListNode;
            n->data.node->nextListNode->nextListNode = workNode;
            tmpNode->prevListNode->prevListNode->nextListNode = NULL;
            tmpNode->prevListNode->prevListNode = workNode;
            workNode->prevListNode = n->data.node->nextListNode;
            workNode->nextListNode = tmpNode->prevListNode;
            resetWidths(workNode);
            computeWidth(workNode);
        }

        return breakMathList(n->data.node->nextListNode->nextListNode,
                             lineWidth - 4 * FATDELIMMULT * charWidth('('));
    }

    return FALSE;
}

/*
 * breakPMEB:
 *
 * Arguments:
 *
 * n : the starting node at which we are to try to break
 *
 * lineWidth : the maximum width of a line
 *
 *
 * Returns: TRUE or FALSE, depending on whether the expression was broken
 *
 *
 * Function: Tries to split an expression that contains only +, -, = or \  as
 * operators.  The split occurs after the operator.
 */

int
#ifndef _NO_PROTO
breakPMEB(listNode * n, long lineWidth)
#else
breakPMEB(n,lineWidth)
listNode * n; 
long lineWidth;
#endif
{
    char *s;
    listNode *rootNode, *tmpNode, *lastNode;
    int ok, op;
    long workWidth, maxWidth = 0;

    if (n->nodeType != N_NODE)
        return FALSE;

    if (n->width <= lineWidth + maxLineSlop)    /* allow a little slop here */
        return FALSE;

    rootNode = n;
    tmpNode = n = n->data.node;
    ok = TRUE;
    op = FALSE;

    while (n && ok) {
        if (n->nodeType == N_TEXT) {
            s = n->data.text;
            if (STRCHREQ(s, '+') || STRCHREQ(s, '-') || STRCHREQ(s, '=') ||
                (0 == strcmp(s, "\\ ")))
                op = TRUE;
            else if ((0 == strcmp(s, "\\left")) ||
                     (0 == strcmp(s, "\\right")) ||
                     (0 == strcmp(s, "\\over")) ||
                     STRCHREQ(s, ',')) {
                ok = FALSE;
                break;
            }
        }
        tmpNode = n;
        n = n->nextListNode;
    }
    ok = ok & op;

    displaySplitMsg("(+,-,=, )-expression", ok);


    if (ok) {
        if (arrayDepth >= arrayMaxDepth) {
            arrayTooDeep();
            return FALSE;
        }

        /*
         * Create array environment
         */

        lastNode = insertStringAtFront("\\begin{array}{@{}l}\\displaystyle", rootNode);
        arrayDepth++;
        insertStringAtBack("\\end{array}", tmpNode);

        /*
         * Now break at best place short of width. Start after the
         * environment begins.
         */

        n = lastNode->nextListNode;

        /*
         * try to split the first expression if too big
         */

        tmpNode = n->nextListNode;
        if (breakMathList(n, lineWidth)) {
            workWidth = n->width;
            n = tmpNode;
        }
        else
            workWidth = n->width;
        maxWidth = workWidth;

        while (n->nextListNode) {
    loop_top:
            if ((n->nodeType == N_TEXT) &&
              (STRCHREQ(n->data.text, '+') || STRCHREQ(n->data.text, '-') ||
               STRCHREQ(n->data.text, '=') ||
               (0 == strcmp(n->data.text, "\\ "))) &&
                (workWidth > 24) &&     /* avoid - or + on their own line */
                (workWidth + n->nextListNode->width > lineWidth)) {

                if ((workWidth < lineWidth / 3) &&
                  (breakMathList(n->nextListNode, lineWidth - workWidth))) {
                    n->nextListNode->width = -1;
                    n->nextListNode->realWidth = 0;
                    computeNodeWidth(n->nextListNode);
                    goto loop_top;
                }

                /*
                 * \  means multiplication. Use a \cdot to make this clearer
                 */

                if (0 == strcmp(n->data.text, "\\ "))
                    n = insertStringAfter("\\cdot \\\\ \\\\ \\displaystyle", n);
                else
                    n = insertStringAfter("\\\\ \\\\ \\displaystyle", n);
                maxWidth = max(maxWidth, workWidth);

                /*
                 * try to split the next expression if too big
                 */

                tmpNode = n->nextListNode;
                if (breakMathList(n, lineWidth)) {
                    workWidth = n->width;
                    n = tmpNode;
                }
                else
                    workWidth = n->width;
            }
            else {
                workWidth += n->nextListNode->width;
                n = n->nextListNode;
            }
        }

        rootNode->width = rootNode->realWidth =
            rootNode->data.node->width = rootNode->data.node->realWidth =
            maxWidth;
        arrayDepth--;

        return TRUE;
    }

    return FALSE;
}

/*
 * breakMathList:
 *
 * Arguments:
 *
 * n : the starting node at which we are to try to break
 *
 * lineWidth : the maximum width of a line
 *
 *
 * Returns: TRUE or FALSE, depending on whether the expression was broken
 *
 *
 * Function: Tries various methods to break the expression up into multiple
 * lines if the expression is too big.
 */

int
#ifndef _NO_PROTO
breakMathList(listNode * n, long lineWidth)
#else
breakMathList(n,lineWidth)
listNode * n; 
long lineWidth;
#endif
{
    int split = FALSE;

    /*
     * Don't do anything if already short enough.
     */

    if (n->width <= lineWidth)
        return FALSE;

    /*
     * Can't split strings, so just return.
     */

    if (n->nodeType == N_TEXT)
        return FALSE;

    blanks[indent] = ' ';
    indent += 2;
    blanks[indent] = '\0';

    /*
     * We know we have a node, so see what we can do.
     */

    /*
     * Case 1: a product: t1 \  t2
     */

    if (split = breakFracProd(n, lineWidth, "\\ ", "product", FALSE))
        goto done;

    /*
     * Case 2: a sequence of tokens separated by +, - or =
     */

    if (split = breakPMEB(n, lineWidth))
        goto done;

    /*
     * Case 3: a fraction of terms: t1 \over t2
     */

    if (split = breakFracProd(n, lineWidth, "\\over", "quotient", TRUE))
        goto done;

    /*
     * Case 4: a list of terms bracketed by \left[ and \right] with a comma
     */

    if (split = breakList(n, lineWidth))
        goto done;

    /*
     * Case 5: a list of digits, possibly with one "."
     */

    if (split = breakNumber(n, lineWidth))
        goto done;

    /*
     * Case 6: a parenthesized expression (e.g., a factor)
     */

    if (split = breakParen(n, lineWidth))
        goto done;

    /*
     * Case 7: a function application
     */

    if (split = breakFunction(n, lineWidth))
        goto done;

done:
    blanks[indent] = ' ';
    indent -= 2;
    blanks[indent] = '\0';

    return split;
}

void
#ifndef _NO_PROTO
buildMathList(listNode * oldNode)
#else
buildMathList(oldNode)
listNode * oldNode;
#endif
{
    listNode *curNode, *tmpNode;

    curNode = NULL;
    while (nextMathToken()) {
        if (mathToken[0] == '}')
            break;
        if (mathToken[0] == '{') {
            tmpNode = newListNode(N_NODE);
            buildMathList(tmpNode);
        }
        else {
            tmpNode = newListNode(N_TEXT);
            tmpNode->data.text = strdup(mathToken);
        }
        if (curNode == NULL) {
            oldNode->data.node = tmpNode;
        }
        else {
            tmpNode->prevListNode = curNode;
            curNode->nextListNode = tmpNode;
        }
        curNode = tmpNode;
    }

    /*
     * leave with one level of nesting, e.g., {{{x}}} --> {x}
     */

    tmpNode = oldNode->data.node;
    while ( tmpNode && (tmpNode->nodeType == N_NODE) &&
           (tmpNode->nextListNode == NULL) ) {
        oldNode->data.node = tmpNode->data.node;
        free(tmpNode);
        tmpNode = oldNode->data.node;
    }
}

void
#ifndef _NO_PROTO
computeNodeWidth(listNode * n)
#else
computeNodeWidth(n)
listNode * n;
#endif
{
    char *s;
    int i;
    listNode *tmp;

    if (n->width != -1)         /* only = -1 if unprocessed */
        return;

    n->realWidth = 0;

    if (n->nodeType == N_TEXT) {
        s = n->data.text;
        if (s[0] == '\\') {
            if (s[2] == '\0') {
                switch (s[1]) {
                  case ' ':
                    n->width = spaceWidths[0];
                    break;
                  case ',':
                    n->width = spaceWidths[1];
                    break;
                  case '!':
                    n->width = spaceWidths[2];
                    break;
                  case ':':
                    n->width = spaceWidths[3];
                    break;
                  case ';':
                    n->width = spaceWidths[4];
                    break;
                  default:
                    n->width = avgCharWidth;
                }
                n->realWidth = n->width;
            }
            else if ((0 == strcmp(s, "\\displaystyle")) ||
                     (0 == strcmp(s, "\\bf")) ||
                     (0 == strcmp(s, "\\sf")) ||
                     (0 == strcmp(s, "\\tt")) ||
                     (0 == strcmp(s, "\\rm")) ||
                     (0 == strcmp(s, "\\hbox")) ||
                     (0 == strcmp(s, "\\mbox")) ||
                     (0 == strcmp(s, "\\overline")) ||
                     (0 == strcmp(s, "\\textstyle")) ||
                     (0 == strcmp(s, "\\scriptstyle")) ||
                     (0 == strcmp(s, "\\scriptscriptstyle"))) {
                n->width = 0;
            }
            else if (0 == strcmp(s, "\\ldots"))
                n->width = 3 * charWidth('.');
            else if (0 == strcmp(s, "\\left")) {
                tmp = n->nextListNode;
                if (tmp->nodeType != N_TEXT)
                    error("unusual token following \\left", "");
                n->realWidth = n->width = (tmp->data.text[0] == '.')
                    ? 0
                    : charWidth(tmp->data.text[0]);
                tmp->width = 0;
                fatDelimiter = 1;
            }
            else if (0 == strcmp(s, "\\over")) {

                /*
                 * have already added in width of numerator
                 */
                computeNodeWidth(n->nextListNode);
                n->realWidth = extraOverWidth + max(n->prevListNode->width, n->nextListNode->width);
                n->width = n->realWidth - n->prevListNode->width;
                n->nextListNode->width = 0;
                fatDelimiter = FATDELIMMULT;
            }
            else if (0 == strcmp(s, "\\right")) {
                tmp = n->nextListNode;
                if (tmp->nodeType != N_TEXT)
                    error("unusual token following \\right", "");
                n->realWidth = n->width = fatDelimiter *
                    ((tmp->data.text[0] == '.') ? 0 : charWidth(tmp->data.text[0]));
                tmp->width = 0;
                fatDelimiter = 1;
            }
            else if (0 == strcmp(s, "\\root")) {
                computeNodeWidth(n->nextListNode);      /* which root */
                n->nextListNode->nextListNode->width = 0;       /* \of */
                tmp = n->nextListNode->nextListNode->nextListNode;
                computeNodeWidth(tmp);  /* root of    */
                n->realWidth = n->width = tmp->width + (avgCharWidth / 2) +
                    max(avgCharWidth, n->nextListNode->width);
                n->nextListNode->width = 0;
                tmp->width = 0;
            }
            else if (0 == strcmp(s, "\\sqrt")) {
                computeNodeWidth(n->nextListNode);
                n->realWidth = n->width =
                    avgCharWidth + (avgCharWidth / 2) + n->nextListNode->width;
                n->nextListNode->width = 0;
            }
            else if (0 == strcmp(s, "\\zag")) {
                computeNodeWidth(n->nextListNode);
                computeNodeWidth(n->nextListNode->nextListNode);
                n->realWidth = n->width = avgCharWidth + max(n->nextListNode->width,
                                      n->nextListNode->nextListNode->width);
                n->nextListNode->width = 0;
                n->nextListNode->nextListNode->width = 0;
                fatDelimiter = FATDELIMMULT;
            }
            else if ((0 == strcmp(s, "\\alpha")) ||
                     (0 == strcmp(s, "\\beta")) ||
                     (0 == strcmp(s, "\\pi"))) {
                n->realWidth = n->width = avgCharWidth;
            }
            else if (0 == strcmp(s, "\\sin"))
                /* should use table lookup here */
                n->realWidth = n->width = sinWidth;
            else if (0 == strcmp(s, "\\cos"))
                n->realWidth = n->width = cosWidth;
            else if (0 == strcmp(s, "\\tan"))
                n->realWidth = n->width = tanWidth;
            else if (0 == strcmp(s, "\\erf"))
                n->realWidth = n->width = erfWidth;

            /*
             * otherwise just compute length of token after \
             */
            else {
                n->width = 0;
                for (i = 1; i < strlen(s); i++)
                    n->width += charWidth(s[i]);
                n->realWidth = n->width;
            }
        }
        else if (s[1] == '\0')
            switch (s[0]) {
              case '^':
              case '_':
                tmp = n->nextListNode;
                computeNodeWidth(tmp);
                n->width = n->width = tmp->width;
                tmp->width = 0;
                break;
              default:
                n->realWidth = n->width = charWidth(s[0]);
            }
        else {
            n->width = 0;
            for (i = 0; i < strlen(s); i++)
                n->width += charWidth(s[i]);
            n->realWidth = n->width;
        }
    }
    else {
        n->realWidth = n->width = computeWidth(n->data.node);
    }
}

long
#ifndef _NO_PROTO
computeWidth(listNode * n)
#else
computeWidth(n)
listNode * n;
#endif
{
    long w = 0;

    while (n != NULL) {
        if (n->width == -1) {
            computeNodeWidth(n);
            w += n->width;
        }
        n = n->nextListNode;
    }
    return w;
}

/*
 * displaySplitMsg:
 *
 * Arguments:
 *
 * s : a string describing the kind of expression we are trying to split.
 *
 * ok : whether we can split it (TRUE or FALSE)
 *
 *
 * Returns: nothing
 *
 *
 * Function: Displays a message on stderr about whether a particular method of
 * line breaking will be successful.
 */

void
#ifndef _NO_PROTO
displaySplitMsg(char *s, int ok)
#else
displaySplitMsg(s,ok)
char *s; 
int ok;
#endif
{
/*  fprintf(stderr, "%sCan split %s: %s\n", blanks, s, ok ? "TRUE" : "FALSE"); */
}

void
arrayTooDeep()
{
    fprintf(stderr, "%s->Array nesting too deep!\n", blanks);
}

void
#ifndef _NO_PROTO
error(char *msg, char *insert)
#else
error(msg,insert)
char *msg;
char *insert;
#endif
{
    fputs("Error (texbreak): ", stderr);
    fputs(msg, stderr);
    fputs(insert, stderr);
    fputc('\n', stderr);

    fputs("% Error (texbreak): ", stdout);
    fputs(msg, stdout);
    fputs(insert, stdout);
    fputc('\n', stdout);
    exit(1);
}

void
#ifndef _NO_PROTO
freeMathList(listNode * n)
#else
freeMathList(n)
listNode * n;
#endif
{
    listNode *tmpNode;

    while (n != NULL) {
        if (n->nodeType == N_NODE)
            freeMathList(n->data.node);
        else if (n->nodeType == N_TEXT)
            free(n->data.text);
        else {
            freeMathList(n->data.array->argsNode);
            freeMathList(n->data.array->entries);
            free(n->data.array);
        }
        tmpNode = n->nextListNode;
        free(n);
        n = tmpNode;
    }
}

listNode *
#ifndef _NO_PROTO
insertStringAfter(char *s, listNode * n)
#else
insertStringAfter(s,n)
char *s; 
listNode * n;
#endif
{

    /*
     * returns node after inserted string
     */
    listNode *workNode, *lastNode;

    workNode = newListNode(N_NODE);
    lastNode = string2NodeList(s, workNode);

    n->nextListNode->prevListNode = lastNode;
    lastNode->nextListNode = n->nextListNode;
    n->nextListNode = workNode->data.node;
    workNode->data.node->prevListNode = n;

    free(workNode);
    return lastNode->nextListNode;
}

listNode *
#ifndef _NO_PROTO
insertStringAtBack(char *s, listNode * n)
#else
insertStringAtBack(s,n)
char *s; 
listNode * n;
#endif
{

    /*
     * Breaks s up into a list of tokens and appends them onto the end of n.
     * n must be non-NULL.
     */

    listNode *workNode, *lastNode;

    workNode = newListNode(N_NODE);
    lastNode = string2NodeList(s, workNode);
    n->nextListNode = workNode->data.node;
    workNode->data.node->prevListNode = n;
    free(workNode);

    return lastNode;
}

listNode *
#ifndef _NO_PROTO
insertStringAtFront(char *s, listNode * n)
#else
insertStringAtFront(s,n)
char *s; 
listNode * n;
#endif
{

    /*
     * Breaks s up into a list of tokens and appends them onto the front of
     * n. n must be a node.
     */

    listNode *workNode, *lastNode;

    workNode = newListNode(N_NODE);
    lastNode = string2NodeList(s, workNode);
    lastNode->nextListNode = n->data.node;
    n->data.node->prevListNode = lastNode;
    n->data.node = workNode->data.node;
    free(workNode);

    return lastNode;
}

int
#ifndef _NO_PROTO
newLineIfNecessary(int lastWasNewLine)
#else
newLineIfNecessary(lastWasNewLine)
int lastWasNewLine;
#endif
{
    if (!lastWasNewLine || (charsOut > 0)) {
        putcBuf('\n', bufout);
        outLineNum++;
        charsOut = 0;
    }
    return TRUE;
}

listNode *
#ifndef _NO_PROTO
newListNode(enum nodeTypes nt)
#else
newListNode(nt)
enum nodeTypes nt;
#endif
{
    listNode *n;

    n = (listNode *) malloc(sizeof(listNode));
    n->nextListNode = n->prevListNode = NULL;
    n->nodeType = nt;
    n->width = -1;
    n->realWidth = -1;
    if (nt == N_NODE)
        n->data.node = NULL;
    else if (nt == N_TEXT)
        n->data.text = NULL;
    else {
        n->data.array = (arrayNode *) malloc(sizeof(arrayNode));
        n->data.array->argsNode = NULL;
        n->data.array->entries = NULL;
        n->data.array->cols = 0;
    }
    return n;
}

int
nextMathToken()
{


    /*
     * Sets mathToken. Returns 1 if ok, 0 if no more tokens.
     */

    char curChar, errChar[2];

    errChar[1] = '\0';
    mathToken[0] = '\0';
    mathTokenLen = 0;

    /*
     * Kill any blanks.
     */

    while ((mathBufferPtr < mathBufferLen) && (mathBuffer[mathBufferPtr] == ' '))
        mathBufferPtr++;

    /*
     * If at end, exit saying so.
     */

    if (mathBufferPtr >= mathBufferLen)
        return 0;

    mathToken[mathTokenLen++] = curChar = mathBuffer[mathBufferPtr++];

    if (curChar == '\\') {
        curChar = mathBuffer[mathBufferPtr++];
        switch (curChar) {
          case '\0':            /* at end of buffer */
            mathToken[mathTokenLen++] = ' ';
            goto done;
          case '\\':
          case ' ':
          case '!':
          case '#':
          case '$':
          case '%':
          case '&':
          case ',':
          case ':':
          case ';':
          case '^':
          case '_':
          case '{':
          case '}':
            mathToken[mathTokenLen++] = curChar;
            goto done;
        }
        if (isalpha(curChar) || (curChar == '@')) {
            mathToken[mathTokenLen++] = curChar;
            while ((curChar = mathBuffer[mathBufferPtr]) &&
                   (isalpha(curChar) || (curChar == '@'))) {
                mathToken[mathTokenLen++] = curChar;
                mathBufferPtr++;
            }
        }
        else {
            errChar[0] = curChar;
            errChar[1] = '\0';
            error("strange character following \\: ", errChar);
        }
    }
    else if (isdigit(curChar))  /* digits are individual tokens */
        ;
    else if (isalpha(curChar)) {
        while ((curChar = mathBuffer[mathBufferPtr]) &&
               (isalpha(curChar))) {
            mathToken[mathTokenLen++] = curChar;
            mathBufferPtr++;
        }
    }
    else if (curChar == '"') {  /* handle strings */
        while ((curChar = mathBuffer[mathBufferPtr]) &&
               (curChar != '"')) {
            mathToken[mathTokenLen++] = curChar;
            mathBufferPtr++;
        }
        mathToken[mathTokenLen++] = '"';
        mathBufferPtr++;
    }

done:
    mathToken[mathTokenLen--] = '\0';

    /*
     * Some translations.
     */
    if (0 == strcmp(mathToken, "\\sp")) {
        mathToken[0] = '^';
        mathToken[1] = '\0';
        mathTokenLen = 1;
    }
    else if (0 == strcmp(mathToken, "\\sb")) {
        mathToken[0] = '_';
        mathToken[1] = '\0';
        mathTokenLen = 1;
    }

    return 1;
}

int
#ifndef _NO_PROTO
printChar(char c)
#else
printChar(c)
char c;
#endif
{
    if ((charsOut > MAXCHARSINLINE) &&
        isdigit(lastPrinted) && isdigit(c)) {
        putcBuf('\n', bufout);
        outLineNum++;
        charsOut = 0;
    }

    putcBuf(c, bufout);
    lastPrinted = c;
    charsOut++;

    /*
     * break lines after following characters
     */

    if ((charsOut > MAXCHARSINLINE) && strchr("+- ,_^", c)) {
        putcBuf('\n', bufout);
        outLineNum++;
        charsOut = 0;
        lastPrinted = '\0';
        return TRUE;
    }
    return FALSE;
}

int
#ifndef _NO_PROTO
printMathList(listNode * n, int lastWasNewLine)
#else
printMathList(n,lastWasNewLine)
listNode * n; 
int lastWasNewLine;
#endif
{
    listNode *tmpNode, *rowNode, *colNode;
    int begin, group, r, c;

    while (n != NULL) {
        if (n->nodeType == N_NODE) {
            lastWasNewLine = printChar('{');
            lastWasNewLine = printMathList(n->data.node, lastWasNewLine);
            lastWasNewLine = printChar('}');
        }
        else if (n->nodeType == N_ARRAY) {
            lastWasNewLine = newLineIfNecessary(lastWasNewLine);
            lastWasNewLine = printString("\\begin{array}");
            lastWasNewLine = printMathList(n->data.array->argsNode, lastWasNewLine);
            lastWasNewLine = printString("\\displaystyle");
            lastWasNewLine = newLineIfNecessary(lastWasNewLine);

            rowNode = n->data.array->entries;   /* node pointing to first row */
            while (rowNode) {
                colNode = rowNode->data.node;
                while (colNode) {
                    if (colNode->prevListNode) {        /* if not first column */
                        lastWasNewLine = printString(" & ");
                        lastWasNewLine = newLineIfNecessary(lastWasNewLine);
                    }
                    lastWasNewLine = printMathList(colNode->data.node, lastWasNewLine);
                    colNode = colNode->nextListNode;
                }
                if (rowNode->nextListNode)      /* if not last row */
                    lastWasNewLine = printString(" \\\\");

                lastWasNewLine = newLineIfNecessary(lastWasNewLine);
                rowNode = rowNode->nextListNode;
            }

            lastWasNewLine = printString("\\end{array}");
            lastWasNewLine = newLineIfNecessary(lastWasNewLine);
        }
        else if (n->nodeType == N_TEXT) {

            /*
             * handle keywords that might appear in math mode
             */

            if ((0 == strcmp(n->data.text, "by")) ||
                (0 == strcmp(n->data.text, "if")) ||
                (0 == strcmp(n->data.text, "then")) ||
                (0 == strcmp(n->data.text, "else"))) {
                lastWasNewLine = printString(" \\hbox{ ");
                lastWasNewLine = printString(n->data.text);
                lastWasNewLine = printString(" } ");
            }

            /*
             * handle things that should be in a special font
             */

            else if ((0 == strcmp(n->data.text, "true")) ||
                     (0 == strcmp(n->data.text, "false")) ||
                     (0 == strcmp(n->data.text, "table")) ||
                     (0 == strcmp(n->data.text, "Aleph"))
                ) {
                lastWasNewLine = printString(" \\mbox{\\rm ");
                lastWasNewLine = printString(n->data.text);
                lastWasNewLine = printString("} ");
            }

            /*
             * handle things that should always be on their own line
             */

            else if ((0 == strcmp(n->data.text, "\\\\")) ||
                     (0 == strcmp(n->data.text, "\\displaystyle"))) {
                lastWasNewLine = newLineIfNecessary(lastWasNewLine);
                lastWasNewLine = printString(n->data.text);
                lastWasNewLine = newLineIfNecessary(lastWasNewLine);
            }

            /*
             * handle phrases that should be on their own line.
             */

            else if ((0 == strcmp(n->data.text, "\\begin")) ||
                     (0 == strcmp(n->data.text, "\\end"))) {
                lastWasNewLine = newLineIfNecessary(lastWasNewLine);
                lastWasNewLine = printString(n->data.text);
                begin = (n->data.text[1] == 'b') ? TRUE : FALSE;

                n = n->nextListNode;    /* had better be a node */
                tmpNode = n->data.node;
                lastWasNewLine = printChar('{');
                lastWasNewLine = printMathList(tmpNode, lastWasNewLine);
                lastWasNewLine = printChar('}');

                if (begin) {

                    /*
                     * if array, print the argument.
                     */

                    if (0 == strcmp(tmpNode->data.text, "array")) {
                        n = n->nextListNode;    /* had better be a node */
                        lastWasNewLine = printChar('{');
                        lastWasNewLine = printMathList(n->data.node, lastWasNewLine);
                        lastWasNewLine = printChar('}');
                    }
                }
                lastWasNewLine = newLineIfNecessary(FALSE);
            }

            /*
             * handle everything else, paying attention as to whether we
             * should include a trailing blank.
             */

            else {
                group = 0;
                /* guess whether next word is part of a type */
                if ((strlen(n->data.text) > 2) &&
                    ('A' <= n->data.text[0]) &&
                    ('Z' >= n->data.text[0])) {
                    group = 1;
                    lastWasNewLine = printString("\\hbox{\\axiomType{");
                }
                lastWasNewLine = printString(n->data.text);
                if (group) {
                    lastWasNewLine = printString("}\\ }");
                    group = 0;
                }
                tmpNode = n->nextListNode;
                if ((n->data.text[0] == '_') ||
                    (n->data.text[0] == '^') ||
                    (n->data.text[0] == '.') ||
                    (n->data.text[0] == '(') ||
                    (0 == strcmp(n->data.text, "\\left")) ||
                    (0 == strcmp(n->data.text, "\\right")) ||
                    (0 == strcmp(n->data.text, "\\%")));
                else if (tmpNode && (tmpNode->nodeType == N_TEXT)) {
                    if (((isdigit(n->data.text[0])) &&
                         (isdigit(tmpNode->data.text[0]))) ||
                        ((isdigit(n->data.text[0])) &&
                         (',' == tmpNode->data.text[0])) ||
                        (tmpNode->data.text[0] == '\'') ||
                        (tmpNode->data.text[0] == '_') ||
                        (tmpNode->data.text[0] == '^') ||
                        (tmpNode->data.text[0] == '.') ||
                        (tmpNode->data.text[0] == ')'));
                    else
                        lastWasNewLine = printChar(' ');
                }
            }
        }
        n = n->nextListNode;
    }
    return lastWasNewLine;
}

int
#ifndef _NO_PROTO
printString(char *s)
#else
printString(s)
char *s;
#endif
{
    if (s[0]) {
        if (!s[1])
            return printChar(s[0]);
        else {
            putsBuf(s,bufout);
            charsOut += strlen(s);
        }
    }
    return FALSE;
}

void
#ifndef _NO_PROTO
putsBuf(char s[], char buf[])
#else
putsBuf(s,buf)
char s[], buf[]
#endif
{
  strcat(buf,s);
}

void
#ifndef _NO_PROTO
putcBuf(char c,char buf[])
#else
putcBuf(c,buf)
char c, buf[]
#endif
{
  char s[2];

  s[0] = c;
  s[1] = '\0';
  strcat(buf,s);
}

listNode *
#ifndef _NO_PROTO
string2NodeList(char *s, listNode * n)
#else
string2NodeList(s,n)
char *s;
listNode * n;
#endif
{

    /*
     * First argument is string to be broken up, second is a node. Return
     * value is last item in list.
     */

    mathBufferPtr = 0;
    strcpy(mathBuffer, s);
    mathBufferLen = strlen(s);
    buildMathList(n);
    n = n->data.node;
    while (n->nextListNode) {

        /*
         * set width to 0: other funs will have to set for real
         */
        n->width = 0;
        n = n->nextListNode;
    }
    n->width = 0;
    return n;
}

void
resetCharMults()
{

    /*
     * this is a ratio by which the standard \mit should be multiplied to get
     * other fonts, roughly
     */

    charMultNum = charMultDenom = 1;
}

void
ttCharMults()
{

    /*
     * this is a ratio by which the standard \mit should be multiplied to get
     * the \tt font, roughly
     */

    charMultNum = 11;
    charMultDenom = 10;
}

int
#ifndef _NO_PROTO
charWidth(char c)
#else
charWidth(c)
char c;
#endif
{
    return (charMultNum * charTable[c]) / charMultDenom;
}

void
#ifndef _NO_PROTO
#else
#endif
initCharTable()
{
    int i;

    avgCharWidth = 95;          /* where 1000 = 1 inch */

    spaceWidths[0] = 51;        /* \  */
    spaceWidths[1] = 25;        /* \, */
    spaceWidths[2] = -25;       /* \! */
    spaceWidths[3] = 37;        /* \: */
    spaceWidths[4] = 42;        /* \; */

    extraOverWidth = 33;        /* extra space in fraction bar */

    sinWidth = 186;             /* width of \sin */
    cosWidth = 203;
    tanWidth = 219;
    erfWidth = 185;

    for (i = 0; i < 256; i++)
        charTable[i] = avgCharWidth;

    charTable['!'] = 42;
    charTable['"'] = 76;
    charTable['%'] = 126;
    charTable['('] = 59;
    charTable[')'] = 59;
    charTable['+'] = 185;
    charTable[','] = 42;
    charTable['-'] = 185;
    charTable['.'] = 42;
    charTable['/'] = 76;
    charTable['0'] = 76;
    charTable['1'] = 76;
    charTable['2'] = 76;
    charTable['3'] = 76;
    charTable['4'] = 76;
    charTable['5'] = 76;
    charTable['6'] = 76;
    charTable['7'] = 76;
    charTable['8'] = 76;
    charTable['9'] = 76;
    charTable[':'] = 42;
    charTable[';'] = 42;
    charTable['<'] = 202;
    charTable['='] = 202;
    charTable['>'] = 202;
    charTable['A'] = 114;
    charTable['B'] = 123;
    charTable['C'] = 119;
    charTable['D'] = 130;
    charTable['E'] = 121;
    charTable['F'] = 119;
    charTable['G'] = 119;
    charTable['H'] = 138;
    charTable['I'] = 79;
    charTable['J'] = 99;
    charTable['K'] = 140;
    charTable['L'] = 103;
    charTable['M'] = 164;
    charTable['N'] = 138;
    charTable['O'] = 120;
    charTable['P'] = 118;
    charTable['Q'] = 120;
    charTable['R'] = 116;
    charTable['S'] = 102;
    charTable['T'] = 110;
    charTable['U'] = 120;
    charTable['V'] = 122;
    charTable['W'] = 164;
    charTable['X'] = 137;
    charTable['Y'] = 122;
    charTable['Z'] = 114;
    charTable['['] = 42;
    charTable[']'] = 42;
    charTable['a'] = 80;
    charTable['b'] = 65;
    charTable['c'] = 66;
    charTable['d'] = 79;
    charTable['e'] = 71;
    charTable['f'] = 91;
    charTable['g'] = 78;
    charTable['h'] = 87;
    charTable['i'] = 52;
    charTable['j'] = 71;
    charTable['k'] = 84;
    charTable['l'] = 48;
    charTable['m'] = 133;
    charTable['n'] = 91;
    charTable['o'] = 73;
    charTable['p'] = 76;
    charTable['q'] = 73;
    charTable['r'] = 73;
    charTable['s'] = 71;
    charTable['t'] = 55;
    charTable['u'] = 87;
    charTable['v'] = 79;
    charTable['w'] = 113;
    charTable['x'] = 87;
    charTable['y'] = 80;
    charTable['z'] = 77;
    charTable['{'] = 76;
    charTable['|'] = 42;
    charTable['}'] = 76;
}