summaryrefslogtreecommitdiff
path: root/dviware/dvgtk/dvgt.c
blob: 2c5b6dd3d9a2c8536a2ac0d35d74bb69acdd85e1 (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
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
/* dvgtk.c - main dvgtk functions
   $Id: dvgt.c,v 0.2 1997/03/28 03:15:36 tjchol01 Exp $
   Authors: Andrew Trevorrow, Ian Dall, Geoffrey Tobin, Tomasz J. Cholewo
 */

#include "dvgt.h"

#include <kpathsea/c-ctype.h>
#include <kpathsea/proginit.h>
#include <kpathsea/tex-file.h>

#include "defaults.h"
#include "screenio.h"
#include "options.h"
#include "unixio.h"
#include "vdu.h"
#include "dvireader.h"
#include "fontreader.h"

/* Variables Exported, via vdu.h */

int DVIstatusl, windowstatusl, messagel, commandl, bottoml;
int windowh, windowv, windowwd, windowht;


static void DisplayPage ();
static void NextCommandLine ();
static boolean ShowCmdHelp ();


/*----------------------------------------------------------------------
   DECLARATIONS FOR PROCESSING USER COMMANDS

   Most commands consist of one or two characters and can be entered in
   upper or lowercase.  Multiple commands are processed in the order
   given but we only update the window, if necessary, at the end.  If a
   bad command is encountered, any further commands are ignored.  Some
   commands can have parameters; they are all dimensions in terms of the
   current units.  Spaces before and after commands and parameters are
   ignored.
*/

/* Possible commands are:                                                  */
/* i                  a positive integer; display ith DVI page             */

#define TeXpage         "["
	/* start of a TeX page specification: [i0. ... .i9]     */
#define NextPage        "N"
	/* display next DVI page, depending on direction        */
#define Window          "W"
	/* move window's top left corner to given position      */
#define Up              "U"
	/* move window up a given amount                        */
#define Down            "D"
	/* move window down a given amount                      */
#define Left            "L"
	/* move window left a given amount                      */
#define Right           "R"
	/* move window right a given amount                     */
#define Hsize           "H"
	/* set scaledwd: window's horizontal size               */
#define Vsize           "V"
	/* set scaledht: window's vertical size                 */
#define AutoView        "A"
	/* enable/disable automatic view after page selection   */
#define ZoomInOut       "Z"
	/* halve/double window dimensions                       */
#define Terse           "T"
	/* display quick and nasty chars at reference points    */
#define Box             "B"
	/* display box outlines of glyphs                       */
#define Full            "F"
	/* display all pixels in glyphs                         */
#define Ic              "I"
	/* get/show dimensions in inches                        */
#define Cm              "C"
	/* get/show dimensions in centimetres                   */
#define Mm              "M"
	/* get/show dimensions in millimetres                   */
#define PcPtPx          "P"
	/* get/show dimensions in picas/points/pixels           */
#define Help            "?"
	/* display help on available commands                   */
#define Show            "S"
	/* display useful statistics                            */
#define Quit            "Q"
	/* have a guess                                         */

#define commprompt      "Command: "


static String commstring;	/* holds user responses                   */
static int commpos;		/* current position in commstring         */
static int commlen;		/* length of commstring                   */
static char command;		/* starting character of command          */
static int maxpix;
/* maximum absolute pixel value; depends on resolution */
/* These flags are used to handle multiple commands:                       */
static boolean screenjustcleared;
	/* has screen just been cleared?          */
static boolean paintDVIStatus;	/* does DVI status line need updating?    */
static boolean paintWindowStatus;
	/* does window status line need updating? */
static boolean paintwindow;	/* does window region need updating?      */
static boolean pageoffpaper;	/* is page off paper?                     */
static boolean badcommand;	/* was there a bad command?               */


/*----------------------------------------------------------------------
   DECLARATIONS FOR DISPLAYING A PAGE

   The reference points of characters and rules on a page are stored as
   pairs of horizontal and vertical paper pixel coordinates.
   The paper coordinate scheme is described in detail in DVIReader.
   The screen coordinate scheme is described in detail in VDU.
   To update the window region, DVItoVDU maps visible paper pixels
   to screen pixels using windowh and windowv to help with translation,
   and windowwd and windowht to help with scaling.
   What the user sees depends on the current displaymode, the current size
   of the window region (scaledwd by scaledht are in paper pixels and determine
   the horizontal and vertical scaling factors), and the current paper position
   of the window region's top left corner; i.e., (windowleft,windowtop).

   A NOTE ON THE SCALING METHOD USED BY DVItoVDU:
   We desire the following conditions when scaling paper pixels to
   screen pixels:
   1. Rules/glyphs having the same top/bottom/left/right paper coordinates also
      have the same screen coordinates (e.g., to ensure baselines line up).
      This condition is incompatible with a rule/glyph staying the same
      width and height as the window position changes!  Too bad.
   2. After being scaled, visible pixel positions must not exceed the
      window region's edges.  In our case, only the bottom and right edges are
      a problem because scaling starts at the top left corner of the window.
      We use two different scaling calculations depending on
      whether the h/vscalefactors are < 1.0 or not.
   3. Scaled heights and widths must be > 0 even when h/vscalefactors
      approach 0.  If h/vscalefactors are > 1.0 then the width/height of
      paper pixels increase accordingly.
*/

/* terse - show quick and nasty chars at ref pts  */
/* box   - show box outlines of glyphs            */
/* full  - show all pixels in glyphs              */

#define  tersemode  1
#define  boxmode    2
#define  fullmode   4
int displaymode;

/* we get/show dimensions in currentunits */
units currentunits;

static int papertop, paperleft, paperbottom, paperright;
	/* these define the edges of the paper    */

static int windowtop, windowleft, windowbottom, windowright;
	/* these define the current window edges  */

static boolean allpagevisible;	/* is all of page visible in window?      */
static boolean outsidepage;	/* is entire window outside page?         */
static int scaledht;		/* current window height in paper pixels  */
static int scaledwd;		/* current window width in paper pixels   */
static double zoomfactor;	/* current zoom factor - default is 2     */
static double vscalefactor;	/* windowht / scaledht                    */
static double hscalefactor;	/* windowwd / scaledwd                    */
static ruleinfo *thisruleinfo;	/* current rule info in rulelist          */
static fontinfo *unusedfont;	/* first unused font in sorted fontlist   */
static fontinfo *thisfontinfo;	/* current font info in sorted fontlist   */
static charinfo *thischarinfo;	/* current char info in charlist          */
static int thischar;		/* current index into current chartable   */
static boolean fontopen;	/* is thisfontinfo->fontspec open?        */
static boolean useraborted;	/* did user abort page display?           */
static boolean autoviewing;	/* automatic window view enabled?         */

static char *immed_help_strings[] =
{
  DVGT_VERSION,
  "dvgt interactively views TeX-generated DVI files on some common VDUs.",
  "This is the precompiled help shown if no arguments are given.",
  "The options help file, `options.txt', gives more information.",
  "USAGE:",
  "  dvgt  filename[.dvi]",
  "        [-H x_offset]  [-V y_offset]  [-d dummy_pk]  [-e dummy_tfm]",
  "        [-i] [-k kpathsea_debug_mode] [-l]",
  "        [-m magnification]  [-r xres[,yres]]",
  "        [-t tfm_directory]  [-x paperwd]  [-y paperht]",
  "",
  "-H horizontal_offset   (default = 0.0 in)",
  "-V vertical_offset     (default = 0.0 in)",
  "-l   (set landscape mode, instead of the default portrait mode)",
  "-m magnification   (default = DVI file's intrinsic magnification)",
  "",
  "The other parameters' default values are system dependent.",
  NULL
};

static char *cmd_help_strings[] =
{
  "MISCELLANEOUS                         CHANGING PAGE DISPLAY (TOGGLES)",
  "?  Display this command help info     T  Terse - fast but inaccurate",
  "S  Show options, fonts and page info  B  Bounding Box of glyphs",
  "A  Toggle Auto window                 F  Full - accurate but slow",
  "^L Refresh screen",
  "Q  Quit from dvgt                     CHANGING UNITS OF DIMENSIONS",
  "                                      C u  Where u is one of the units",
  "SELECTING A PAGE                      BP, CM, IN, MM, PC, PT, PX, or SP",
  "[i0. ... .i9]  Select TeX page        (big point, cm, inch, mm, pica,",
"i  Select the ith DVI page            point, paper pixel, or scaled point)",
  "N  Next DVI page",
  "P  Previous DVI page                  MOVING THE WINDOW",
  "                                      W h,v  Move Window to given posn",
"CHANGING THE SIZE OF THE WINDOW              or to (minh,minv) if no h,v ",
  "H x   Set Horiz. window size to x     U v    Move window Up by v",
"      or to unscaled width if no x           or by half current ht if no v",
  "V y   Set Vertical window size to y   D v    Move window Down by v",
  "      or to unscaled height if no y          or by half cur. ht if no v",
  "ZI z  Zoom In by factor z             L h    Move window Left by h",
"      or by current factor if no z           or by half cur. width if no h",
  "ZO z  Zoom Out, as for ZI             R h    Move window Right by h",
"ZCI z, ZCO z  Zoom wrt window center         or by half cur. width if no h",
  NULL
};

/*--------------------------------------------------------------------*/

static void
ClearMessageLine ()
{
  /* Clear message line and move cursor to start of line.
     We don't show any message here; that will usually be done
     immediately after calling this routine.
   */
  ClearTextLine (messagel);
  MoveToTextLine (messagel);
}
/* ClearMessageLine */
/*--------------------------------------------------------------------*/
static void
WaitForReturn ()
{
  /* DVItoVDU has just displayed an important message.
     To ensure message is seen we wait for user to hit Return.
   */

  char ch;

  MesgFlush ();
  do
    {
      ReadChar (&ch);
    }
  while (ch != CR);
}
/* WaitForReturn */
/*--------------------------------------------------------------------*/
static boolean 
PrintText (char **text)
{
  int retval = false;

  if (text == (char **) NULL)
    {
      retval = false;		/* No text to print. */
    }
  else
    {
      /* Print each text string */
      for (; *text != (char *) NULL; text++)
	{
	  printf ("%s", *text);
	  /* If there's no newline in *text, print one. */
	  if (strchr (*text, '\n') == (char *) NULL)
	    printf ("\n");
	}
      retval = true;
    }
  return retval;
}
/* PrintText */
/*--------------------------------------------------------------------*/
static boolean 
ShowText (char **text)
{
  /* Show text of consecutive lines, in a way something like UNIX more. */
  int lines;
  char answer;

  if (text == (char **) NULL)
    {
      ClearMessageLine ();
      MesgString ("NULL text!");
      return false;
    }
  ClearScreen ();
  screenjustcleared = true;
  MoveToTextLine (1);
  rawoutoff ();

  for (lines = 0; true; lines++)
    {
      if (text[lines] == (char *) NULL)
	{			/* end of text */
	  ClearTextLine (bottoml);
	  MoveToTextLine (bottoml);
	  MesgString ("End of text,");
	  MesgString (" hit RETURN key to resume page display: ");
	  MesgFlush ();
	  do
	    {
	      ReadChar (&answer);
	    }
	  while (answer != CR);
	  break;		/* EXIT point 1 of 2 from enclosing (for) loop */
	}
      if (lines >= bottoml - 2)
	{
	  /* blank line before prompt */
	  ClearTextLine (bottoml);
	  MoveToTextLine (bottoml);

	  /* prompt */
	  MesgString ("Hit RETURN key to resume page display,");
	  MesgString (" or any other key for more text: ");
	  MesgFlush ();

	  ReadChar (&answer);
	  if (answer == CR)
	    break;		/* EXIT point 2 of 2 from enclosing (for) loop */

	  ClearScreen ();
	  screenjustcleared = true;
	  MoveToTextLine (1);
	  lines = 0;		/* reset line count */
	}
      MesgString (text[lines]);
      MesgLine ();
    }

  rawouton ();
  ClearScreen ();
  screenjustcleared = true;
  paintDVIStatus = true;
  paintWindowStatus = true;
  if (currDVIpage != 0)
    paintwindow = true;

  return true;
}
/* ShowText */

/*--------------------------------------------------------------------*/
static boolean 
ShowCmdHelp ()
{
  /* Help information is displayed in lines 1 to bottoml-2.
     We assume that bottoml is at least 3 and that VDU screen is at least
     maxline characters wide.
   */
  return ShowText (cmd_help_strings);
}
/* ShowCmdHelp */
/*--------------------------------------------------------------------*/
void
PadMesg ()
{
  /* Pad current text line with spaces. */
  String padding;
  int i;
  for (i = 0; i < maxstring; i++)
    padding[i] = ' ';
  padding[maxstring] = '\0';
  MesgString (padding);
}
/* Pad Mesg */
/*--------------------------------------------------------------------*/
static void
InitWinVars ()
{
  /* TeX will not generate dimensions > than about 38 feet, so we
     choose an absolute limit on our dimensions to be 40 feet.
   */

  int ymaxpix = yres * (40 * 12);	/* 40 ft = 40 * 12 in */
  maxpix = xres * (40 * 12);
  if (ymaxpix < maxpix)
    maxpix = ymaxpix;

  /* top left corner of paper is fixed at (-1",-1") */
  papertop = -yres;
  paperleft = -xres;

  paperbottom = papertop + paperht - 1;
  paperright = paperleft + paperwd - 1;

  /* User sees the following status values before requesting the first page. */

  /*
     FIRST STATUS LINE:  # pages, DVI page, TeX page, Auto, Displaymode, Zoom.
     Note that DVIReader has already counted the number of pages,
     and initialized currDVIpage and currTeXpage.
   */

  autoviewing = true;		/* start off enabled */
  displaymode = fullmode;	/* Full mode, neither Box nor Terse mode */
  zoomfactor = 2.0;		/* default factor for zooming is 2 */

  /*
     SECOND STATUS LINE:  Window loc. & dims, Page loc. & dims, Unit.
   */

  windowleft = 0;		/* window location */
  windowtop = 0;
  scaledwd = windowwd;		/* window size is initially unscaled */
  scaledht = windowht;

  minhp = 0;
  minvp = 0;			/* page location */
  maxhp = 0;
  maxvp = 0;
  hscalefactor = 1.0;		/* page size is initially unscaled, too */
  vscalefactor = 1.0;

  currentunits = ic;		/* inch */

  /* WINDOW:  Chars & Rules. */

  pageempty = true;		/* no page read yet, so no chars and no rules! */
}
/* InitWinVars */

/*--------------------------------------------------------------------*/
static void
UpdateDVIStatusLine ()
{
  /* Show totalpages, currDVIpage, currTeXpage, direction and displaymode. */

  int i, lastnonzero;

  ClearTextLine (DVIstatusl);
  MoveToTextLine (DVIstatusl);

  MesgInt (totalpages);
  MesgString (" pages");

  MesgString (" DVI page=");
  MesgInt (currDVIpage);

  MesgString (" TeX page=");

  MesgChar ('[');

  lastnonzero = 9;
  while (lastnonzero > 0 && currTeXpage[lastnonzero] == 0)
    {
      lastnonzero--;		/* find last counter with non-zero value */
    }
  /* always show \count0 but don't show trailing 0 counters */
  for (i = 0; i <= lastnonzero; i++)
    {
      MesgInt (currTeXpage[i]);

      if (i != lastnonzero)
	MesgChar ('.');
    }
  MesgChar (']');

  MesgString (" Auto=");
  if (autoviewing)
    MesgChar ('+');
  else
    MesgChar ('-');

  MesgString (" ");
  if (displaymode & tersemode)
    MesgString ("T");
  else
    MesgString (" ");

  if (displaymode & boxmode)
    MesgString ("B");
  else
    MesgString (" ");

  if (displaymode & fullmode)
    MesgString ("F");
  else
    MesgString (" ");

  {
    String msgstring;
    /* gt - this is surely safe from overflow of msgstring - yes? */
    sprintf (msgstring, " Zoom=%.2f", zoomfactor);
    MesgString (msgstring);
  }

  MesgLine ();
}
/* UpdateDVIStatusLine */


/*--------------------------------------------------------------------*/
static void 
WriteDimension (double precision, double res, int pixels)
{
  /* Show the given pixel dimension in terms of currentunits. */

  double realdim = 0.0;
  int fracpart;

  if (currentunits == px)
    MesgInt (pixels);
  else
    {
      switch (currentunits)
	{
	case ic:
	  realdim = (double) pixels / res;
	  break;
	case cm:
	  realdim = (double) pixels / res * 2.54;
	  break;
	case mm:
	  realdim = (double) pixels / res * 25.4;
	  break;
	case bp:
	  realdim = (double) pixels / res * 72.0;
	  break;
	case pc:
	  realdim = (double) pixels / res * 72.27 / 12.0;
	  break;
	case pt:
	  realdim = (double) pixels / res * 72.27;
	  break;
	case sp:
	  realdim = (double) pixels / res * 72.27 * 65536.0;
	  break;
	case px:
	  return;		/* can't happen */
	}			/* currentunits */
      /* gt - This seems immensely complicated, for what it's doing! */
      /* show realdim to the specified precision */
      if (fabs (realdim) < 0.5 * precision)
	MesgString ("0.0");
      else
	{
	  if (realdim < 0.0)
	    {
	      MesgChar ('-');
	      realdim = fabs (realdim);
	    }
	  realdim += 0.5 * precision;	/* round up to specified precision */
	  MesgInt ((int) realdim);	/* whole part */
	  MesgChar ('.');
	  fracpart = (int) ((realdim - (int) realdim) / precision);
	  MesgInt (fracpart);
	}			/* if */
    }				/* if */
}

/* WriteDimension */

/*--------------------------------------------------------------------*/
static void 
WriteXDim (double precision, int pixels)
{
  WriteDimension (precision, xres, pixels);
}
/* Write XDim */
/*--------------------------------------------------------------------*/
static void 
WriteYDim (double precision, int pixels)
{
  WriteDimension (precision, yres, pixels);
}
/* Write YDim */
/*--------------------------------------------------------------------*/
static void
UpdateWindowStatusLine ()
{
  /* Show current window location and size, page location and size, and units. */

  double precision = 0.1;	/* precision for status line */

  ClearTextLine (windowstatusl);
  MoveToTextLine (windowstatusl);

  MesgString ("Window at (");
  WriteXDim (precision, windowleft);
  MesgChar (',');
  WriteYDim (precision, windowtop);
  MesgString (") ");
  WriteXDim (precision, scaledwd);
  MesgString (" by ");
  WriteYDim (precision, scaledht);

  MesgString ("  Page at (");
  WriteXDim (precision, minhp);
  MesgChar (',');
  WriteYDim (precision, minvp);
  MesgString (") ");
  WriteXDim (precision, maxhp - minhp + 1);
  MesgString (" by ");
  WriteYDim (precision, maxvp - minvp + 1);
  MesgString ("  ");

  switch (currentunits)
    {
    case ic:
      MesgString ("IN");
      break;
    case cm:
      MesgString ("CM");
      break;
    case mm:
      MesgString ("MM");
      break;
    case bp:
      MesgString ("BP");
      break;
    case pc:
      MesgString ("PC");
      break;
    case pt:
      MesgString ("PT");
      break;
    case sp:
      MesgString ("SP");
      break;
    case px:
      MesgString ("PX");
      break;
    }				/* currentunits */
  MesgLine ();
}
/* UpdateWindowStatusLine */
/*--------------------------------------------------------------------*/
#define limit           2147483647
/* TeX's limit = 2^31 - 1.
   Should also be >= maxpix.
   Note that this also defines the range of
   page numbers the user can ask for! */
#define threshold       (limit / 10)	/* nearing overflow */


static boolean 
GetInteger (char *str_in, int slen, int *pos, int *n)
{
  /* Extract an integer from given str_in starting at given pos.
     pos is also used to return the position after the integer.
     If no integer is found, then set n to 0 and return FALSE
     (in that case, pos will only change if leading spaces were skipped).
     If ABS(n) > limit then set n to sign * limit.
     Valid syntax is  +{digit}  or  -{digit}  or  digit{digit}.
     Note that a + or - by itself is valid and sets n to 0.
   */

  String str;

  int absval, last, sign;
  boolean inttoobig;
  boolean intfound = false;

  memcpy (str, str_in, sizeof (String));

  while (*pos < slen && str[*pos] == ' ')
    {				/* skip any leading spaces */
      (*pos)++;
    }

  absval = 0;
  sign = 1;
  last = *pos;
  inttoobig = false;

  if (*pos < slen)
    {
      if (str[*pos] == '-')
	{
	  sign = -1;
	  last++;
	}
      else
	{
	  if (str[*pos] == '+')
	    last++;
	}

      while (last < slen && (str[last] >= '0' && str[last] <= '9'))
	{
	  if (absval > threshold || (absval == threshold && str[last] > '7'))
	    inttoobig = true;
	  else
	    absval = absval * 10 + str[last] - '0';
	  last++;
	}
    }
  if (*pos == last)
    {
      *n = 0;
      intfound = false;
    }
  else
    {
      *pos = last;
      if (inttoobig)
	absval = limit;
      *n = sign * absval;
      intfound = true;
    }

  return intfound;
}				/* GetInteger */

#undef limit
#undef threshold
/*--------------------------------------------------------------------*/
static boolean 
GetReal (char *str_in, int slen, int *pos, double *r)
{
  /* Extract a real number r from given str_in starting at given pos.
     pos is also used to return the position after the real number.
     If no number is found, then set r to 0.0 and return FALSE
     (in that case pos will only change if leading spaces were skipped).
     Valid syntax of a real number is  integer[.{digit}]  or  .{digit}
     where an integer is defined by GetInteger.
     Real numbers are truncated to 4 decimal places.
     Note that a sign or decimal point by itself is valid and sets r to 0.0.
   */

  String str;
  int sign, intpart, fracpart, divisor;
  double absreal;

  memcpy (str, str_in, strlen (str_in) + 1);

  /* GetInteger does not remember a sign by itself, so we need to check
     for -ve dimensions like -.5 first.
   */

  while (*pos < slen && str[*pos] == ' ')
    {				/* skip any spaces */
      (*pos)++;
    }

  sign = 1;
  if (*pos < slen)
    {
      if (str[*pos] == '-')
	sign = -1;
    }
  if (!GetInteger (str, slen, pos, &intpart))
    {
      if (*pos == slen || str[*pos] != '.')
	{
	  *r = 0.0;
	  return false;
	}
    }
  /* real number is valid;
     if no integer part, then intpart will be 0;
     sign = +|-1
   */
  if (*pos == slen || str[*pos] != '.')
    {
      /* no fractional part */
      absreal = (double) abs (intpart);
    }
  else
    {
      /* extract fractional part */
      (*pos)++;			/* skip over decimal point */
      divisor = 1;
      fracpart = 0;
      while (*pos < slen && (str[*pos] >= '0' && str[*pos] <= '9'))
	{
	  /* only consider up to 4 decimal places */
	  if (divisor < 10000)
	    {
	      divisor *= 10;
	      fracpart = fracpart * 10 + str[*pos] - '0';
	    }
	  (*pos)++;
	}
      absreal = (double) abs (intpart) + (double) fracpart / divisor;
    }

  *r = sign * absreal;

  return true;
}				/* GetReal */


/*--------------------------------------------------------------------*/

static boolean
GetDimension (double res, char *str_in, int slen, int *pos, int *n)
{
  /* Extract a dimension from given str_ starting at given pos.
     n returns the corresponding number of pixels in the dimension
     (which is an integer or real value in terms of currentunits);
     pos is also used to return the position after the dimension.
     If no dimension is found then set n to 0 and return FALSE (pos will only
     change if leading spaces were skipped).
     If ABS(n) > maxpix then set n to sign * maxpix.
     Valid syntax of a dimension is  integer[.{digit}]  or  .{digit}  where
     an integer is defined by GetInteger.
     Real dimensions are truncated to 4 decimal places.
     Note that a sign or decimal point by itself is valid and sets n to 0.
   */

  String str;
  int sign, intdim, fracpart, divisor;
  double absrealdim;
  boolean intpresent, dimtoobig;

  memcpy (str, str_in, sizeof (String));

  /* GetInteger does not remember a sign by itself, so we need to check
     for -ve dimensions like -.5 first.
   */

  while (*pos < slen && str[*pos] == ' ')
    {				/* skip any leading spaces */
      (*pos)++;
    }

  sign = 1;
  if (*pos < slen)
    {
      if (str[*pos] == '-')
	sign = -1;
    }
  intpresent = GetInteger (str, slen, pos, &intdim);
  if (!intpresent)
    {
      if (*pos == slen || str[*pos] != '.')
	{
	  *n = 0;
	  return false;
	}
    }				/* if */
  /* dimension is valid; if no integer part then intdim will be 0; sign = +|-1 */
  if (*pos == slen || str[*pos] != '.')
    {
      /* no fractional part */
      absrealdim = abs (intdim);
    }
  else
    {
      /* extract fractional part */
      (*pos)++;			/* skip over decimal point */
      divisor = 1;
      fracpart = 0;
      while (*pos < slen && (str[*pos] >= '0' && str[*pos] <= '9'))
	{
	  /* only consider up to 4 decimal places */
	  if (divisor < 10000)
	    {
	      divisor *= 10;
	      fracpart = fracpart * 10 + str[*pos] - '0';
	    }
	  (*pos)++;
	}			/* while */
      absrealdim = abs (intdim) + (double) fracpart / divisor;
    }				/* if */

  /* calculate n based on absrealdim, sign and currentunits */
  dimtoobig = false;
  switch (currentunits)
    {
    case ic:
      if (absrealdim > (double) maxpix / res)
	dimtoobig = true;
      else
	*n = sign * (int) (absrealdim * res + 0.5);
      break;
    case cm:
      if (absrealdim > (double) maxpix / res * 2.54)
	dimtoobig = true;
      else
	*n = sign * (int) (absrealdim / 2.54 * res + 0.5);
      break;
    case mm:
      if (absrealdim > (double) maxpix / res * 25.4)
	dimtoobig = true;
      else
	*n = sign * (int) (absrealdim / 25.4 * res + 0.5);
      break;
    case bp:
      if (absrealdim > (double) maxpix / res * 72.0)
	dimtoobig = true;
      else
	*n = sign * (int) (absrealdim / 72.0 * res + 0.5);
      break;
    case pc:
      if (absrealdim > (double) maxpix / res * (72.27 / 12.0))
	dimtoobig = true;
      else
	*n = sign * (int) (absrealdim / 72.27 * 12.0 * res + 0.5);
      break;
    case pt:
      if (absrealdim > (double) maxpix / res * 72.27)
	dimtoobig = true;
      else
	*n = sign * (int) (absrealdim / 72.27 * res + 0.5);
      break;
    case sp:
      if (absrealdim > (double) maxpix / res * 72.27 * 65536.0)
	dimtoobig = true;
      else
	*n = sign * (int) (absrealdim / (72.27 * 65536.0) * res + 0.5);
      break;
    case px:
      if (absrealdim > maxpix)
	dimtoobig = true;
      else
	*n = sign * (int) (absrealdim + 0.5);
      break;
    }				/* currentunits */

  if (dimtoobig)
    *n = sign * maxpix;

  return true;
}
/* GetDimension */

/*--------------------------------------------------------------------*/

static boolean 
GetXDim (char *str_in, int slen, int *pos, int *n)
{
  return GetDimension (xres, str_in, slen, pos, n);
}
/* GetXDim */

/*--------------------------------------------------------------------*/

static boolean 
GetYDim (char *str_in, int slen, int *pos, int *n)
{
  return GetDimension (yres, str_in, slen, pos, n);
}
/* GetYDim */

/*--------------------------------------------------------------------*/

static void
BadCommandMessage ()
{
  /* A bad command has just been detected and some sort of message displayed.
     Note that commpos is pointing to just after the problem character.
     If there are further commands then we show user what will be ignored.
   */

  int i;

  badcommand = true;

  ClearTextLine (commandl);
  MoveToTextLine (commandl);

  MesgString (commprompt);
  for (i = 0; i < commpos; i++)
    MesgChar (commstring[i]);
  MesgChar ('!');		/* put ! after the problem character */
  if (commpos < commlen)
    {
      MesgString ("   Ignoring: ");
      for (i = commpos; i < commlen; i++)
	MesgChar (commstring[i]);
    }
  NextCommandLine ();
}
/* BadCommandMessage */

/*--------------------------------------------------------------------*/

static void 
NewLocation (int newhp, int newvp)
{
  /* Change window location to given position and update window edges.
     If entire window moves outside non-empty page rectangle then outsidepage
     becomes TRUE and we restrict movement to just beyond the edge(s) so that
     user can easily move window (via Up,Down,Left,Right) to positions
     in which one or more window and page edges coincide.
     Note that allpagevisible is also updated.
   */

  outsidepage = false;
  if (currDVIpage != 0 && !pageempty)
    {
      /* check if new position puts window entirely outside edges;
         if so then minimize the movement needed to keep this true */

      if (newvp > maxvp)
	{
	  outsidepage = true;
	  newvp = maxvp + 1;
	}
      else if (newvp <= minvp - scaledht)
	{
	  outsidepage = true;
	  newvp = minvp - scaledht;
	}
      if (newhp > maxhp)
	{
	  outsidepage = true;
	  newhp = maxhp + 1;
	}
      else if (newhp <= minhp - scaledwd)
	{
	  outsidepage = true;
	  newhp = minhp - scaledwd;
	}
    }
  windowtop = newvp;
  windowleft = newhp;
  windowbottom = windowtop + scaledht - 1;
  windowright = windowleft + scaledwd - 1;
  allpagevisible = (currDVIpage != 0 && !pageempty
		    && (minvp >= windowtop && maxvp <= windowbottom)
		    && (minhp >= windowleft && maxhp <= windowright));

  /* even if pageempty or window hasn't moved we must still call DisplayPage */

  if (currDVIpage != 0)
    paintwindow = true;
}
/* NewLocation */

/*--------------------------------------------------------------------*/

static void
WindowMove ()
{
  /* Syntax of Window command is  W hpos,vpos  where hpos and vpos are
     dimensions with leading and/or trailing spaces.  If hpos,vpos absent
     then we move to minhp,minvp (top left corner of page rectangle).
   */

  int hpos, vpos;		/* move window to this new position */

  /* commpos is positioned after W */

  /* seek hpos */
  if (!GetXDim (commstring, commlen, &commpos, &hpos))
    {
      /* hpos,vpos absent - move to top left of page */
      NewLocation (minhp, minvp);
      return;
    }
  /* skip any spaces before comma */
  while (commpos < commlen && commstring[commpos] == ' ')
    commpos++;

  /* seek comma */
  if (commpos == commlen || commstring[commpos] != ',')
    {
      /* comma , (which ought to precede vpos) is missing */
      ClearMessageLine ();
      MesgString ("Comma expected!");
      if (commpos < commlen)
	commpos++;
      BadCommandMessage ();
      return;
    }
  commpos++;			/* skip over comma */

  /* seek vpos */
  if (GetYDim (commstring, commlen, &commpos, &vpos))
    {
      NewLocation (hpos, vpos);
    }
  else
    {
      /* vpos is missing or wrongly typed */
      ClearMessageLine ();
      MesgString ("Vertical coordinate expected!");
      if (commpos < commlen)
	commpos++;
      BadCommandMessage ();
    }
}
/* WindowMove */

/*--------------------------------------------------------------------*/

static void
WindowUpDown ()
{
  int amount;			/* move window up/down this many pixels */
  char STR[2];

  /* commpos is positioned after U or D */
  if (!GetYDim (commstring, commlen, &commpos, &amount))
    /* if amount absent, move by _half_ window height */
    amount = scaledht / 2;	/* for odd scaleht, this is half a pixel less */

  sprintf (STR, "%c", command);
  if (!strcmp (STR, Up))	/* move Up.  (Down is positive.) */
    amount = -amount;

  NewLocation (windowleft, windowtop + amount);
}
/* WindowUpDown */

/*--------------------------------------------------------------------*/

static void
WindowLeftRight ()
{
  int amount;			/* move window left/right this many pixels */
  char STR[2];

  /* commpos is positioned after L or R */
  if (!GetXDim (commstring, commlen, &commpos, &amount))
    /* if amount absent, move by _half_ window width */
    amount = scaledwd / 2;	/* for odd scaledwd, this is half a pixel less */

  sprintf (STR, "%c", command);
  if (!strcmp (STR, Left))	/* move Left.  (Right is positive.) */
    amount = -amount;

  NewLocation (windowleft + amount, windowtop);
}
/* WindowLeftRight */

/*--------------------------------------------------------------------*/

static void 
NewWindowWidth (int wd)
{
  /* Set window width to given value (> 0 and <= max dimension). */

  scaledwd = wd;
  hscalefactor = (double) windowwd / scaledwd;
}

/* NewWindowWidth */

/*--------------------------------------------------------------------*/

static void
SetWindowWidth ()
{
  /* Set horizontal size of window region to given dimension;
     if <= 0, then set horizontal size to 1 pixel.
     If no parameter, then use the unscaled width represented by windowwd.
   */

  int wd;

  /* commpos is positioned after H */
  if (!GetXDim (commstring, commlen, &commpos, &wd))
    {				/* parameter absent */
      NewWindowWidth (windowwd);
      return;
    }
  /* note that maximum value of wd is restricted to maxpix */
  if (wd <= 0)
    wd = 1;
  NewWindowWidth (wd);
}
/* SetWindowWidth */

/*--------------------------------------------------------------------*/

static void 
NewWindowHeight (int ht)
{
  /* Set window height to given value (> 0 and <= max dimension). */

  scaledht = ht;
  vscalefactor = (double) windowht / scaledht;
}

/* NewWindowHeight */

/*--------------------------------------------------------------------*/

static void
SetWindowHeight ()
{
  /* Set vertical size of window region to given dimension;
     if <= 0, then set vertical size to 1 pixel.
     If no parameter, then use the unscaled height represented by windowht.
   */

  int ht;

  /* commpos is positioned after V */
  if (!GetYDim (commstring, commlen, &commpos, &ht))
    {				/* parameter absent */
      NewWindowHeight (windowht);
      return;
    }
  /* note that maximum value of ht is restricted to maxpix */
  if (ht <= 0)
    ht = 1;
  NewWindowHeight (ht);
}
/* SetWindowHeight */

/*--------------------------------------------------------------------*/

static int 
ScaleHpos (int h)
{
  /* Return a scaled value for the given horizontal window coordinate. */

  if (hscalefactor > 1.0)
    return ((int) (h * hscalefactor + 0.5));
  else				/* hscalefactor <= 1.0 */
    return ((int) ((h + 0.5) * hscalefactor));
}

/* ScaleHpos */

/*--------------------------------------------------------------------*/

static int 
ScaleVpos (int v)
{
  /* Return a scaled value for the given vertical window coordinate. */

  if (vscalefactor > 1.0)
    return ((int) (v * vscalefactor + 0.5));
  else				/* vscalefactor <= 1.0 */
    return ((int) ((v + 0.5) * vscalefactor));
}

/* ScaleVpos */

/*--------------------------------------------------------------------*/

static void
SetAutoView ()
{
  /* Toggle AutoView. */

  autoviewing = (autoviewing == false ? true : false);
}

/* SetAutoView */

/*--------------------------------------------------------------------*/

static void
ZITL ()
{
  /* Zoom In, fixing Top Left of window. */

  /* scaledwd and scaledht are > 0 */
  NewWindowWidth ((int) ceil (scaledwd / zoomfactor));
  NewWindowHeight ((int) ceil (scaledht / zoomfactor));
}

/* ZITL */

/*--------------------------------------------------------------------*/

static void
ZOTL ()
{
  /* Zoom out, fixing Top Left of window. */

  /* avoid overflow *//* GT asks:  what overflow? */

  if (maxpix / zoomfactor > scaledwd)
    NewWindowWidth ((int) (scaledwd * zoomfactor));
  else
    NewWindowWidth (maxpix);

  if (maxpix / zoomfactor > scaledht)
    NewWindowHeight ((int) (scaledht * zoomfactor));
  else
    NewWindowHeight (maxpix);
}
/* ZOTL */

/*--------------------------------------------------------------------*/

static void
ZoomWindow ()
{
  /* Zoom In, or Zoom Out. */
  /* For ZI, ZO, zoom relative to top left of window. */
  /* For ZCI, ZCO, zoom relative to centre of window. */

  /* Just read a 'Z'. */
  /* Parse the rest of a ZoomInOut command and do it.
     commpos is pointing to next position in commandstr
     (and should be I or O).
   */

  String zs;			/* Zoom command string */
  char zch2 = '\0', zch3 = '\0';	/* Zoom command characters 2 and 3 */
  double zoomf;			/* Zoom Factor */
  boolean zin = true;		/* flag for Zoom direction; default = Zoom in */
  boolean zc = false;		/* flag for Zoom location; default = top left */
  boolean zok = true;		/* flag for valid Zoom; default = valid */

  zs[0] = 'Z';			/* Zoom commands begin with 'Z' */
  zs[1] = '\0';			/* properly terminate zs */

  /* read second command character, which should be 'I' or 'O'. */
  if (commpos < commlen)
    {
      zch2 = TOUPPER (commstring[commpos]);
      commpos++;
      zs[1] = zch2;
      zs[2] = '\0';
    }
  switch (zch2)
    {
    case 'I':
      zc = false;
      zin = true;
      break;
    case 'O':
      zc = false;
      zin = false;
      break;
    case 'C':
      if (commpos < commlen)
	{
	  zch3 = TOUPPER (commstring[commpos]);
	  commpos++;
	  zs[2] = zch3;
	  zs[3] = '\0';
	}
      switch (zch3)
	{
	case 'I':
	  zc = true;
	  zin = true;
	  break;
	case 'O':
	  zc = true;
	  zin = false;
	  break;
	default:
	  zok = false;
	  break;
	}
      break;
    default:
      zok = false;
      break;
    }

  if (!zok)
    {				/* invalid Z* command */
      String got;
      ClearMessageLine ();
      sprintf (got, "Read `%s', ", zs);
      MesgString (got);
      MesgString ("ZI, ZO, ZCI or ZCO expected!");
      BadCommandMessage ();
    }
  else
    {				/* valid Zoom command */
      int pos = 0;
      boolean realfound = false;

      /* skip any spaces after Zoom command */
      while (commpos < commlen && commstring[commpos] == ' ')
	commpos++;

      /* scan rest of command line for a number */
      /* this is unambiguous, b/c "zoom, goto new page" is silly on a line */
      /* fortunately, commstring is well terminated, with a NUL char */

/* GT - this is the line I once spoilt:  I wasn't advancing by characters! */
/* GT - use the real number reading code from GetDimension? */
/* static boolean GetReal (char * str_in, int slen, int * pos, double  *r) */

/*    if (sscanf (commstring+commpos, "%lf", &zoomf) == 1)    */

      pos = 0;			/* pos == new commpos - old commpos */
      realfound = GetReal (commstring + commpos, commlen - commpos, &pos, &zoomf);
      commpos += pos;

      /* Set Zoom Factor, if any. */
      if (realfound)
	{
	  if (zoomf > 1.0)
	    /* change Zoom Factor */
	    zoomfactor = zoomf;
	  else
	    {
	      /* Zooms of unity or less are rejected */
	      /* this covers zero, and avoids ZI/ZO confusion for user */
	      String msgstring;

	      /* !! GT - dangerous, as msgstring may overflow - unlikely, though */
	      sprintf (msgstring,
		    "zoom factor must > 1, so keeping old factor of %.2f\n",
		       zoomfactor);

	      ClearMessageLine ();
	      MesgString (msgstring);

	      BadCommandMessage ();
	    }
	  /* gt - signal to update status line b/c of new Zoom Factor */
	  paintDVIStatus = true;
	}

      /* Zoom! */
      if (zc)
	{			/* Zoom wrt Centre */
	  if (zin)
	    {
	      /*   ZCI = Zoom In to Centre.  Algorithm:   */
	      /* Down and Right to centre of window, */
	      /* Zoom in to top left of new window, */
	      /* Up and Left to top left of that window. */

	      NewLocation (windowleft + scaledwd / 2, windowtop + scaledht / 2);
	      ZITL ();
	      NewLocation (windowleft - scaledwd / 2, windowtop - scaledht / 2);
	    }
	  else
	    {
	      /*   ZCO = Zoom Out from Centre.  Algorithm:   */
	      /* Down and Right to centre of window, */
	      /* Zoom out from top left of new window, */
	      /* Up and Left to top left of that window. */
	      /* DEFECT:  can be altered by Zoom Out restrictions. */

	      NewLocation (windowleft + scaledwd / 2, windowtop + scaledht / 2);
	      ZOTL ();
	      NewLocation (windowleft - scaledwd / 2, windowtop - scaledht / 2);
	    }
	}
      else
	{			/* Zoom wrt Top Left */
	  /* DEFECT:  Zoom Out is restricted; see ZOTL and NewLocation code. */
	  if (zin)
	    ZITL ();		/* ZI = Zoom In to Top Left */
	  else
	    ZOTL ();		/* ZO = Zoom out from Top Left */
	}
    }
}
/* ZoomWindow */

/*--------------------------------------------------------------------*/

static boolean 
NextPageFound (boolean ascending)
{
  /* User has selected next page in DVI file; what they get will depend on
     the current DVI page and whether we are ascending or not.
     Return TRUE iff we can move to next page.
   */

  boolean found = false;

  if (currDVIpage == 1 && !ascending)
    {
      ClearMessageLine ();
      MesgString ("You are looking at first DVI page!");
      BadCommandMessage ();
      found = false;
    }
  else if (currDVIpage == totalpages && ascending)
    {
      ClearMessageLine ();
      MesgString ("You are looking at last DVI page!");
      BadCommandMessage ();
      found = false;
    }
  else
    {
      MoveToNextPage (ascending);	/* position to next DVI page */
      found = true;
    }
  return found;
}
/* NextPageFound */

/*--------------------------------------------------------------------*/

static boolean 
DVIPageFound (int n)
{
  /* User has selected a particular DVI page number.
     Move to page n and return TRUE iff n is in 1..totalpages.
   */

  boolean found = false;

  if (n < 1 || n > totalpages)
    {
      ClearMessageLine ();
      if (totalpages > 1)
	{
	  MesgString ("You can only request DVI pages 1 to ");
	  MesgInt (totalpages);
	  MesgChar ('!');
	}
      else
	{
	  MesgString ("You can only request DVI page 1!");
	}
      BadCommandMessage ();
      found = false;
    }
  else
    {
      MoveToDVIPage (n);	/* position to given DVI page */
      found = true;
    }
  return found;
}
/* DVIPageFound */

/*--------------------------------------------------------------------*/

static boolean 
ParseTeXpage (TeXpageinfo * newTeXpage)
{
  /* Return TRUE iff TeX page specification in commstring is valid.  If so then
     newTeXpage will contain the appropriate information for MoveToTeXPage.
     The syntax of a TeX page specification is [n{.n}] where n is any integer as
     defined by GetInteger.  Up to 10 integers may be given and are separated by
     periods, even if absent.  Trailing periods may be omitted.  Spaces before
     and after integers and periods are skipped.  The 10 positions correspond to
     the \count0, \count1, ... ,\count9 values that TeX stores with every page.
     commpos is initially pointing at [.
   */

  newTeXpage->lastvalue = 0;
  while (true)
    {
      commpos++;

      newTeXpage->present[(int) newTeXpage->lastvalue] =
	GetInteger (commstring, commlen, &commpos,
		    &newTeXpage->value[(int) newTeXpage->lastvalue]);

      /* commpos now at commlen, space, period, non-digit or ']' */

      while (commpos < commlen && commstring[commpos] == ' ')
	{
	  commpos++;		/* skip any spaces */
	}
      if (commpos == commlen)
	{			/* check this first! */
	  ClearMessageLine ();
	  MesgString ("] expected!");
	  BadCommandMessage ();	/* commpos at commlen */
	  return false;
	}
      if (commstring[commpos] == ']')
	{			/* end of TeX page spec */
	  commpos++;
	  break;		/* escape from enclosing "infinite" while loop */
	}
      if (newTeXpage->lastvalue >= 9)
	{
	  ClearMessageLine ();
	  MesgString ("] expected after 10 integers!");
	  commpos++;
	  BadCommandMessage ();
	  return false;
	}
      newTeXpage->lastvalue++;
      if (commstring[commpos] == '.')
	continue;
      ClearMessageLine ();
      MesgString ("Period, integer or ] expected!");
      commpos++;
      BadCommandMessage ();
      return false;
    }				/* while */

  while (newTeXpage->lastvalue > 0
	 && !newTeXpage->present[(int) newTeXpage->lastvalue])
    {
      newTeXpage->lastvalue--;
    }
  return true;
}
/* ParseTeXpage */

/*--------------------------------------------------------------------*/

static boolean
TeXPageFound ()
{
  /* Return TRUE iff TeX page specification is valid and exists.
     If so then position to lowest matching page.
   */

  boolean found = false;
  TeXpageinfo newTeXpage;

  if (ParseTeXpage (&newTeXpage))
    {				/* invalid TeX page specification */
      if (MoveToTeXPage (&newTeXpage))
	found = true;		/* we found lowest matching page */
      else
	{
	  ClearMessageLine ();
	  MesgString ("No TeX page matches your request!");
	  BadCommandMessage ();
	  found = false;
	}
    }
  else
    found = false;
  return found;
}
/* TeXPageFound */

/*--------------------------------------------------------------------*/

static int 
Min (int a, int b)
{
  /* Return the minimum value of a and b. */

  if (a < b)
    return a;
  else
    return b;
}
/* Min */

/*--------------------------------------------------------------------*/

static int 
Max (int a, int b)
{
  /* Return the maximum value of a and b. */

  if (a > b)
    return a;
  else
    return b;
}
/* Max */

/*--------------------------------------------------------------------*/

static void
ProcessPage ()
{
  /* We are ready to interpret the current DVI page and fill in the various data
     structures imported from DVIReader.  This routine will also:
     set the window size and location to useful values (if autoviewing),
     update pageoffpaper (after checking to see if it was TRUE for the previous
     page processed as part of a multiple command string),
     set screenjustcleared, paintwindow and paintWindowStatus to TRUE,
     set paintDVIStatus to FALSE.
   */

  int halfht, halfwd;

  /* We check pageoffpaper here so user can type "NNNNNNNNNNNNN..." and
     note ALL the pages that are off the paper, not just the last one
     processed.
   */
  if (pageoffpaper)
    {
      ClearMessageLine ();
      MesgString ("Page off paper!");
      WaitForReturn ();
      /* the previous page */
    }
  ClearScreen ();
  screenjustcleared = true;
  UpdateDVIStatusLine ();
  /* a MoveTo... routine has updated currDVI/TeXpage */
  paintDVIStatus = false;
  InterpretPage ();		/* fill in DVIReader's page data structures */
  SortFonts (&unusedfont);
  /* sort fonts in order of least chars and return
     pointer to first unused font */
  ClearMessageLine ();		/* clear any message */
  if (pageempty)
    {
      minhp = 0;
      maxhp = 0;
      minvp = 0;
      maxvp = 0;		/* for window status */
    }
  if (autoviewing)
    {				/* view as much of paper as possible, but without too much distortion */
      if ((paperwd < paperht && windowwd >= windowht)
	  || (paperwd == paperht && windowwd > windowht))
	{
	  halfht = paperht / 2;
	  if (paperht & 1)	/* ensure bottom visible */
	    halfht++;
	  NewWindowHeight (halfht);	/* try top half of paper */
	  NewWindowWidth (paperwd);
	  NewLocation (paperleft, papertop);	/* top left corner of paper */
	  if (!pageempty && outsidepage)	/* try moving down */
	    NewLocation (paperleft, papertop + halfht);
	}
      else if ((paperwd > paperht && windowwd <= windowht)
	       || (paperwd == paperht && windowwd < windowht))
	{
	  halfwd = paperwd / 2;
	  if (paperwd & 1)	/* ensure right visible */
	    halfwd++;
	  NewWindowHeight (paperht);
	  NewWindowWidth (halfwd);	/* try left half of paper */
	  NewLocation (paperleft, papertop);	/* top left corner of paper */
	  if (!pageempty && outsidepage)	/* try moving right */
	    NewLocation (paperleft + halfwd, papertop);
	}
      else
	{
	  /* paper shape matches unscaled window shape */
	  NewWindowHeight (paperht);	/* try all of paper */
	  NewWindowWidth (paperwd);
	  NewLocation (paperleft, papertop);	/* top left corner of paper */
	}
    }
  else
    {
      /* not autoviewing, so use current window location and size */
      NewWindowHeight (scaledht);
      NewWindowWidth (scaledwd);
      NewLocation (windowleft, windowtop);
    }

  /* check if part/all of page is off paper;
     if so, and autoviewing is enabled, then we set window size and location
     so user can just see ALL of paper AND ALL of page.
   */
  pageoffpaper = (!pageempty && ((minhp < paperleft || minvp < papertop)
			   || (maxhp > paperright || maxvp > paperbottom)));
  if (pageoffpaper && autoviewing)
    {
      NewWindowHeight (Max (maxvp, paperbottom) - Min (minvp, papertop) + 1);
      NewWindowWidth (Max (maxhp, paperright) - Min (minhp, paperleft) + 1);
      NewLocation (Min (minhp, paperleft), Min (minvp, papertop));
    }
  paintWindowStatus = true;
  paintwindow = true;
}
/* ProcessPage */

/*--------------------------------------------------------------------*/

static void
ChangeUnits ()
{
  /* Parse a C command.
     commpos is pointing to next position in commstring.
     Hope that is the start of IN, CM, MM, BP, PC, PT, SP, or PX.
   */

  char nextch1, nextch2;
  String cstr;

  /* skip any spaces between 'C' command and following unit */

  while (commpos < commlen && commstring[commpos] == ' ')
    commpos++;

  /* read next two characters */
  /* these should comprise a known unit of distance */

  if (commpos < commlen)
    {
      nextch1 = TOUPPER (commstring[commpos]);
      commpos++;
    }
  else
    nextch1 = ' ';

  if (commpos < commlen)
    {
      nextch2 = TOUPPER (commstring[commpos]);
      commpos++;
    }
  else
    nextch2 = ' ';

  sprintf (cstr, "%c%c", nextch1, nextch2);

  if (!strcmp (cstr, "IN"))
    currentunits = ic;
  else if (!strcmp (cstr, "CM"))
    currentunits = cm;
  else if (!strcmp (cstr, "MM"))
    currentunits = mm;
  else if (!strcmp (cstr, "BP"))
    currentunits = bp;
  else if (!strcmp (cstr, "PC"))
    currentunits = pc;
  else if (!strcmp (cstr, "PT"))
    currentunits = pt;
  else if (!strcmp (cstr, "SP"))
    currentunits = sp;
  else if (!strcmp (cstr, "PX"))
    currentunits = px;
  else
    {
      ClearMessageLine ();
      MesgString ("Unknown units: `");
      MesgString (cstr);
      MesgString ("'.  ");
      switch (nextch1)
	{
	case 'I':
	  MesgString ("IN");
	  break;

	case 'C':
	  MesgString ("CM");
	  break;

	case 'M':
	  MesgString ("MM");
	  break;

	case 'B':
	  MesgString ("BP");
	  break;

	case 'P':
	  MesgString ("PC, PT or PX");
	  break;

	case 'S':
	  MesgString ("SP");
	  break;

	default:
	  MesgString ("IN, CM, MM, BP, PC, PT, SP or PX");
	  break;
	}			/* command */

      MesgString (" expected.");
      BadCommandMessage ();

    }				/* strcmp (cstr, UNITNAME) */
}
/* ChangeUnits */

/*--------------------------------------------------------------------*/

static boolean 
UserHitsReturn (int *linecount)
{
  /* Do a MesgLine and return TRUE iff linecount = bottoml-2 AND user hits CR.
     If linecount < bottoml-2 then return FALSE; if not, and user hits
     something other than CR, then prepare a new screen before returning FALSE.
   */

  char ch;

  MesgLine ();
  /* test for approaching end of screen */
  if (*linecount == bottoml - 2)
    {
      /* prompt for next screen */
      MoveToTextLine (bottoml);
      MesgString ("Hit RETURN key to resume page display,");
      MesgString (" or any other key for more: ");
      MesgFlush ();

      /* read first character typed by user in response to prompt */
      ReadChar (&ch);
      if (ch == CR)
	{
	  return true;
	}
      ClearScreen ();
      screenjustcleared = true;
      MoveToTextLine (1);
      *linecount = 1;
    }
  else
    {
      (*linecount)++;
    }
  return false;
}
/* UserHitsReturn */

/*--------------------------------------------------------------------*/

static void
WriteUnits ()
{
  switch (currentunits)
    {
    case ic:
      MesgString ("in");
      break;
    case cm:
      MesgString ("cm");
      break;
    case mm:
      MesgString ("mm");
      break;
    case bp:
      MesgString ("bp");
      break;
    case pc:
      MesgString ("pc");
      break;
    case pt:
      MesgString ("pt");
      break;
    case sp:
      MesgString ("sp");
      break;
    case px:
      MesgString ("px");
      break;
    }				/* currentunits */
}
/* WriteUnits */

/*--------------------------------------------------------------------*/

static int 
WritePtSize (int scaledsize)
{
  /* Show given font size (in DVI units), in (possibly magnified) pts.
     Return length of displayed message.
   */

  double realdim;
  int fracpart;
  double precision = 0.1;
  int len = 0;

  realdim = scaledsize / 65536.0 * (mag / 1000.0);
  /* show realdim to the precision given above */
  if (fabs (realdim) < 0.5 * precision)
    {
      MesgChar ('0');
      ++len;
    }
  else
    {
      if (realdim < 0.0)
	{
	  MesgChar ('-');
	  ++len;
	  realdim = fabs (realdim);
	}
      realdim += 0.5 * precision;	/* round up to specified precision */
      len += MesgInt ((int) realdim);	/* whole part */
      fracpart = (int) ((realdim - (int) realdim) / precision);
      if (fracpart > 0)
	{
	  MesgChar ('.');
	  ++len;
	  len += MesgInt (fracpart);
	}
    }
  MesgString ("pt");
  len += 2;
  return (len);
}
/* WritePtSize */

/*--------------------------------------------------------------------*/

static void
ShowStatistics ()
{
  /* Show option values and font/character/rule/special statistics.
     UserHitsReturn controls pagination and takes the place of MesgLine.
   */

  specialinfo *temp;
  int linecount, fontcount;
  char ch;
  static char LeftStr[] = "";
  static char RightStr[] = "";
  double precision = 1.0e-3;	/* precision of quantities */

  ClearScreen ();
  screenjustcleared = true;
  MoveToTextLine (1);
  linecount = 1;

  MesgString ("DVI file           = ");
  MesgString (LeftStr);
  MesgString (DVIname);
  MesgString (RightStr);
  if (UserHitsReturn (&linecount))
    return;

  MesgString ("VDU                = ");
  MesgString (LeftStr);
  MesgString (vdu);
  MesgString (RightStr);
  if (UserHitsReturn (&linecount))
    return;

  {				/* beginblock */
    String realstring;

    MesgString ("X Resolution (dpi) = ");
    /* xres is unlikely to overflow realstring */
    sprintf (realstring, "%f", xres);
    MesgString (realstring);
    if (UserHitsReturn (&linecount))
      return;

    MesgString ("Y Resolution (dpi) = ");
    /* yres is unlikely to overflow realstring */
    sprintf (realstring, "%f", yres);
    MesgString (realstring);
    if (UserHitsReturn (&linecount))
      return;

  }				/* endblock */

  MesgString ("Magnification      = ");
  MesgInt (mag);
  if (mag == DVImag)
    {
      MesgString (" (DVI mag)");
    }
  else
    {
      MesgString (" (DVI mag of ");
      MesgInt (DVImag);
      MesgString (" was overridden)");
    }
  if (UserHitsReturn (&linecount))
    return;

  MesgString ("Dummy PK font      = ");
  MesgString (LeftStr);
  MesgString (dummy_pk);
  MesgString (RightStr);
  if (UserHitsReturn (&linecount))
    return;

  MesgString ("Dummy TFM metric   = ");
  MesgString (LeftStr);
  MesgString (dummy_tfm);
  MesgString (RightStr);
  if (UserHitsReturn (&linecount))
    return;

  MesgString ("Horizontal offset  = ");
  WriteXDim (precision, hoffset);
  WriteUnits ();
  if (UserHitsReturn (&linecount))
    return;

  MesgString ("Vertical offset    = ");
  WriteYDim (precision, voffset);
  WriteUnits ();
  if (UserHitsReturn (&linecount))
    return;

  MesgString ("Paper wd by ht     = ");
  WriteXDim (precision, paperwd);
  WriteUnits ();
  MesgString (" by ");
  WriteYDim (precision, paperht);
  WriteUnits ();
  if (UserHitsReturn (&linecount))
    return;

  MesgString ("Total fonts on ALL pages = ");
  MesgInt (totalfonts);
  if (UserHitsReturn (&linecount))
    return;

  MesgString ("Fonts, at pt size: (if on current page, give (total chars))");
  if (UserHitsReturn (&linecount))
    return;

  MesgString
    ("H: Honest, S: Substitute;  K: PK, T: TFM, D: DVI.");
  if (UserHitsReturn (&linecount))
    return;

  fontcount = 0;
  for (thisfontinfo = fontlist;
       thisfontinfo != (fontinfo *) NULL;
       thisfontinfo = thisfontinfo->nextfont)
    {
      String msgstr;		/* output string for messages */
      int len;			/* length of a displayed message */
      int maxptroom = 7;	/* room for point size message */
      int i;

      if (thisfontinfo->fontspeclen == 0)
	{			/* need to build fontspec */
	  BuildFontSpec (thisfontinfo);
	  /* fontexists may have become TRUE */
	}
      /* most font names have at most 8 characters, for ms-dos! */
      sprintf (msgstr, "%-8s", thisfontinfo->fontname);
      MesgString (msgstr);

      MesgString (" ");
      len = WritePtSize (thisfontinfo->scaledsize);
      for (i = len; i < maxptroom; i++)
	MesgChar (' ');

      MesgString ("->");

      if (thisfontinfo->fontexists)
	{
	  if (thisfontinfo->honest)
	    MesgChar ('H');
	  else			/* substitute */
	    MesgChar ('S');

	  if (thisfontinfo->pkfont)
	    MesgChar ('K');
	  else			/* non-PostScript TFM */
	    MesgChar ('T');

	  MesgString (" ");
	  i = thisfontinfo->fontspeclen - 50;	/* try to show last 70 chars */
	  if (i < 0)
	    i = 0;
	  MesgString (thisfontinfo->fontspec + i);
	}
      else
	{
	  MesgChar ('S');
	  MesgChar ('D');

	  MesgString (" ");
	  MesgString ("Terse display");
	}

      if (thisfontinfo->fontused)
	{
	  fontcount++;
	  MesgString ("  (");
	  MesgInt (thisfontinfo->totalchars);
	  MesgString (")");
	}
      if (UserHitsReturn (&linecount))
	return;
    }
  /* end (for) loop */

  if (currDVIpage == 0)
    MesgString ("You haven't selected a page yet.");
  else
    {
      MesgString ("Total fonts on current page = ");
      MesgInt (fontcount);
    }
  if (UserHitsReturn (&linecount))
    return;

  MesgString ("Total rules on current page = ");
  MesgInt (totalrules);

  if (speciallist != (specialinfo *) NULL)
    {
      if (UserHitsReturn (&linecount))
	return;

      MesgString ("\\special commands on current page: ");
      if (UserHitsReturn (&linecount))
	return;

      temp = speciallist;
      while (temp != (specialinfo *) NULL)
	{
	  MesgString ("At (");
	  WriteXDim (precision, temp->hp);
	  MesgChar (',');
	  WriteYDim (precision, temp->vp);
	  MesgString ("): ");
	  MesgString (temp->special);
	  if (UserHitsReturn (&linecount))
	    return;

	  temp = temp->nextspecial;
	}			/* while */
    }				/* if */
  MesgLine ();
  MesgLine ();
  MoveToTextLine (bottoml);
  MesgString ("Hit RETURN key to resume page display: ");
  MesgFlush ();

  do
    {
      ReadChar (&ch);
    }
  while (ch != CR);

}
/* ShowStatistics */

/*--------------------------------------------------------------------*/
/*--------------------------------------------------------------------*/

/*--------------------------------------------------------------------*/

#define edgepixel       '.'
	/* black pixel for outlines on non-graphic VDUs;
	   note that VDU TeXtoASCII['.'] = '.' */

static void
DisplayPaperEdges ()
{
  /* Display visible outlines of the imaginary sheet of paper.
     Thickness of outlines = 1 screen pixel,
     no matter what the h and v scaling.
   */

  int top, bot, left, right;	/* visible edges of paper in paper pixels */
  int scaledtop, scaledleft;	/* scaled visible edges in screen pixels */
  int scaledbot, scaledright, scaledheight;
  /* scaled width and height */
  int scaledwidth;

  /* first check if any part of paper is visible */

  if (papertop > windowbottom)
    return;

  if (paperbottom < windowtop)
    return;

  if (paperleft > windowright)
    return;

  if (paperright < windowleft)
    return;

  /* part or all of paper is visible, so return visible region */
  top = Max (papertop, windowtop);
  bot = Min (paperbottom, windowbottom);
  left = Max (paperleft, windowleft);
  right = Min (paperright, windowright);
  scaledtop = ScaleVpos (top - windowtop) + windowv;
  scaledleft = ScaleHpos (left - windowleft) + windowh;
  if (vscalefactor > 1.0)
    scaledbot = ScaleVpos (bot - windowtop + 1) + windowv - 1;
  else
    scaledbot = ScaleVpos (bot - windowtop) + windowv;
  if (hscalefactor > 1.0)
    scaledright = ScaleHpos (right - windowleft + 1) + windowh - 1;
  else
    scaledright = ScaleHpos (right - windowleft) + windowh;
  scaledheight = scaledbot - scaledtop + 1;
  scaledwidth = scaledright - scaledleft + 1;
  /* only show visible edges if they are also paper outlines */
  if (left == paperleft)
    ShowRectangle (scaledleft, scaledtop, 1, scaledheight, edgepixel);
  if (bot == paperbottom)
    ShowRectangle (scaledleft, scaledbot, scaledwidth, 1, edgepixel);
  if (top == papertop)
    ShowRectangle (scaledleft, scaledtop, scaledwidth, 1, edgepixel);
  if (right == paperright)
    ShowRectangle (scaledright, scaledtop, 1, scaledheight, edgepixel);
}
/* DisplayPaperEdges */

#undef edgepixel


/*--------------------------------------------------------------------*/

static boolean
RectangleVisible (int intop, int inbot, int inleft, int inright,
		  int *outtop, int *outbot, int *outleft, int *outright)
{
  /* Return TRUE iff part or all of given rectangle would be visible
     in the current window.  Iff so, then we also return the visible
     region; the input and possible output rectangles are defined by their
     top, bottom, left and right edges in paper pixel coordinates.
   */

  if (allpagevisible)
    {				/* all of rectangle must be visible */
      *outtop = intop;
      *outbot = inbot;
      *outleft = inleft;
      *outright = inright;
      return true;
    }
  else if (intop > windowbottom)
    return false;
  else if (inbot < windowtop)
    return false;
  else if (inleft > windowright)
    return false;
  else if (inright < windowleft)
    return false;
  else
    {
      /* part or all of rectangle is visible, so return visible region */
      *outtop = Max (intop, windowtop);
      *outbot = Min (inbot, windowbottom);
      *outleft = Max (inleft, windowleft);
      *outright = Min (inright, windowright);
      return true;
    }
}
/* RectangleVisible */

/*--------------------------------------------------------------------*/

#define RULEPIXEL       '*'
	/* black pixel for rules on non-graphic VDUs;
	   note that VDU sets TeXtoASCII['*'] := '*' */


static void
DisplayRules ()
{
  /* Display all pixels in rules, regardless of current displaymode.
     Rules will be displayed in the same order as in the DVI page (essentially
     top-down and left-right) because of the way DVIReader builds a rulelist.
   */

  int top, bottom, left, right;	/* visible edges of rule */
  int scaledtop, scaledleft;	/* scaled visible edges */
  int scaledbot, scaledright, scaledwidth, scaledheight;
  /* scaled width and height */
  int thisrule;
  char keyhit;			/* returned by BusyRead if TRUE */
  _REC_ruletable *ruletab = (_REC_ruletable *) NULL;

  thisruleinfo = rulelist;
  while (thisruleinfo != (ruleinfo *) NULL)
    {
      thisrule = 0;
      while (thisrule < thisruleinfo->rulecount)
	{
	  ruletab = &thisruleinfo->ruletable[thisrule];
	  /* check if any part of rule is visible */
	  /* vp,hp is bottom left corner of rule on page */
	  if (RectangleVisible (ruletab->vp - ruletab->ht + 1,
				ruletab->vp, ruletab->hp,
				ruletab->hp + ruletab->wd - 1,
				&top, &bottom, &left, &right))
	    {			/* rule edges */
	      /* show all pixels in this rectangle */
	      scaledtop = ScaleVpos (top - windowtop) + windowv;
	      scaledleft = ScaleHpos (left - windowleft) + windowh;

	      if (vscalefactor > 1.0)
		scaledbot = ScaleVpos (bottom - windowtop + 1) + windowv - 1;
	      else
		scaledbot = ScaleVpos (bottom - windowtop) + windowv;

	      if (hscalefactor > 1.0)
		scaledright = ScaleHpos (right - windowleft + 1) + windowh - 1;
	      else
		scaledright = ScaleHpos (right - windowleft) + windowh;

	      /* v coord of top left cnr */
	      scaledheight = scaledbot - scaledtop + 1;

	      /* h coord of top left cnr */
	      scaledwidth = scaledright - scaledleft + 1;

	      ShowRectangle (scaledleft, scaledtop, scaledwidth, scaledheight,
			     RULEPIXEL);

	      /* check keyboard after every visible rule */
	      if (BusyRead (&keyhit))
		{
		  char STR1[2];
		  keyhit = TOUPPER (keyhit);
		  sprintf (STR1, "%c", keyhit);
		  if (!strcmp (STR1, Terse))
		    {
		      displaymode ^= tersemode;		/* toggle terse mode */
		      StartText ();
		      UpdateDVIStatusLine ();
		      StartGraphics ();
		    }
		  else
		    {
		      char STR2[2];
		      sprintf (STR2, "%c", keyhit);
		      if (!strcmp (STR2, Box))
			{
			  displaymode ^= boxmode;	/* toggle box mode */
			  StartText ();
			  UpdateDVIStatusLine ();
			  StartGraphics ();
			}
		      else
			{
			  char STR3[2];
			  sprintf (STR3, "%c", keyhit);
			  if (!strcmp (STR3, Full))
			    {
			      displaymode ^= fullmode;	/* toggle full mode */
			      StartText ();
			      UpdateDVIStatusLine ();
			      StartGraphics ();
			    }
			  else if (keyhit == CR)
			    {
			      useraborted = true;	/* checked in DisplayPage */
			      return;

			    }	/* if */
			}	/* if */
		    }		/* if */
		}		/* if */
	    }			/* if */
	  /* visible rectangle */
	  thisrule++;
	}			/* while */
      thisruleinfo = thisruleinfo->nextrule;
    }				/* while */
}
/* DisplayRules */




/*--------------------------------------------------------------------*/
/* Adapted from xdvi-20.0 by Paul Vojta */
/* Keys for epsf specials */

static char *keytab[] =
{
  "clip",
  "llx",
  "lly",
  "urx",
  "ury",
  "rwi",
  "rhi",

  "hsize",
  "vsize",
  "hoffset",
  "voffset",
  "hscale",
  "vscale",
  "angle"
};

#define KEY_LLX keyval[0]
#define KEY_LLY keyval[1]
#define KEY_URX keyval[2]
#define KEY_URY keyval[3]
#define KEY_RWI keyval[4]
#define KEY_RHI keyval[5]

#define KEY_HSIZE keyval[6]
#define KEY_VSIZE keyval[7]
#define KEY_HOFFSET keyval[8]
#define KEY_VOFFSET keyval[9]
#define KEY_HSCALE keyval[10]
#define KEY_VSCALE keyval[11]
#define KEY_ANGLE keyval[12]

#define NKEYS (sizeof(keytab)/sizeof(*keytab))
#define N_ARGLESS_KEYS 1

static int 
epsf_special (char *cp, int *wd, int *ht)
{
  char *filename;
  int filenamelen = 0;
  int flags = 0;
  double keyval[NKEYS - N_ARGLESS_KEYS];

  /* skip to the file name */
  while (isspace (*cp))
    ++cp;
  if (*cp != '=')
    return 0;
  do
    ++cp;
  while (isspace (*cp));

  filename = cp;
  if (*cp == '\'' || *cp == '"')
    {
      do
	++cp;
      while (*cp != '\0' && *cp != *filename);	/* up to closing ['"] */
      ++filename;
    }
  else
    while (*cp != '\0' && *cp != ' ' && *cp != '\t')
      ++cp;
  filenamelen = cp - filename;
  while (*cp == ' ' || *cp == '\t')
    ++cp;
  while (*cp != '\0')
    {
      char *p1 = cp;
      int keyno;

      while (*p1 != '=' && !isspace (*p1) && *p1 != '\0')
	++p1;
      for (keyno = 0;; ++keyno)
	{
	  if (keyno >= NKEYS)
	    {
#if 0
	      Fprintf (stderr,
		 "%s: unknown keyword (%*s) in \\special will be ignored\n",
		       prog, (int) (p1 - cp), cp);
#endif

	      break;
	    }
	  if (strncmp (cp, keytab[keyno], p1 - cp) == 0)
	    {
	      if (keyno >= N_ARGLESS_KEYS)
		{
		  while (isspace (*p1))
		    ++p1;
		  if (*p1 == '=')
		    {
		      ++p1;
		      while (isspace (*p1))
			++p1;
		    }
		  {
		    int keyno_tmp = keyno - N_ARGLESS_KEYS;
		    keyval[keyno_tmp] = atof (p1);
		    flags |= (1 << keyno_tmp);
		  }
		}
	      break;
	    }
	}
      cp = p1;
      while (!isspace (*cp) && *cp != '\0')
	++cp;
      while (isspace (*cp))
	++cp;
    }

  if ((flags & 0x30) == 0x30 || ((flags & 0x30) && (flags & 0xf) == 0xf))
    {
      /* convert from pt to sp and next to pixels */
      *wd = XPixelRound (65536 * 0.1 * ((flags & 0x10) ? KEY_RWI
		    : KEY_RHI * (KEY_URX - KEY_LLX) / (KEY_URY - KEY_LLY)));
      *ht = YPixelRound (65536 * 0.1 * ((flags & 0x20) ? KEY_RHI
		    : KEY_RWI * (KEY_URY - KEY_LLY) / (KEY_URX - KEY_LLX)));
      return 1;
    }
  else if ((flags & 0xc0) == 0xc0)
    {
      *wd = XPixelRound (65536 * ((flags & 0x400) ? KEY_HSCALE : 1.0) * KEY_HSIZE);
      *ht = YPixelRound (65536 * ((flags & 0x800) ? KEY_VSCALE : 1.0) * KEY_VSIZE);
      return 1;
    }
  return 0;
}

/*--------------------------------------------------------------------*/
static void
DisplaySpecials ()
{
  /* Display dvips eps specials as boxes */

  int top, bottom, left, right;	/* visible edges of special */
  int scaledtop, scaledleft;	/* scaled visible edges */
  int scaledbot, scaledright, scaledwidth, scaledheight;
  /* scaled width and height */
  specialinfo *thisspecial;
  char keyhit;			/* returned by BusyRead if TRUE */

  thisspecial = speciallist;
  while (thisspecial != (specialinfo *) NULL)
    {
      int wd, ht;
      /* Using undeclared strncasecmp just as xdvik/hypertex.c does. */
      if (strncasecmp (thisspecial->special, "psfile", 6) == 0 &&
	  epsf_special (thisspecial->special + 6, &wd, &ht))
	{
	  /* check if any part of special is visible */
	  /* vp,hp is bottom left corner of special on page */
	  if (RectangleVisible (thisspecial->vp - ht + 1,
				thisspecial->vp,
				thisspecial->hp,
				thisspecial->hp + wd - 1,
				&top, &bottom, &left, &right))
	    {			/* special edges */
	      /* show all pixels in this rectangle */
	      scaledtop = ScaleVpos (top - windowtop) + windowv;
	      scaledleft = ScaleHpos (left - windowleft) + windowh;

	      if (vscalefactor > 1.0)
		scaledbot = ScaleVpos (bottom - windowtop + 1) + windowv - 1;
	      else
		scaledbot = ScaleVpos (bottom - windowtop) + windowv;

	      if (hscalefactor > 1.0)
		scaledright = ScaleHpos (right - windowleft + 1) + windowh - 1;
	      else
		scaledright = ScaleHpos (right - windowleft) + windowh;
	      /* coord of top left cnr */
	      scaledheight = scaledbot - scaledtop + 1;
	      scaledwidth = scaledright - scaledleft + 1;

	      if (left == thisspecial->hp)
		ShowRectangle (scaledleft, scaledtop, 1, scaledheight, RULEPIXEL);
	      if (bottom == thisspecial->vp)
		ShowRectangle (scaledleft, scaledbot, scaledwidth, 1, RULEPIXEL);
	      if (top == thisspecial->vp - ht + 1)
		ShowRectangle (scaledleft, scaledtop, scaledwidth, 1, RULEPIXEL);
	      if (right == thisspecial->hp + wd - 1)
		ShowRectangle (scaledright, scaledtop, 1, scaledheight, RULEPIXEL);

	      /* check keyboard after every visible special */
	      if (BusyRead (&keyhit))
		{
		  char STR1[2];
		  keyhit = TOUPPER (keyhit);
		  sprintf (STR1, "%c", keyhit);
		  if (!strcmp (STR1, Terse))
		    {
		      displaymode ^= tersemode;		/* toggle terse mode */
		      StartText ();
		      UpdateDVIStatusLine ();
		      StartGraphics ();
		    }
		  else
		    {
		      char STR2[2];
		      sprintf (STR2, "%c", keyhit);
		      if (!strcmp (STR2, Box))
			{
			  displaymode ^= boxmode;	/* toggle box mode */
			  StartText ();
			  UpdateDVIStatusLine ();
			  StartGraphics ();
			}
		      else
			{
			  char STR3[2];
			  sprintf (STR3, "%c", keyhit);
			  if (!strcmp (STR3, Full))
			    {
			      displaymode ^= fullmode;	/* toggle full mode */
			      StartText ();
			      UpdateDVIStatusLine ();
			      StartGraphics ();
			    }
			  else if (keyhit == CR)
			    {
			      useraborted = true;	/* checked in DisplayPage */
			      return;

			    }	/* if */
			}	/* if */
		    }		/* if */
		}		/* if */
	    }			/* if */
	}
      thisspecial = thisspecial->nextspecial;
    }				/* while */
}
/* DisplaySpecials */

#undef RULEPIXEL

/*--------------------------------------------------------------------*/

static boolean 
PixelVisible (int hpos, int vpos)
{
  /* Return TRUE iff given paper pixel would be visible in current window. */

  if (allpagevisible)
    return true;
  else if (vpos < windowtop)
    return false;
  else if (vpos > windowbottom)
    return false;
  else if (hpos < windowleft)
    return false;
  else if (hpos > windowright)
    return false;
  else
    return true;
}
/* PixelVisible */

/*--------------------------------------------------------------------*/

static boolean
TerseChar ()
{
  /* Display a quick and nasty representation of character,
     only if ref pt visible.
     Just how good the representation is,
     depends on the capabilities of the VDU.
     We don't bother checking
     whether glyph is actually blank or non-existent.
   */

  _REC_chartable *chartab = &thischarinfo->chartable[thischar];

  if (chartab == (_REC_chartable *) NULL)
    return false;

  if (PixelVisible (chartab->hp, chartab->vp))	/* ref pt of char is visible */
    ShowChar (ScaleHpos (chartab->hp - windowleft) + windowh,
	      ScaleVpos (chartab->vp - windowtop) + windowv,
	      chartab->code);

  return true;
}
/* TerseChar */

/*--------------------------------------------------------------------*/

static boolean
BoxChar ()
{
  /* Display visible box outlines of glyph.
     Thickness of outlines = 1 screen pixel,
     no matter what the h and v scaling.
   */

  int vpmyo, hpmxo;		/* vp-yo, hp-xo: glyph's top and left edges */
  int top, bottom, left, right;	/* visible edges of glyph */
  int scaledtop, scaledleft;	/* scaled visible edges */
  int scaledbot, scaledright, scaledheight;
  /* scaled width and height */
  int scaledwidth;
  char ch;

  _REC_chartable *chartab = &thischarinfo->chartable[thischar];
  _REC_pixeltable *pixtab = (_REC_pixeltable *) NULL;

  if (chartab == (_REC_chartable *) NULL)
    return false;

  pixtab = &thisfontinfo->pixelptr[chartab->code];
  if (pixtab == (_REC_pixeltable *) NULL)
    return false;

  if (pixtab->mapadr != 0)
    {				/* glyph present and non-blank */
      /* check if any part of glyph is visible */

      vpmyo = chartab->vp - pixtab->yo;
      hpmxo = chartab->hp - pixtab->xo;

      if (RectangleVisible (vpmyo, vpmyo + pixtab->ht - 1,
			    hpmxo, hpmxo + pixtab->wd - 1,
			    &top, &bottom, &left, &right))
	{			/* glyph edges */

	  scaledtop = ScaleVpos (top - windowtop) + windowv;
	  scaledleft = ScaleHpos (left - windowleft) + windowh;

	  if (vscalefactor > 1.0)
	    scaledbot = ScaleVpos (bottom - windowtop + 1) + windowv - 1;
	  else
	    scaledbot = ScaleVpos (bottom - windowtop) + windowv;

	  if (hscalefactor > 1.0)
	    scaledright = ScaleHpos (right - windowleft + 1) + windowh - 1;
	  else
	    scaledright = ScaleHpos (right - windowleft) + windowh;

	  scaledheight = scaledbot - scaledtop + 1;
	  scaledwidth = scaledright - scaledleft + 1;

	  /* Only show edges that are also glyph outlines!
	     Following method reduces the number of ShowRectangle calls needed for
	     very small boxes.
	   */
	  ch = chartab->code;
	  if ((scaledheight < 3
	       && (top == vpmyo && bottom == vpmyo + pixtab->ht - 1))
	      || (scaledwidth < 3
		  && (left == hpmxo && right == hpmxo + pixtab->wd - 1)))
	    {
	      ShowRectangle (scaledleft, scaledtop, scaledwidth, scaledheight, ch);
	    }
	  else
	    {
	      if (left == hpmxo)
		ShowRectangle (scaledleft, scaledtop, 1, scaledheight, ch);
	      if (bottom == vpmyo + pixtab->ht - 1)
		ShowRectangle (scaledleft, scaledbot, scaledwidth, 1, ch);
	      if (top == vpmyo)
		ShowRectangle (scaledleft, scaledtop, scaledwidth, 1, ch);
	      if (right == hpmxo + pixtab->wd - 1)
		ShowRectangle (scaledright, scaledtop, 1, scaledheight, ch);
	    }
	}
      /* visible part */
    }
  return true;
}
/* BoxChar */

/*--------------------------------------------------------------------*/

static void 
NotFound (char *fspec)
{
  StartText ();
  ResetVDU ();			/* do before message since it might erase screen! */
  FATAL1 ("Couldn't open font %s.", fspec);
}

/* NotFound */

/*--------------------------------------------------------------------*/

#define MAXVISWORDS     100
#define WORDSIZE  32

/* MAXVISWORDS * WORDSIZE = 100 * 32 = 3200 bits = maximum pixel width
   of glyph!
   If any fonts have glyphs wider than this, then increase MAXVISWORDS.
 */

/* SYSDEP: BITSET is 32 bit word with elements 31,30,29,...,0 */
typedef Word glyphrow[MAXVISWORDS];


static boolean
FullChar ()
{
  /* Display all pixels in a glyph using bitmap from font file.
     The algorithm avoids overlapping rows when vscalefactor < 1.0.
     When hscalefactor < 1.0, it is not worth the extra code to avoid
     overlapping runs of 1 bits because the majority of character glyphs
     have only one or two runs per row.
   */

  int vpmyo, hpmxo;		/* vp-yo, hp-xo: glyph's top and left edges */
  int top, bottom, left, right;	/* visible edges of glyph */
  int scaledv, scalednextv;	/* scaled vertical positions for rows */
  int scaledh = 0;		/* scaled horizontal positions within row */
  int scaledwidth, scaledheight;	/* scaled width and height of row */
  int thisrow, thisbit;		/* in paper coordinates */
  int wordsperrow;		/* rows of bitmap are word aligned */
  int firstbit, lastbit;	/* somewhere in 0 .. wordsperrow*WORDSIZE-1 */
  int firstword, lastword;	/* somewhere in 0 .. wordsperrow-1 */
  int endword;			/* = visible words in row, - 1 */
  int wordpos;			/* 0 .. endword */
  int bitpos;			/* (WORDSIZE-1) .. 0 */
  int i;

  glyphrow row;			/* holds VISIBLE bits in one row of glyph;
				   possibly > one row if vscalefactor < 1.0 */

  int_or_bptr ptr;		/* pointer into bitmap - actually a "struct" */
  boolean inrun = false;	/* are we in a run of black pixels in row? */

  _REC_chartable *chartab = &thischarinfo->chartable[thischar];
  _REC_pixeltable *pixtab = &thisfontinfo->pixelptr[chartab->code];

  if (pixtab->mapadr != 0)
    {				/* glyph present and non-blank */
      /* check if any part of glyph is visible */

      vpmyo = chartab->vp - pixtab->yo;
      hpmxo = chartab->hp - pixtab->xo;
      if (RectangleVisible (vpmyo, vpmyo + pixtab->ht - 1, hpmxo,
		      hpmxo + pixtab->wd - 1, &top, &bottom, &left, &right))
	{			/* glyph edges */
	  if (pixtab->bitmap.UU.mptr == (Word *) NULL)
	    {
	      if (!fontopen)
		{		/* dimensions of bitmap */
		  if (thisfontinfo->fontexists)
		    {
		      if (!OpenFontFile (thisfontinfo->fontspec))
			NotFound (thisfontinfo->fontspec);
		    }
		  else
		    {
		      NotFound (dummy_pk);	/* !!! */
		    }
		  fontopen = true;	/* only open font once */
		}
	      /* bitmap info in font file */
	      /* &pixtab->bitmap receives the starting address of bitmap */
	      if (!GetBitmap (pixtab->ht, pixtab->wd, pixtab->mapadr, &pixtab->bitmap))
		return false;
	    }
	  /* Words in 1 row of bitmap */
	  wordsperrow = (pixtab->wd + (WORDSIZE - 1)) / WORDSIZE;

	  firstbit = left - hpmxo;	/* first visible bit */
	  lastbit = right - hpmxo;	/* last visible bit */
	  firstword = firstbit / WORDSIZE;	/* first visible word */
	  lastword = lastbit / WORDSIZE;	/* last visible word */
	  endword = lastword - firstword;

	  /* set the visible words in row to 0 */
	  for (i = 0; i <= endword; i++)
	    row[i] = 0;
	  /* calculate scaled v coord of first visible row */
	  scaledv = ScaleVpos (top - windowtop) + windowv;

	  /* only consider visible rows; thisrow := top to bottom */
	  thisrow = top;
	  while (true)
	    {
	      /* move to first byte of first visible word in this row */
	      ptr.UU.int_ = pixtab->bitmap.UU.int_ +
		((thisrow - vpmyo) * wordsperrow + firstword) * 4;
	      /* get row of visible words from bitmap and OR with row array */
	      wordpos = 0;
	      while (true)
		{
		  row[wordpos] |= *ptr.UU.bptr;		/* set union */
		  if (wordpos == endword)
		    break;	/* escape from inner "infinite" loop */
		  wordpos++;
		  ptr.UU.int_ += 4;	/* next word */
		}
	      /* calculate scaled v coord of next row */
	      scalednextv = ScaleVpos (thisrow - windowtop + 1) + windowv;
	      scaledheight = scalednextv - scaledv;
	      if (scaledheight > 0 || thisrow == bottom)
		{
		  /* display black pixels in row, doing any h/v expansion */
		  if (scaledheight < 1)		/* avoid 0 */
		    scaledheight = 1;
		  inrun = false;
		  /* bitpos ranges over (WORDSIZE-1)..0 */
		  bitpos = (WORDSIZE - 1) - (firstbit & (WORDSIZE - 1));
		  wordpos = 0;

		  /* only consider visible bits; thisbit := left to right */
		  thisbit = left;
		  while (true)
		    {		/* bit loop */
		      if ((unsigned) bitpos < WORDSIZE
			  && ((1 << bitpos) & row[wordpos]) != 0)
			{	/* start/continue run */
			  if (!inrun)
			    {	/* remember start of run */
			      inrun = true;
			      scaledh = ScaleHpos (thisbit - windowleft) + windowh;
			    }
			}
		      else if (inrun)
			{
			  inrun = false;
			  scaledwidth = ScaleHpos (thisbit - windowleft) + windowh - scaledh;
			  if (scaledwidth < 1)	/* avoid 0 */
			    scaledwidth = 1;
			  ShowRectangle (scaledh, scaledv, scaledwidth, scaledheight,
					 chartab->code);
			}
		      if (thisbit == right)	/* EXIT bit loop */
			break;
		      if (bitpos == 0)
			{
			  wordpos++;
			  bitpos = (WORDSIZE - 1);
			}
		      else
			{	/* look at next bit in word */
			  bitpos--;
			}
		      thisbit++;
		    }		/* bit loop */

		  if (inrun)
		    {		/* show run at end of row */
		      scaledwidth = ScaleHpos (thisbit - windowleft + 1) + windowh - scaledh;
		      if (scaledwidth < 1)	/* avoid 0 */
			scaledwidth = 1;
		      ShowRectangle (scaledh, scaledv, scaledwidth, scaledheight,
				     chartab->code);
		    }
		  if (thisrow == bottom)	/* EXIT row loop */
		    break;
		  /* else reset the visible words in row to 0 */
		  for (i = 0; i <= endword; i++)
		    row[i] = 0;
		}		/* if */
	      scaledv = scalednextv;
	      thisrow++;
	    }			/* row loop */

	}			/* if */
      /* visible part */
    }
  /* 0 bit has ended run */
  return true;
}
/* FullChar */


#undef WORDSIZE
#undef MAXVISWORDS
/*--------------------------------------------------------------------*/
static void
DisplayChars ()
{
  /* Display all characters on a font by font basis.  How characters will be
     represented depends on the current displaymode (which the user can change,
     while the window is being updated, by typing the Terse/Box/Full commands).
     Fonts will be displayed in order of ascending totalchars (due to SortFonts).
     Characters in a font will be displayed in a top-down, left-right manner
     because of the way DVIReader builds a charlist.
   */

  char keyhit;			/* check for abort or mode change */

  for (thisfontinfo = fontlist;
       thisfontinfo != unusedfont;
       thisfontinfo = thisfontinfo->nextfont)
    {
      /* SortFont makes sure we only consider used fonts */

      fontopen = false;		/* might be set in FullChar */

      /* Some VDUs may be able to simulate the given font.
         To help the VDU select appropriately sized characters, we need to
         pass the scaledsize of the font (converted to unscaled paper pixels),
         the overall mag, and the current h/vscalefactors.
       */

      LoadFont (thisfontinfo->fontspec,
		XPixelRound (thisfontinfo->scaledsize),
		mag / 1000.0,
		hscalefactor,
		vscalefactor);

      /* display chars in chartable */

      for (thischarinfo = thisfontinfo->charlist;
	   thischarinfo != (charinfo *) NULL;
	   thischarinfo = thischarinfo->nextchar)
	{
	  for (thischar = 0; thischar < thischarinfo->charcount; thischar++)
	    {
	      if (thisfontinfo->fontexists)
		{
		  if (displaymode & fullmode)
		    {
		      if (thisfontinfo->pkfont)
			FullChar ();
		      else
			BoxChar ();
		    }
		  if (displaymode & tersemode)
		    {
		      TerseChar ();
		    }
		  if (displaymode & boxmode)
		    {
		      BoxChar ();
		    }
		}
	      else
		{		/* font is missing! */
		  if (displaymode & (fullmode | tersemode))
		    {
		      TerseChar ();
		    }
		  if (displaymode & boxmode)
		    {
		      BoxChar ();
		    }
		}

	      /* check for abort or mode change */
	      if (BusyRead (&keyhit))
		{
		  char STR1[2];
		  keyhit = TOUPPER (keyhit);
		  sprintf (STR1, "%c", keyhit);

		  if (!strcmp (STR1, Terse))
		    {
		      displaymode ^= tersemode;		/* toggle terse mode */
		      StartText ();
		      UpdateDVIStatusLine ();
		      StartGraphics ();
		    }
		  else if (!strcmp (STR1, Box))
		    {
		      displaymode ^= boxmode;	/* toggle box mode */
		      StartText ();
		      UpdateDVIStatusLine ();
		      StartGraphics ();
		    }
		  else if (!strcmp (STR1, Full))
		    {
		      displaymode ^= fullmode;	/* toggle full mode */
		      StartText ();
		      UpdateDVIStatusLine ();
		      StartGraphics ();
		    }
		  else if (keyhit == CR)
		    {
		      if (fontopen)
			CloseFontFile ();
		      /* no need to set useraborted; DisplayRules done first */
		      return;

		    }		/* if */
		}		/* if */
	    }			/* inner (for) loop */
	}			/* middle (for) loop */
      if (fontopen)
	CloseFontFile ();
    }				/* outer (for) loop */
}
/* DisplayChars */

/*--------------------------------------------------------------------*/
static void 
PaperMessage (double precision)
{
  /* Called by CheckPageEdges to remind user of the paper size. */

  WriteUnits ();
  MesgString ("! (Paper ");
  WriteXDim (precision, paperwd);
  MesgString (" x ");
  WriteYDim (precision, paperht);
  MesgChar (')');
  ClearMessageLine ();
  WaitForReturn ();
}

/* PaperMessage */

/*--------------------------------------------------------------------*/

static void
CheckPageEdges ()
{
  /* One or more page edges do not fall within the paper edges.
     This routine is called after the page & paper have been displayed so
     user can see how bad the problem is.
   */

  double precision = 1.0e-2;

  if (minhp < paperleft)
    {
      ClearMessageLine ();
      MesgString ("Page past paper's left edge by ");
      WriteXDim (precision, paperleft - minhp);
      PaperMessage (precision);
    }
  if (maxhp > paperright)
    {
      ClearMessageLine ();
      MesgString ("Page past paper's right edge by ");
      WriteXDim (precision, maxhp - paperright);
      PaperMessage (precision);
    }
  if (minvp < papertop)
    {
      ClearMessageLine ();
      MesgString ("Page past paper's top edge by ");
      WriteYDim (precision, papertop - minvp);
      PaperMessage (precision);
    }
  if (maxvp > paperbottom)
    {
      ClearMessageLine ();
      MesgString ("Page past paper's bottom edge by ");
      WriteYDim (precision, maxvp - paperbottom);
      PaperMessage (precision);
    }
}
/* CheckPageEdges */
/*--------------------------------------------------------------------*/
static void
DisplayPage ()
{
  /* Display page in window region based on window location and size,
     and displaymode.  This routine is only called if paintwindow is TRUE
     after all commands have been processed.
   */

  if (screenjustcleared)
    {
      /* avoid doing it again */

      if (paintDVIStatus)
	UpdateDVIStatusLine ();

      if (paintWindowStatus)
	UpdateWindowStatusLine ();
    }
  else
    {
      ClearScreen ();
      screenjustcleared = true;
      UpdateDVIStatusLine ();
      UpdateWindowStatusLine ();
    }

  StartGraphics ();
  DisplayPaperEdges ();
  StartText ();

  if (pageempty)
    {
      ClearMessageLine ();
      MesgString ("Page is empty.");
    }
  else if (outsidepage)
    {
      if (pageoffpaper)
	CheckPageEdges ();

      ClearMessageLine ();
      MesgString ("Window is ");

      if (windowtop > maxvp)
	{
	  MesgString ("below ");
	  if (windowleft > maxhp || windowleft <= minhp - scaledwd)
	    MesgString ("and ");
	}
      else if (windowtop <= minvp - scaledht)
	{
	  MesgString ("above ");
	  if (windowleft > maxhp || windowleft <= minhp - scaledwd)
	    MesgString ("and ");
	}
      if (windowleft > maxhp)
	MesgString ("to the right of ");
      else if (windowleft <= minhp - scaledwd)
	MesgString ("to the left of ");

      MesgString ("page.");
    }
  else
    {
      /* Page is not empty and part or all of it is visible. */
      StartGraphics ();

      useraborted = false;
      DisplayRules ();
      if (!useraborted)
	DisplaySpecials ();
      if (!useraborted)
	DisplayChars ();

      StartText ();

      if (pageoffpaper)
	CheckPageEdges ();	/* May write messages */

      if (allpagevisible)
	{
	  ClearMessageLine ();
	  MesgString ("Entire page is visible.  ");
	  PadMesg ();
	}
    }

  MesgFlush ();
}
/* DisplayPage */
/*--------------------------------------------------------------------*/
void 
ProcessCommandLine (String commstring)
{
  /* Parse commstring, and call the appropriate command handler
     for each command in commstring.
   */
  int n;			/* returned by GetInteger call */

  ClearMessageLine ();		/* erase message line at this stage */
  commlen = strlen (commstring);
  /* ignore any trailing spaces */
  while (commlen > 0 && commstring[commlen - 1] == ' ')
    commlen--;
  /* terminate commstring properly */
  commstring[commlen] = '\0';

  /* initialize flags for multiple command processing */
  badcommand = false;
  paintWindowStatus = false;
  paintDVIStatus = false;
  paintwindow = false;
  screenjustcleared = false;
  pageoffpaper = false;

  commpos = 0;
  while (commpos < commlen && !badcommand)
    {
      /* next command is defined by the next non-space character in commstring */
      while (commstring[commpos] == ' ')
	commpos++;		/* ignore any leading spaces */

      command = TOUPPER (commstring[commpos]);
      switch (command)
	{
	case 'W':		/* Window move */
	  commpos++;
	  WindowMove ();
	  if (!badcommand)
	    paintWindowStatus = true;
	  break;

	case 'U':		/* move Up */
	case 'D':		/* move Down */
	  commpos++;
	  WindowUpDown ();
	  paintWindowStatus = true;
	  break;

	case 'L':		/* move Left */
	case 'R':		/* move Right */
	  commpos++;
	  WindowLeftRight ();
	  paintWindowStatus = true;
	  break;

	case 'H':		/* Horizontal dimension */
	  commpos++;
	  SetWindowWidth ();
	  NewLocation (windowleft, windowtop);
	  paintWindowStatus = true;
	  break;

	case 'V':		/* Vertical dimension */
	  commpos++;
	  SetWindowHeight ();
	  NewLocation (windowleft, windowtop);
	  paintWindowStatus = true;
	  break;

	case 'A':		/* toggle Autoview on or off */
	  commpos++;
	  SetAutoView ();
	  if (!badcommand)
	    paintDVIStatus = true;
	  break;

	case 'Z':		/* Zoom in or out */
	  commpos++;
	  ZoomWindow ();
	  if (!badcommand)
	    NewLocation (windowleft, windowtop);
	  if (!badcommand)
	    paintWindowStatus = true;
	  break;

	case 'N':		/* Next page */
	  commpos++;
	  if (NextPageFound (true))	/* ascending */
	    ProcessPage ();
	  break;

	case 'P':		/* Previous page */
	  commpos++;
	  if (NextPageFound (false))	/* descending */
	    ProcessPage ();
	  break;

	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
	  /* go to page with this number, if number is valid */

	  if (GetInteger (commstring, commlen, &commpos, &n))
	    {
	      /* must be true, and commpos now after last digit */
	      if (DVIPageFound (n))
		ProcessPage ();
	    }
	  else
	    {			/* safety net */
	      ClearMessageLine ();
	      MesgString ("Expected an Integer!  Type ? for help.");
	      BadCommandMessage ();
	    }
	  break;

	case '[':		/* go to page described by count0...count9 */
	  if (TeXPageFound ())
	    /* commpos incremented in ParseTeXpage */
	    ProcessPage ();
	  break;

	case 'T':		/* Terse display */
	  commpos++;
	  displaymode ^= tersemode;	/* toggle terse mode */
	  paintDVIStatus = true;
	  if (currDVIpage != 0)
	    paintwindow = true;
	  break;

	case 'B':		/* Box display */
	  commpos++;
	  displaymode ^= boxmode;	/* toggle box mode */
	  paintDVIStatus = true;
	  if (currDVIpage != 0)
	    paintwindow = true;
	  break;

	case 'F':		/* Full display */
	  commpos++;
	  displaymode ^= fullmode;	/* toggle full mode */
	  paintDVIStatus = true;
	  if (currDVIpage != 0)
	    paintwindow = true;
	  break;

	case 'C':		/* Change units */
	  commpos++;
	  ChangeUnits ();
	  if (!badcommand)
	    paintWindowStatus = true;
	  break;

	case '?':		/* command help */
	  commpos++;
	  ShowCmdHelp ();
	  break;

	case 'S':		/* file-and-page Statistics */
	  commpos++;
	  ShowStatistics ();
	  ClearScreen ();
	  screenjustcleared = true;
	  paintDVIStatus = true;
	  paintWindowStatus = true;
	  if (currDVIpage != 0)
	    paintwindow = true;
	  break;

	case '\014':		/* ctrl-L : refresh screen */
	  commpos++;
	  DisplayPage ();	/* unconditionally, and immediately on interpretation */
	  break;

	case '\021':		/* ctrl-Q : ignore flow-control continue */
	case '\023':		/* ctrl-S : ignore flow-control suspend */
	  /* do nothing, except advance character pointer */
	  commpos++;
	  break;

	case 'Q':		/* Quit */
	  return;

	  break;

	default:		/* unknown command */
	  commpos++;
	  ClearMessageLine ();
	  MesgString ("Unknown command!  Type ? for help.");
	  BadCommandMessage ();
	  break;
	}			/* command */
    }				/* while */

  if (paintwindow)		/* only update window after processing all commands */
    DisplayPage ();
  else if (!vdu_clears_lines && (paintDVIStatus || paintWindowStatus))
    DisplayPage ();
  else
    {
      if (paintDVIStatus)
	UpdateDVIStatusLine ();
      if (paintWindowStatus)
	UpdateWindowStatusLine ();
    }
}
/* ProcessCommandLine */

/*--------------------------------------------------------------------*/

static void
NextCommandLine ()
{
  /* Prompt user for next command line, and process response */

  ClearTextLine (commandl);
  MoveToTextLine (commandl);

  MesgString (commprompt);
  MesgFlush ();

  ReadString (commstring);	/* read new command line */

  ProcessCommandLine (commstring);
}

/* NextCommandLine */

/*--------------------------------------------------------------------*/
static void
Finish ()
{
  /* close DVI file, reset VDU and restore terminal */

  CloseDVIFile ();

  /*!!!  ClearScreen(); */
  screenjustcleared = true;
  MoveToTextLine (1);
  MesgLine ();
  /*!!!  ResetVDU(); */
}

/* Finish */

/*--------------------------------------------------------------------*/
void *
Malloc (size_t n)
{
  void *MallocTemp;
  MallocTemp = malloc (n);
  if (MallocTemp)
    {
      return MallocTemp;
    }
  else
    {
      StartText ();
      ResetVDU ();		/* do before message since it might erase screen! */
      FATAL ("Out of memory.");
      return NULL;
    }
}
/*--------------------------------------------------------------------*/

int 
main (int argc, char **argv)
{
  char STR1[2];

  kpse_set_progname (argv[0]);
  kpse_init_prog ("DVGT", DEF_XRES, DEF_MFMODE, DEF_DUMMY);
  kpse_set_program_enabled (kpse_pk_format, true, kpse_src_compile);

  save_init_tty ();		/* save initial terminal settings, early */
  textlinewidth = 80;		/* for the initial screen type */
  if (!InitOptions (argc, argv))
    {				/* initialize DVIname and command options */
      /* Print the precompiled information */
      PrintText (immed_help_strings);
      return 1;
    }
  InitScreenIO ();		/* SYSDEP: sets cbreak on & echo off */

  InitDVIReader ();
  InitFontReader ();
  OpenDVIFile (DVIname);	/* and read DVImag etc. */
  if (mag == 0)			/* use DVImag */
    mag = DVImag;
  SetConversionFactors (xres, yres, mag / 1000.0);	/* for DVIReader */
  InitVDU ();			/* init windowwd/ht etc. */
  InitWinVars ();
  StartText ();
  ClearScreen ();
  screenjustcleared = true;
  UpdateDVIStatusLine ();
  UpdateWindowStatusLine ();
  MoveToTextLine (messagel);
  MesgString (DVGT_VERSION);
  MesgLine ();
  do
    {
      NextCommandLine ();	/* parse and execute command(s) */
    }
  while (strcmp ((sprintf (STR1, "%c", command), STR1), Quit));
  Finish ();
  return 0;			/* OK */
}
/* main() program of DVItoVDU */

/* end dvitovdu.c */