/* ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010, 2011 Giovanni Di Sirio. This file is part of ChibiOS/RT. ChibiOS/RT is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. ChibiOS/RT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ /** * @page concepts Kernel Concepts * @brief ChibiOS/RT Kernel Concepts * - @ref naming * - @ref api_suffixes * - @ref interrupt_classes * - @ref system_states * - @ref scheduling * - @ref thread_states * - @ref priority * - @ref warea * . * @section naming Naming Conventions * ChibiOS/RT APIs are all named following this convention: * @a ch\\\(). * The possible groups are: @a Sys, @a Sch, @a Time, @a VT, @a Thd, @a Sem, * @a Mtx, @a Cond, @a Evt, @a Msg, @a SequentialStream, @a IO, @a IQ, @a OQ, * @a Dbg, @a Core, @a Heap, @a Pool. * * @section api_suffixes API Name Suffixes * The suffix can be one of the following: * - None, APIs without any suffix can be invoked only from the user * code in the Normal state unless differently specified. See * @ref system_states. * - @anchor I-Class "I", I-Class APIs are invokable only from the * I-Locked or S-Locked states. See @ref system_states. * - @anchor S-Class "S", S-Class APIs are invokable only from the * S-Locked state. See @ref system_states. * . * Examples: @p chThdCreateStatic(), @p chSemSignalI(), @p chIQGetTimeout(). * * @section interrupt_classes Interrupt Classes * In ChibiOS/RT there are three logical interrupt classes: * - Regular Interrupts. Maskable interrupt sources that cannot * preempt (small parts of) the kernel code and are thus able to invoke * operating system APIs from within their handlers. The interrupt handlers * belonging to this class must be written following some rules. See the * @ref system APIs group and the web article * * How to write interrupt handlers. * - Fast Interrupts. Maskable interrupt sources with the ability * to preempt the kernel code and thus have a lower latency and are less * subject to jitter, see the web article * * Response Time and Jitter. * Such sources are not supported on all the architectures.
* Fast interrupts are not allowed to invoke any operating system API from * within their handlers. Fast interrupt sources may, however, pend a lower * priority regular interrupt where access to the operating system is * possible. * - Non Maskable Interrupts. Non maskable interrupt sources are * totally out of the operating system control and have the lowest latency. * Such sources are not supported on all the architectures. * . * The mapping of the above logical classes into physical interrupts priorities * is, of course, port dependent. See the documentation of the various ports * for details. * * @section system_states System States * When using ChibiOS/RT the system can be in one of the following logical * operating states: * - Init. When the system is in this state all the maskable * interrupt sources are disabled. In this state it is not possible to use * any system API except @p chSysInit(). This state is entered after a * physical reset. * - Normal. All the interrupt sources are enabled and the system APIs * are accessible, threads are running. * - Suspended. In this state the fast interrupt sources are enabled but * the regular interrupt sources are not. In this state it is not possible * to use any system API except @p chSysDisable() or @p chSysEnable() in * order to change state. * - Disabled. When the system is in this state both the maskable * regular and fast interrupt sources are disabled. In this state it is not * possible to use any system API except @p chSysSuspend() or * @p chSysEnable() in order to change state. * - Sleep. Architecture-dependent low power mode, the idle thread * goes in this state and waits for interrupts, after servicing the interrupt * the Normal state is restored and the scheduler has a chance to reschedule. * - S-Locked. Kernel locked and regular interrupt sources disabled. * Fast interrupt sources are enabled. @ref S-Class and @ref I-Class APIs are * invokable in this state. * - I-Locked. Kernel locked and regular interrupt sources disabled. * @ref I-Class APIs are invokable from this state. * - Serving Regular Interrupt. No system APIs are accessible but it is * possible to switch to the I-Locked state using @p chSysLockFromIsr() and * then invoke any @ref I-Class API. Interrupt handlers can be preemptable on * some architectures thus is important to switch to I-Locked state before * invoking system APIs. * - Serving Fast Interrupt. System APIs are not accessible. * - Serving Non-Maskable Interrupt. System APIs are not accessible. * - Halted. All interrupt sources are disabled and system stopped into * an infinite loop. This state can be reached if the debug mode is activated * and an error is detected or after explicitly invoking * @p chSysHalt(). * . * Note that the above states are just Logical States that may have no * real associated machine state on some architectures. The following diagram * shows the possible transitions between the states: * * @if LATEX_PDF * @dot digraph example { size="5, 7"; rankdir="LR"; node [shape=circle, fontname=Helvetica, fontsize=8, fixedsize="true", width="0.75", height="0.75"]; edge [fontname=Helvetica, fontsize=8]; init [label="Init", style="bold"]; norm [label="Normal", shape=doublecircle]; susp [label="Suspended"]; disab [label="Disabled"]; slock [label="S-Locked"]; ilock [label="I-Locked"]; slock [label="S-Locked"]; sleep [label="Sleep"]; sri [label="SRI"]; init -> norm [label="chSysInit()"]; norm -> slock [label="chSysLock()", constraint=false]; slock -> norm [label="chSysUnlock()"]; norm -> susp [label="chSysSuspend()"]; susp -> disab [label="chSysDisable()"]; norm -> disab [label="chSysDisable()"]; susp -> norm [label="chSysEnable()"]; disab -> norm [label="chSysEnable()"]; disab -> susp [label="chSysSuspend()"]; slock -> ilock [label="Context Switch", dir="both"]; norm -> sri [label="Regular IRQ", style="dotted"]; sri -> norm [label="Regular IRQ return", fontname=Helvetica, fontsize=8]; sri -> ilock [label="chSysLockFromIsr()", constraint=false]; ilock -> sri [label="chSysUnlockFromIsr()", fontsize=8]; norm -> sleep [label="Idle Thread"]; sleep -> sri [label="Regular IRQ", style="dotted"]; } * @enddot * @else * @dot digraph example { rankdir="LR"; node [shape=circle, fontname=Helvetica, fontsize=8, fixedsize="true", width="0.75", height="0.75"]; edge [fontname=Helvetica, fontsize=8]; init [label="Init", style="bold"]; norm [label="Normal", shape=doublecircle]; susp [label="Suspended"]; disab [label="Disabled"]; slock [label="S-Locked"]; ilock [label="I-Locked"]; slock [label="S-Locked"]; sleep [label="Sleep"]; sri [label="SRI"]; init -> norm [label="chSysInit()"]; norm -> slock [label="chSysLock()", constraint=false]; slock -> norm [label="chSysUnlock()"]; norm -> susp [label="chSysSuspend()"]; susp -> disab [label="chSysDisable()"]; norm -> disab [label="chSysDisable()"]; susp -> norm [label="chSysEnable()"]; disab -> norm [label="chSysEnable()"]; disab -> susp [label="chSysSuspend()"]; slock -> ilock [label="Context Switch", dir="both"]; norm -> sri [label="Regular IRQ", style="dotted"]; sri -> norm [label="Regular IRQ return", fontname=Helvetica, fontsize=8]; sri -> ilock [label="chSysLockFromIsr()", constraint=false]; ilock -> sri [label="chSysUnlockFromIsr()", fontsize=8]; norm -> sleep [label="Idle Thread"]; sleep -> sri [label="Regular IRQ", style="dotted"]; } * @enddot * @endif * Note, the SFI, Halted and SNMI states were not shown * because those are reachable from most states: * * @dot digraph example { size="5, 7"; rankdir="LR"; node [shape=circle, fontname=Helvetica, fontsize=8, fixedsize="true", width="0.75", height="0.75"]; edge [fontname=Helvetica, fontsize=8]; any1 [label="Any State\nexcept *"]; sfi [label="SFI"]; any1 -> sfi [style="dotted", label="Fast IRQ"]; sfi -> any1 [label="Fast IRQ return"]; } * @enddot * @dot digraph example { size="5, 7"; rankdir="LR"; node [shape=circle, fontname=Helvetica, fontsize=8, fixedsize="true", width="0.75", height="0.75"]; edge [fontname=Helvetica, fontsize=8]; any2 [label="Any State"]; halt [label="Halted"]; SNMI [label="SNMI"]; any2 -> halt [label="chSysHalt()"]; any2 -> SNMI [label="Synchronous NMI"]; any2 -> SNMI [label="Asynchronous NMI", style="dotted"]; SNMI -> any2 [label="NMI return"]; halt -> SNMI [label="Asynchronous NMI", style="dotted"]; SNMI -> halt [label="NMI return"]; } * @enddot * @attention * except: Init, Halt, SNMI, Disabled. * * @section scheduling Scheduling * The strategy is very simple the currently ready thread with the highest * priority is executed. If more than one thread with equal priority are * eligible for execution then they are executed in a round-robin way, the * CPU time slice constant is configurable. The ready list is a double linked * list of threads ordered by priority.

* @if LATEX_PDF * @dot digraph example { size="5, 7"; rankdir="LR"; node [shape=square, fontname=Helvetica, fontsize=8, fixedsize="true", width="0.6", height="0.5"]; edge [fontname=Helvetica, fontsize=8]; subgraph cluster_running { node [shape=square, fontname=Helvetica, fontsize=8, fixedsize="true", width="0.6", height="0.5"]; currp [label="'currp'\npointer", style="bold"]; T4 [label="Tuser(4)\nprio=100"]; label = "Currently Running Thread"; penwidth = 0; } subgraph cluster_rlist { node [shape=square, fontname=Helvetica, fontsize=8, fixedsize="true", width="0.6", height="0.5"]; rh [label="ready list\nheader\nprio=0", style="bold"]; Ti [label="Tidle\nprio=1"]; Tm [label="Tmain\nprio=64"]; T1 [label="Tuser(1)\nprio=32"]; T2 [label="Tuser(2)\nprio=32"]; T3 [label="Tuser(3)\nprio=80"]; label = "Threads Ready for Execution"; penwidth = 0; } currp -> T4 rh -> Ti -> T1 -> T2 -> Tm -> T3 -> rh [label="p_next"]; rh -> T3 -> Tm -> T2 -> T1 -> Ti -> rh [label="p_prev"]; } * @enddot * @else * @dot digraph example { rankdir="LR"; node [shape=square, fontname=Helvetica, fontsize=8, fixedsize="true", width="0.6", height="0.5"]; edge [fontname=Helvetica, fontsize=8]; subgraph cluster_running { node [shape=square, fontname=Helvetica, fontsize=8, fixedsize="true", width="0.6", height="0.5"]; currp [label="'currp'\npointer", style="bold"]; T4 [label="Tuser(4)\nprio=100"]; label = "Currently Running Thread"; penwidth = 0; } subgraph cluster_rlist { node [shape=square, fontname=Helvetica, fontsize=8, fixedsize="true", width="0.6", height="0.5"]; rh [label="ready list\nheader\nprio=0", style="bold"]; Ti [label="Tidle\nprio=1"]; Tm [label="Tmain\nprio=64"]; T1 [label="Tuser(1)\nprio=32"]; T2 [label="Tuser(2)\nprio=32"]; T3 [label="Tuser(3)\nprio=80"]; label = "Threads Ready for Execution"; penwidth = 0; } currp -> T4 rh -> Ti -> T1 -> T2 -> Tm -> T3 -> rh [label="p_next"]; rh -> T3 -> Tm -> T2 -> T1 -> Ti -> rh [label="p_prev"]; } * @enddot * @endif *
* Note that the currently running thread is not in the ready list, the list * only contains the threads ready to be executed but still actually waiting. * * @section thread_states Thread States * The image shows how threads can change their state in ChibiOS/RT.
* @if LATEX_PDF * @dot digraph example { size="5, 7"; rankdir="LR"; node [shape=circle, fontname=Helvetica, fontsize=8, fixedsize="true", width="0.75", height="0.75"]; edge [fontname=Helvetica, fontsize=8]; start [label="Start", style="bold"]; run [label="Running"]; ready [label="Ready"]; suspend [label="Suspended"]; sleep [label="Sleeping"]; stop [label="Stop", style="bold"]; start -> suspend [label="chThdInit()", constraint=false]; start -> run [label="chThdCreate()"]; start -> ready [label="chThdCreate()"]; run -> ready [label="Reschedule", dir="both"]; suspend -> run [label="chThdResume()"]; suspend -> ready [label="chThdResume()"]; run -> sleep [label="chSchGoSleepS()"]; sleep -> run [label="chSchWakepuS()"]; sleep -> ready [label="chSchWakepuS()"]; run -> stop [label="chThdExit()"]; } * @enddot * @else * @dot digraph example { rankdir="LR"; node [shape=circle, fontname=Helvetica, fontsize=8, fixedsize="true", width="0.75", height="0.75"]; edge [fontname=Helvetica, fontsize=8]; start [label="Start", style="bold"]; run [label="Running"]; ready [label="Ready"]; suspend [label="Suspended"]; sleep [label="Sleeping"]; stop [label="Stop", style="bold"]; start -> suspend [label="chThdInit()", constraint=false]; start -> run [label="chThdCreate()"]; start -> ready [label="chThdCreate()"]; run -> ready [label="Reschedule", dir="both"]; suspend -> run [label="chThdResume()"]; suspend -> ready [label="chThdResume()"]; run -> sleep [label="chSchGoSleepS()"]; sleep -> run [label="chSchWakepuS()"]; sleep -> ready [label="chSchWakepuS()"]; run -> stop [label="chThdExit()"]; } * @enddot * @endif * * @section priority Priority Levels * Priorities in ChibiOS/RT are a contiguous numerical range but the initial * and final values are not enforced.
* The following table describes the various priority boundaries (from lowest * to highest): * - @p IDLEPRIO, this is the lowest priority level and is reserved for the * idle thread, no other threads should share this priority level. This is * the lowest numerical value of the priorities space. * - @p LOWPRIO, the lowest priority level that can be assigned to an user * thread. * - @p NORMALPRIO, this is the central priority level for user threads. It is * advisable to assign priorities to threads as values relative to * @p NORMALPRIO, as example NORMALPRIO-1 or NORMALPRIO+4, this ensures the * portability of code should the numerical range change in future * implementations. * - @p HIGHPRIO, the highest priority level that can be assigned to an user * thread. * - @p ABSPRO, absolute maximum software priority level, it can be higher than * @p HIGHPRIO but the numerical values above @p HIGHPRIO up to @p ABSPRIO * (inclusive) are reserved. This is the highest numerical value of the * priorities space. * . * @section warea Thread Working Area * Each thread has its own stack, a Thread structure and some preemption * areas. All the structures are allocated into a "Thread Working Area", * a thread private heap, usually statically declared in your code. * Threads do not use any memory outside the allocated working area * except when accessing static shared data.

* @if LATEX_PDF * @image latex workspace.eps * @else * @image html workspace.png * @endif *
* Note that the preemption area is only present when the thread is not * running (switched out), the context switching is done by pushing the * registers on the stack of the switched-out thread and popping the registers * of the switched-in thread from its stack. * The preemption area can be divided in up to three structures: * - External Context. * - Interrupt Stack. * - Internal Context. * . * See the port documentation for details, the area may change on * the various ports and some structures may not be present (or be zero-sized). */ href='#n414'>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
/*
 * XXXXXXXXXXXXXXXXXXXXXXXXXXX
 * 
 * This is a HACKED figlet source file for Xen.
 * 
 * Hacked to output C octal strings for inclusion in a header file.
 * Support for opening zipped files is removed.
 * 
 * Go to www.figlet.org for the unhacked Figlet sources.
 */

/****************************************************************************

  FIGlet Copyright 1991, 1993, 1994 Glenn Chappell and Ian Chai
  FIGlet Copyright 1996, 1997, 1998, 1999, 2000, 2001 John Cowan
  FIGlet Copyright 2002 Christiaan Keet
  Portions written by Paul Burton and Christiaan Keet
  Internet: <info@figlet.org>
  FIGlet, along with the various FIGlet fonts and documentation, is
    copyrighted under the provisions of the Artistic License (as listed
    in the file "Artistic-license.txt" which is included in this package.
****************************************************************************/

#define DATE "13 July 2002"
#define VERSION "2.2.1"
#define VERSION_INT 20201

/* FIGlet (Frank, Ian & Glenn's Letters) */
/* by Glenn Chappell */
/* Apr 1991 */
/* Automatic file addition by Ian Chai May 1991 */
/* Punctuation and numbers addition by Ian Chai Jan 1993 */
/* Full ASCII by Glenn Chappell Feb 1993 */
/* Line-breaking, general rewrite by Glenn Chappell Mar 1993 */
/* Hard blanks by Glenn Chappell Apr 1993 */
/* Release 2.0 5 Aug 1993 */
/* Right-to-left printing, extended char set by Glenn Chappell Dec 1993 */
/* Control files by Glenn Chappell Feb 1994 */
/* Release 2.1 12 Aug 1994 */
/* Release 2.1.1 25 Aug 1994 */
/* Release 2.1.2 by Gilbert (Mad Programmer) Healton: Add -A command line 
   option.  Sept 8, 1996 */
/* Release 2.2 by John Cowan: multibyte inputs, compressed fonts,
   mapping tables, kerning/smushing options. */
/* Release 2.2.1 by Christiaan Keet: minor updates including readmes
   FAQs and comments. 13 July 2002. The new official FIGlet website is 
   http://www.figlet.org/  */

#define DEFAULTFONTDIR "."
#define DEFAULTFONTFILE "xen.flf"

#include <stdio.h>
#ifdef __STDC__
#include <stdlib.h>
#endif
#include <string.h>
#include <ctype.h>
#include <fcntl.h>     /* Needed for get_columns */

#ifdef unix
#include <sys/ioctl.h> /* Needed for get_columns */
#endif


#define ZFILE FILE
#define Zopen fopen
#define Zgetc fgetc
#define Zungetc(_x,_y) fseek(_y,-1,SEEK_CUR)
#define Zclose fclose

#define MYSTRLEN(x) ((int)strlen(x)) /* Eliminate ANSI problem */

#define DIRSEP '/'
#define DIRSEP2 '\\'
/* Leave alone for Unix and MS-DOS/Windows!
Note: '/' also used in filename in get_columns(). */

#define FONTFILESUFFIX ".flf"
#define FONTFILEMAGICNUMBER "flf2"
#define FSUFFIXLEN MYSTRLEN(FONTFILESUFFIX)
#define CONTROLFILESUFFIX ".flc"
#define CONTROLFILEMAGICNUMBER "flc2"   /* no longer used in 2.2 */
#define CSUFFIXLEN MYSTRLEN(CONTROLFILESUFFIX)
#define DEFAULTCOLUMNS 80


/****************************************************************************

  Globals dealing with chars that are read

****************************************************************************/

typedef long inchr; /* "char" read from stdin */

inchr *inchrline;  /* Alloc'd inchr inchrline[inchrlinelenlimit+1]; */
                   /* Note: not null-terminated. */
int inchrlinelen,inchrlinelenlimit;
inchr deutsch[7] = {196, 214, 220, 228, 246, 252, 223};
  /* Latin-1 codes for German letters, respectively:
     LATIN CAPITAL LETTER A WITH DIAERESIS = A-umlaut
     LATIN CAPITAL LETTER O WITH DIAERESIS = O-umlaut
     LATIN CAPITAL LETTER U WITH DIAERESIS = U-umlaut
     LATIN SMALL LETTER A WITH DIAERESIS = a-umlaut
     LATIN SMALL LETTER O WITH DIAERESIS = o-umlaut
     LATIN SMALL LETTER U WITH DIAERESIS = u-umlaut
     LATIN SMALL LETTER SHARP S = ess-zed
  */

int hzmode;  /* true if reading double-bytes in HZ mode */
int gndbl[4]; /* gndbl[n] is true if Gn is double-byte */
inchr gn[4]; /* Gn character sets: ASCII, Latin-1, none, none */
int gl; /* 0-3 specifies left-half Gn character set */
int gr; /* 0-3 specifies right-half Gn character set */

int Myargc;  /* to avoid passing around argc and argv */
char **Myargv;

/****************************************************************************

  Globals dealing with chars that are written

****************************************************************************/

typedef struct fc {
  inchr ord;
  char **thechar;  /* Alloc'd char thechar[charheight][]; */
  struct fc *next;
  } fcharnode;

fcharnode *fcharlist;
char **currchar;
int currcharwidth;
int previouscharwidth;
char **outputline;    /* Alloc'd char outputline[charheight][outlinelenlimit+1]; */
int outlinelen;


/****************************************************************************

  Globals dealing with command file storage

****************************************************************************/

typedef struct cfn {
  char *thename;
  struct cfn *next;
  } cfnamenode;

cfnamenode *cfilelist,**cfilelistend;

typedef struct cm {
  int thecommand;
  inchr rangelo;
  inchr rangehi;
  inchr offset;
  struct cm *next;
  } comnode;

comnode *commandlist,**commandlistend;

/****************************************************************************

  Globals affected by command line options

****************************************************************************/

int deutschflag,justification,paragraphflag,right2left,multibyte;
int cmdinput;

#define SM_SMUSH 128
#define SM_KERN 64
#define SM_EQUAL 1
#define SM_LOWLINE 2
#define SM_HIERARCHY 4
#define SM_PAIR 8
#define SM_BIGX 16
#define SM_HARDBLANK 32

int smushmode;

#define SMO_NO 0     /* no command-line smushmode */
#define SMO_YES 1    /* use command-line smushmode, ignore font smushmode */
#define SMO_FORCE 2  /* logically OR command-line and font smushmodes */

int smushoverride;

int outputwidth;
int outlinelenlimit;
char *fontdirname,*fontname;


/****************************************************************************

  Globals read from font file

****************************************************************************/

char hardblank;
int charheight;


/****************************************************************************

  Name of program, used in error messages

****************************************************************************/

char *myname;


#ifdef TIOCGWINSZ
/****************************************************************************

  get_columns

  Determines the number of columns of /dev/tty.  Returns the number of
  columns, or -1 if error.  May return 0 if columns unknown.
  Requires include files <fcntl.h> and <sys/ioctl.h>.
  by Glenn Chappell & Ian Chai 14 Apr 1993

****************************************************************************/

int get_columns()
{
  struct winsize ws;
  int fd,result;

  if ((fd = open("/dev/tty",O_WRONLY))<0) return -1;
  result = ioctl(fd,TIOCGWINSZ,&ws);
  close(fd);
  return result?-1:ws.ws_col;
}
#endif /* ifdef TIOCGWINSZ */


/****************************************************************************

  myalloc

  Calls malloc.  If malloc returns error, prints error message and
  quits.

****************************************************************************/

#ifdef __STDC__
char *myalloc(size_t size)
#else
char *myalloc(size)
int size;
#endif
{
  char *ptr;
#ifndef __STDC__
  extern void *malloc();
#endif

  if ((ptr = (char*)malloc(size))==NULL) {
    fprintf(stderr,"%s: Out of memory\n",myname);
    exit(1);
    }
  else {
    return ptr;
    }
}


/****************************************************************************

  hasdirsep

  Returns true if s1 contains a DIRSEP or DIRSEP2 character.

****************************************************************************/

int hasdirsep(s1)
char *s1;
{
  if (strchr(s1, DIRSEP)) return 1;
  else if (strchr(s1, DIRSEP2)) return 1;
  else return 0;
}

/****************************************************************************

  suffixcmp

  Returns true if s2 is a suffix of s1; uses case-blind comparison.

****************************************************************************/

int suffixcmp(s1, s2)
char *s1;
char *s2;
{
  int len1, len2;

  len1 = MYSTRLEN(s1);
  len2 = MYSTRLEN(s2);
  if (len2 > len1) return 0;
  s1 += len1 - len2;
  while (*s1) {
    if (tolower(*s1) != tolower(*s2)) return 0;
    s1++;
    s2++;
    }
  return 1;
}
   
/****************************************************************************

  skiptoeol

  Skips to the end of a line, given a stream.  Handles \r, \n, or \r\n.

****************************************************************************/

void skiptoeol(fp)
ZFILE *fp;
{
  int dummy;

  while (dummy=Zgetc(fp),dummy!=EOF) {
    if (dummy == '\n') return;
    if (dummy == '\r') {
      dummy = Zgetc(fp);
      if (dummy != EOF && dummy != '\n') Zungetc(dummy,fp);
      return;
      }
  }
}


/****************************************************************************

  myfgets

  Local version of fgets.  Handles \r, \n, and \r\n terminators.

****************************************************************************/

char *myfgets(line,maxlen,fp)
char *line;
int maxlen;
ZFILE *fp;
{
  int c = 0;
  char *p;

  p = line;
  while((c=Zgetc(fp))!=EOF&&maxlen) {
    *p++ = c;
    maxlen--;
    if (c=='\n') break;
    if (c=='\r') {
      c = Zgetc(fp);
      if (c != EOF && c != '\n') Zungetc(c,fp);
      *(p-1) = '\n';
      break;
      }
    }
  *p = 0;
  return (c==EOF) ? NULL : line;
}

/****************************************************************************

  usageerr

  Prints "Usage: ...." line to the given stream.

****************************************************************************/

void printusage(out)
FILE *out;
{
  fprintf(out,
    "Usage: %s [ -cklnoprstvxDELNRSWX ] [ -d fontdirectory ]\n",
    myname);
  fprintf(out,
    "              [ -f fontfile ] [ -m smushmode ] [ -w outputwidth ]\n");
  fprintf(out,
    "              [ -C controlfile ] [ -I infocode ] [ message ]\n");
}


/****************************************************************************

  printinfo

  Prints version and copyright message, or utility information.

****************************************************************************/

void printinfo(infonum)
int infonum;
{
  switch (infonum) {
    case 0: /* Copyright message */
      printf("FIGlet Copyright 1991-2002 Glenn Chappell, Ian Chai, ");
      printf("John Cowan, Christiaan Keet\n");
      printf("Internet: <info@figlet.org> ");
      printf("Version: %s, date: %s\n\n",VERSION,DATE);
      printf("FIGlet, along with the various FIGlet fonts");
      printf(" and documentation, may be\n");
      printf("freely copied and distributed.\n\n");
      printf("If you use FIGlet, please send an");
      printf(" e-mail message to <info@figlet.org>.\n\n");
      printf("The latest version of FIGlet is available from the");
      printf(" web site,\n\thttp://www.figlet.org/\n\n");
      printusage(stdout);
      break;
    case 1: /* Version (integer) */
      printf("%d\n",VERSION_INT);
      break;
    case 2: /* Font directory */
      printf("%s\n",fontdirname);
      break;
    case 3: /* Font */
      printf("%s\n",fontname);
      break;
    case 4: /* Outputwidth */
      printf("%d\n",outputwidth);
    }
}


/****************************************************************************

  readmagic

  Reads a four-character magic string from a stream.

****************************************************************************/
void readmagic(fp,magic)
ZFILE *fp;
char *magic;
{
  int i;

  for (i=0;i<4;i++) {
    magic[i] = Zgetc(fp);
    }
  magic[4] = 0;
  }
  
/****************************************************************************

  skipws

  Skips whitespace characters from a stream.

****************************************************************************/
void skipws(fp)
ZFILE *fp;
{
  int c;
  while (c=Zgetc(fp),isascii(c)&&isspace(c)) ;
  Zungetc(c,fp);
  }

/****************************************************************************

  readnum

  Reads a number from a stream.  Accepts "0" prefix for octal and
  "0x" or "0X" for hexadecimal.  Ignores leading whitespace.

****************************************************************************/
void readnum(fp,nump)
ZFILE *fp;
inchr *nump;
{
  int acc = 0;
  char *p;
  int c;
  int base;
  int sign = 1;
  char digits[] = "0123456789ABCDEF";

  skipws(fp);
  c = Zgetc(fp);
  if (c=='-') {
    sign = -1;
    }
  else {
    Zungetc(c,fp);
    }
  c = Zgetc(fp);
  if (c=='0') {
     c = Zgetc(fp);
     if (c=='x'||c=='X') {
       base = 16;
       }
     else {
       base = 8;
       Zungetc(c,fp);
       }
    }
  else {
    base = 10;
    Zungetc(c,fp);
    }

  while((c=Zgetc(fp))!=EOF) {
    c=toupper(c);
    p=strchr(digits,c);
    if (!p) {
      Zungetc(c,fp);
      *nump = acc * sign;
      return;
      }
    acc = acc*base+(p-digits);
    }
  *nump = acc * sign;
  }  

/****************************************************************************

  readTchar

  Reads a control file "T" command character specification.

  Character is a single byte, an escape sequence, or
  an escaped numeric.

****************************************************************************/

inchr readTchar(fp)
ZFILE *fp;
{
  inchr thechar;
  char next;

  thechar=Zgetc(fp);
  if (thechar=='\n' || thechar=='\r') { /* Handle badly-formatted file */
    Zungetc(thechar,fp);
    return '\0';
    }
  if (thechar!='\\') return thechar;
  next=Zgetc(fp);
  switch(next) {
    case 'a':
      return 7;
    case 'b':
      return 8;
    case 'e':
      return 27;
    case 'f':
      return 12;
    case 'n':
      return 10;
    case 'r':
      return 13;
    case 't':
      return 9;
    case 'v':
      return 11;
    default:
      if (next=='-' || next=='x' || (next>='0' && next<='9')) {
        Zungetc(next,fp);
        readnum(fp,&thechar);
        return thechar;
        }
      return next;
    }
}

/****************************************************************************

  charsetname

  Get a Tchar representing a charset name, or 0 if none available.
  Called in getcharset().

****************************************************************************/

inchr charsetname(fp)
ZFILE *fp;
{
  inchr result;

  result = readTchar(fp);
  if (result == '\n' || result == '\r') {
    result = 0;
    Zungetc(result,fp);
    }
  return result;
  }

/****************************************************************************

  charset

  Processes "g[0123]" character set specifier
  Called in readcontrol().

****************************************************************************/

void charset(n, controlfile)
int n;
ZFILE *controlfile;
{
  int ch;

  skipws(controlfile);
  if (Zgetc(controlfile) != '9') {
    skiptoeol(controlfile);
    return;
    }
  ch = Zgetc(controlfile);
  if (ch == '6') {
     gn[n] = 65536L * charsetname(controlfile) + 0x80;
     gndbl[n] = 0;
     skiptoeol(controlfile);
     return;
     }
  if (ch != '4') {
    skiptoeol(controlfile);
    return;
    }
  ch = Zgetc(controlfile);
  if (ch == 'x') {
     if (Zgetc(controlfile) != '9') {
       skiptoeol(controlfile);
       return;
       }
     if (Zgetc(controlfile) != '4') {
       skiptoeol(controlfile);
       return;
       }
     skipws(controlfile);
     gn[n] = 65536L * charsetname(controlfile);
     gndbl[n] = 1;
     skiptoeol(controlfile);
     return;
     }
  Zungetc(ch, controlfile);
  skipws(controlfile);
  gn[n] = 65536L * charsetname(controlfile);
  gndbl[n] = 0;
  return;
  }

/****************************************************************************

  readcontrol

  Allocates memory and reads in the given control file.
  Called in readcontrolfiles().

****************************************************************************/

void readcontrol(controlname)
char *controlname;
{
  inchr firstch,lastch;
  char dashcheck;
  inchr offset;
  char *controlpath,magicnum[5];
  int command;
  ZFILE *controlfile;
  int namelen;

  namelen = MYSTRLEN(fontdirname);
  controlpath = (char*)myalloc(sizeof(char)
    *(namelen+MYSTRLEN(controlname)+CSUFFIXLEN+2));
  controlfile = NULL;
  if (!hasdirsep(controlname)) {
    strcpy(controlpath,fontdirname);
    controlpath[namelen] = DIRSEP;
    controlpath[namelen+1] = '\0';
    strcat(controlpath,controlname);
    strcat(controlpath,CONTROLFILESUFFIX);
    controlfile = Zopen(controlpath,"rb");
    }
  if (controlfile==NULL) {
    strcpy(controlpath,controlname);
    strcat(controlpath,CONTROLFILESUFFIX);
    controlfile = Zopen(controlpath,"rb");
    if (controlfile==NULL) {
      fprintf(stderr,"%s: %s: Unable to open control file\n",myname,
        controlpath);
      exit(1);
      }
    }

  free(controlpath);

  (*commandlistend) = (comnode*)myalloc(sizeof(comnode));
  (*commandlistend)->thecommand = 0; /* Begin with a freeze command */
  commandlistend = &(*commandlistend)->next;
  (*commandlistend) = NULL;

  while(command=Zgetc(controlfile),command!=EOF) {
    switch (command) {
      case 't': /* Translate */
        skipws(controlfile);
        firstch=readTchar(controlfile);
        if ((dashcheck=Zgetc(controlfile))=='-') {
          lastch=readTchar(controlfile);
          }
        else {
          Zungetc(dashcheck,controlfile);
          lastch=firstch;
          }
        skipws(controlfile);
        offset=readTchar(controlfile)-firstch;
        skiptoeol(controlfile);
        (*commandlistend) = (comnode*)myalloc(sizeof(comnode));
        (*commandlistend)->thecommand = 1;
        (*commandlistend)->rangelo = firstch;
        (*commandlistend)->rangehi = lastch;
        (*commandlistend)->offset = offset;
        commandlistend = &(*commandlistend)->next;
        (*commandlistend) = NULL;
        break;
      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
      case '-':
                /* Mapping table entry */
        Zungetc(command,controlfile);
        readnum(controlfile,&firstch);
        skipws(controlfile);
	readnum(controlfile,&lastch);
	offset=lastch-firstch;
        lastch=firstch;
        skiptoeol(controlfile);
        (*commandlistend) = (comnode*)myalloc(sizeof(comnode));
        (*commandlistend)->thecommand = 1;
        (*commandlistend)->rangelo = firstch;
        (*commandlistend)->rangehi = lastch;
        (*commandlistend)->offset = offset;
        commandlistend = &(*commandlistend)->next;
        (*commandlistend) = NULL;
        break;
      case 'f': /* freeze */
        skiptoeol(controlfile);
        (*commandlistend) = (comnode*)myalloc(sizeof(comnode));
        (*commandlistend)->thecommand = 0;
        commandlistend = &(*commandlistend)->next;
        (*commandlistend) = NULL;
        break;
      case 'b': /* DBCS input mode */
        multibyte = 1;
        break;
      case 'u': /* UTF-8 input mode */
        multibyte = 2;
        break;
      case 'h': /* HZ input mode */
        multibyte = 3;
        break;
      case 'j': /* Shift-JIS input mode */
        multibyte = 4;
        break;
      case 'g': /* ISO 2022 character set choices */
        multibyte = 0;
        skipws(controlfile);
        command=Zgetc(controlfile);
        switch (command) {
          case '0': /* define G0 charset */
            charset(0, controlfile);
            break;
          case '1': /* set G1 charset */
            charset(1, controlfile);
            break;
          case '2': /* set G2 charset */
            charset(2, controlfile);
            break;
          case '3': /* set G3 charset */
            charset(3, controlfile);
            break;
          case 'l': case 'L': /* define left half */
            skipws(controlfile);
            gl = Zgetc(controlfile) - '0';
            skiptoeol(controlfile);
            break;
          case 'r': case 'R': /* define right half */
            skipws(controlfile);
            gr = Zgetc(controlfile) - '0';
            skiptoeol(controlfile);
            break;
          default: /* meaningless "g" command */
            skiptoeol(controlfile);
          }
      case '\r': case '\n': /* blank line */
        break;
      default: /* Includes '#' */
        skiptoeol(controlfile);
      }
    }
  Zclose(controlfile);
}


/****************************************************************************

  readcontrolfiles

  Reads in the controlfiles names in cfilelist.  Uses readcontrol.
  Called in main().

****************************************************************************/

void readcontrolfiles()
{
  cfnamenode *cfnptr;

  for (cfnptr=cfilelist;cfnptr!=NULL;cfnptr=cfnptr->next) {
    readcontrol(cfnptr->thename);
    }
}


/****************************************************************************

  clearcfilelist

  Clears the control file list.  Assumes thename does not need freeing.

****************************************************************************/

void clearcfilelist()
{
  cfnamenode *cfnptr1,*cfnptr2;

  cfnptr1 = cfilelist;
  while (cfnptr1 != NULL) {
    cfnptr2 = cfnptr1->next;
    free(cfnptr1);
    cfnptr1 = cfnptr2;
    }
  cfilelist = NULL;
  cfilelistend = &cfilelist;
}


/****************************************************************************

  getparams

  Handles all command-line parameters.  Puts all parameters within
  bounds.

****************************************************************************/

void getparams()
{
  extern char *optarg;
  extern int optind;
  int c; /* "Should" be a char -- need int for "!= -1" test*/
  int columns,firstfont,infoprint;
  char *controlname;

  if ((myname = strrchr(Myargv[0],DIRSEP))!=NULL) {
    myname++;
    }
  else {
    myname = Myargv[0];
    }
  fontdirname = DEFAULTFONTDIR;
  firstfont = 1;
  fontname = (char*)myalloc(sizeof(char)*(MYSTRLEN(DEFAULTFONTFILE)+1));
  strcpy(fontname,DEFAULTFONTFILE); /* Some systems don't have strdup() */
  if (suffixcmp(fontname,FONTFILESUFFIX)) {
    fontname[MYSTRLEN(fontname)-FSUFFIXLEN]='\0';
    }
  cfilelist = NULL;
  cfilelistend = &cfilelist;
  commandlist = NULL;
  commandlistend = &commandlist;
  smushoverride = SMO_NO;
  deutschflag = 0;
  justification = -1;
  right2left = -1;
  paragraphflag = 0;
  infoprint = -1;
  cmdinput = 0;
  outputwidth = DEFAULTCOLUMNS;
  gn[1] = 0x80;
  gr = 1;
  while ((c = getopt(Myargc,Myargv,"ADEXLRI:xlcrpntvm:w:d:f:C:NFskSWo"))!= -1) {
      /* Note: -F is not a legal option -- prints a special err message.  */
    switch (c) {
      case 'A':
        cmdinput = 1;
        break;
      case 'D':
        deutschflag = 1;
        break;
      case 'E':
        deutschflag = 0;
        break;
      case 'X':
        right2left = -1;
        break;
      case 'L':
        right2left = 0;
        break;
      case 'R':
        right2left = 1;
        break;
      case 'x':
        justification = -1;
        break;
      case 'l':
        justification = 0;
        break;
      case 'c':
        justification = 1;
        break;
      case 'r':
        justification = 2;
        break;
      case 'p':
        paragraphflag = 1;
        break;
      case 'n':
        paragraphflag = 0;
        break;
      case 's':
        smushoverride = SMO_NO;
        break;
      case 'k':
        smushmode = SM_KERN;
        smushoverride = SMO_YES;
        break;
      case 'S':
        smushmode = SM_SMUSH;
	smushoverride = SMO_FORCE;
        break;
      case 'o':
        smushmode = SM_SMUSH;
	smushoverride = SMO_YES;
        break;
      case 'W':
        smushmode = 0;
	smushoverride = SMO_YES;
        break;
      case 't':
#ifdef TIOCGWINSZ
        columns = get_columns();
        if (columns>0) {
          outputwidth = columns;
          }
#else /* ifdef TIOCGWINSZ */
        fprintf(stderr,
          "%s: \"-t\" is disabled, since ioctl is not fully implemented.\n",
          myname);
#endif /* ifdef TIOCGWINSZ */
        break;
      case 'v':
        infoprint = 0;
        break;
      case 'I':
        infoprint = atoi(optarg);
        break;
      case 'm':
        smushmode = atoi(optarg);
        if (smushmode < -1) {
          smushoverride = SMO_NO;
          break;
          }
	if (smushmode == 0) smushmode = SM_KERN;
	else if (smushmode == -1) smushmode = 0;
	else smushmode = (smushmode & 63) | SM_SMUSH;
	smushoverride = SMO_YES;
        break;
      case 'w':
        columns = atoi(optarg);
        if (columns>0) {
          outputwidth = columns;
          }
        break;
      case 'd':
        fontdirname = optarg;
        break;
      case 'f':
        if (firstfont) {
          free(fontname);
          firstfont = 0;
          }
        fontname = optarg;
        if (suffixcmp(fontname,FONTFILESUFFIX)) {
          fontname[MYSTRLEN(fontname)-FSUFFIXLEN] = '\0';
          }
        break;
      case 'C':
        controlname = optarg;
        if (suffixcmp(controlname, CONTROLFILESUFFIX)) {
          controlname[MYSTRLEN(controlname)-CSUFFIXLEN] = '\0';
          }
        (*cfilelistend) = (cfnamenode*)myalloc(sizeof(cfnamenode));
        (*cfilelistend)->thename = controlname;
        cfilelistend = &(*cfilelistend)->next;
        (*cfilelistend) = NULL;
        break;
      case 'N':
        clearcfilelist();
        multibyte = 0;
        gn[0] = 0;
        gn[1] = 0x80;
        gn[2] = gn[3] = 0;
        gndbl[0] = gndbl[1] = gndbl[2] = gndbl[3] = 0;
        gl = 0;
        gr = 1;
        break;
      case 'F': /* Not a legal option */
        fprintf(stderr,"%s: illegal option -- F\n",myname);
        printusage(stderr);
        fprintf(stderr,"\nBecause of numerous incompatibilities, the");
        fprintf(stderr," \"-F\" option has been\n");
        fprintf(stderr,"removed.  It has been replaced by the \"figlist\"");
        fprintf(stderr," program, which is now\n");
        fprintf(stderr,"included in the basic FIGlet package.  \"figlist\"");
        fprintf(stderr," is also available\n");
        fprintf(stderr,"from  http://www.figlet.org/");
        fprintf(stderr,"under UNIX utilities.\n");
        exit(1);
        break;
      default:
        printusage(stderr);
        exit(1);
      }
    }
  if (optind!=Myargc) cmdinput = 1; /* force cmdinput if more arguments */
  outlinelenlimit = outputwidth-1;
  if (infoprint>=0) {
    printinfo(infoprint);
    exit(0);
    }
}


/****************************************************************************

  clearline

  Clears both the input (inchrline) and output (outputline) storage.

****************************************************************************/

void clearline()
{
  int i;

  for (i=0;i<charheight;i++) {
    outputline[i][0] = '\0';
    }
  outlinelen = 0;
  inchrlinelen = 0;
}


/****************************************************************************

  readfontchar

  Reads a font character from the font file, and places it in a
  newly-allocated entry in the list.

****************************************************************************/

void readfontchar(file,theord,line,maxlen)
ZFILE *file;
inchr theord;
char *line;
int maxlen;
{
  int row,k;
  char endchar;
  fcharnode *fclsave;

  fclsave = fcharlist;
  fcharlist = (fcharnode*)myalloc(sizeof(fcharnode));
  fcharlist->ord = theord;
  fcharlist->thechar = (char**)myalloc(sizeof(char*)*charheight);
  fcharlist->next = fclsave;
  for (row=0;row<charheight;row++) {
    if (myfgets(line,maxlen+1,file)==NULL) {
      line[0] = '\0';
      }
    k = MYSTRLEN(line)-1;
    while (k>=0 && isspace(line[k])) {
      k--;
      }
    if (k>=0) {
      endchar = line[k];
      while (k>=0 ? line[k]==endchar : 0) {
        k--;
        }
      }
    line[k+1] = '\0';
    fcharlist->thechar[row] = (char*)myalloc(sizeof(char)*(k+2));
    strcpy(fcharlist->thechar[row],line);
    }
}


/****************************************************************************

  readfont

  Allocates memory, initializes variables, and reads in the font.
  Called near beginning of main().

****************************************************************************/

void readfont()
{
#define MAXFIRSTLINELEN 1000
  int i,row,numsread;
  inchr theord;
  int maxlen,cmtlines,ffright2left;
  int smush,smush2;
  char *fontpath,*fileline,magicnum[5];
  ZFILE *fontfile;
  int namelen;

  namelen = MYSTRLEN(fontdirname);
  fontpath = (char*)myalloc(sizeof(char)
    *(namelen+MYSTRLEN(fontname)+FSUFFIXLEN+2));
  fontfile = NULL;
  if (!hasdirsep(fontname)) {
    strcpy(fontpath,fontdirname);
    fontpath[namelen] = DIRSEP;
    fontpath[namelen+1] = '\0';
    strcat(fontpath,fontname);
    strcat(fontpath,FONTFILESUFFIX);
    fontfile = Zopen(fontpath,"rb");
    }
  if (fontfile==NULL) {
    strcpy(fontpath,fontname);
    strcat(fontpath,FONTFILESUFFIX);
    fontfile = Zopen(fontpath,"rb");
    if (fontfile==NULL) {
      fprintf(stderr,"%s: %s: Unable to open font file\n",myname,fontpath);
      exit(1);
      }
    }

  readmagic(fontfile,magicnum);
  fileline = (char*)myalloc(sizeof(char)*(MAXFIRSTLINELEN+1));
  if (myfgets(fileline,MAXFIRSTLINELEN+1,fontfile)==NULL) {
    fileline[0] = '\0';
    }
  if (MYSTRLEN(fileline)>0 ? fileline[MYSTRLEN(fileline)-1]!='\n' : 0) {
    skiptoeol(fontfile);
    }
  numsread = sscanf(fileline,"%*c%c %d %*d %d %d %d %d %d",
    &hardblank,&charheight,&maxlen,&smush,&cmtlines,
    &ffright2left,&smush2);
  free(fileline);
  if (strcmp(magicnum,FONTFILEMAGICNUMBER) || numsread<5) {
    fprintf(stderr,"%s: %s: Not a FIGlet 2 font file\n",myname,fontpath);
    exit(1);
    }
  for (i=1;i<=cmtlines;i++) {
    skiptoeol(fontfile);
    }
  free(fontpath);

  if (numsread<6) {
    ffright2left = 0;
    }

  if (numsread<7) { /* if no smush2, decode smush into smush2 */
    if (smush == 0) smush2 = SM_KERN;
    else if (smush < 0) smush2 = 0;
    else smush2 = (smush & 31) | SM_SMUSH;
    }

  if (charheight<1) {
    charheight = 1;
    }

  if (maxlen<1) {
    maxlen = 1;
    }

  maxlen += 100; /* Give ourselves some extra room */

  if (smushoverride == SMO_NO)
     smushmode = smush2;
  else if (smushoverride == SMO_FORCE)
     smushmode |= smush2;

  if (right2left<0) {
    right2left = ffright2left;
    }

  if (justification<0) {
    justification = 2*right2left;
    }

  fileline = (char*)myalloc(sizeof(char)*(maxlen+1));
  /* Allocate "missing" character */
  fcharlist = (fcharnode*)myalloc(sizeof(fcharnode));
  fcharlist->ord = 0;
  fcharlist->thechar = (char**)myalloc(sizeof(char*)*charheight);
  fcharlist->next = NULL;
  for (row=0;row<charheight;row++) {
    fcharlist->thechar[row] = (char*)myalloc(sizeof(char));
    fcharlist->thechar[row][0] = '\0';
    }
  for (theord=' ';theord<='~';theord++) {
    readfontchar(fontfile,theord,fileline,maxlen);
    }
  for (theord=0;theord<=6;theord++) {
    readfontchar(fontfile,deutsch[theord],fileline,maxlen);
    }
  while (myfgets(fileline,maxlen+1,fontfile)==NULL?0:
    sscanf(fileline,"%li",&theord)==1) {
    readfontchar(fontfile,theord,fileline,maxlen);
    }
  Zclose(fontfile);
  free(fileline);
}


/****************************************************************************

  linealloc

  Allocates & clears outputline, inchrline. Sets inchrlinelenlimit.
  Called near beginning of main().

****************************************************************************/

void linealloc()
{
  int row; 

  outputline = (char**)myalloc(sizeof(char*)*charheight);
  for (row=0;row<charheight;row++) {
    outputline[row] = (char*)myalloc(sizeof(char)*(outlinelenlimit+1));
    }
  inchrlinelenlimit = outputwidth*4+100;
  inchrline = (inchr*)myalloc(sizeof(inchr)*(inchrlinelenlimit+1));
  clearline();
}


/****************************************************************************

  getletter

  Sets currchar to point to the font entry for the given character.
  Sets currcharwidth to the width of this character.

****************************************************************************/

void getletter(c)
inchr c;
{
  fcharnode *charptr;

  for (charptr=fcharlist;charptr==NULL?0:charptr->ord!=c;
    charptr=charptr->next) ;
  if (charptr!=NULL) {
    currchar = charptr->thechar;
    }
  else {
    for (charptr=fcharlist;charptr==NULL?0:charptr->ord!=0;
      charptr=charptr->next) ;
    currchar = charptr->thechar;
    }
  previouscharwidth = currcharwidth;
  currcharwidth = MYSTRLEN(currchar[0]);
}


/****************************************************************************

  smushem

  Given 2 characters, attempts to smush them into 1, according to
  smushmode.  Returns smushed character or '\0' if no smushing can be
  done.

  smushmode values are sum of following (all values smush blanks):
    1: Smush equal chars (not hardblanks)
    2: Smush '_' with any char in hierarchy below
    4: hierarchy: "|", "/\", "[]", "{}", "()", "<>"
       Each class in hier. can be replaced by later class.
    8: [ + ] -> |, { + } -> |, ( + ) -> |
   16: / + \ -> X, > + < -> X (only in that order)
   32: hardblank + hardblank -> hardblank

****************************************************************************/

char smushem(lch,rch)
char lch,rch;
{
  if (lch==' ') return rch;
  if (rch==' ') return lch;

  if (previouscharwidth<2 || currcharwidth<2) return '\0';
    /* Disallows overlapping if the previous character */
    /* or the current character has a width of 1 or zero. */

  if ((smushmode & SM_SMUSH) == 0) return '\0';  /* kerning */

  if ((smushmode & 63) == 0) {
    /* This is smushing by universal overlapping. */
    if (lch==' ') return rch;