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 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152 16153 16154 16155 16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199 16200 16201 16202 16203 16204 16205 16206 16207 16208 16209 16210 16211 16212 16213 16214 16215 16216 16217 16218 16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229 16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260 16261 16262 16263 16264 16265 16266 16267 16268 16269 16270 16271 16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356 16357 16358 16359 16360 16361 16362 16363 16364 16365 16366 16367 16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410 16411 16412 16413 16414 16415 16416 16417 16418 16419 16420 16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439 16440 16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472 16473 16474 16475 16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493 16494 16495 16496 16497 16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512 16513 16514 16515 16516 16517 16518 16519 16520 16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547 16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563 16564 16565 16566 16567 16568 16569 16570 16571 16572 16573 16574 16575 16576 16577 16578 16579 16580 16581 16582 16583 16584 16585 16586 16587 16588 16589 16590 16591 16592 16593 16594 16595 16596 16597 16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608 16609 16610 16611 16612 16613 16614 16615 16616 16617 16618 16619 16620 16621 16622 16623 16624 16625 16626 16627 16628 16629 16630 16631 16632 16633 16634 16635 16636 16637 16638 16639 16640 16641 16642 16643 16644 16645 16646 16647 16648 16649 16650 16651 16652 16653 16654 16655 16656 16657 16658 16659 16660 16661 16662 16663 16664 16665 16666 16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692 16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730 16731 16732 16733 16734 16735 16736 16737 16738 16739 16740 16741 16742 16743 16744 16745 16746 16747 16748 16749 16750 16751 16752 16753 16754 16755 16756 16757 16758 16759 16760 16761 16762 16763 16764 16765 16766 16767 16768 16769 16770 16771 16772 16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790 16791 16792 16793 16794 16795 16796 16797 16798 16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811 16812 16813 16814 16815 16816 16817 16818 16819 16820 16821 16822 16823 16824 16825 16826 16827 16828 16829 16830 16831 16832 16833 16834 16835 16836 16837 16838 16839 16840 16841 16842 16843 16844 16845 16846 16847 16848 16849 16850 16851 16852 16853 16854 16855 16856 16857 16858 16859 16860 16861 16862 16863 16864 16865 16866 16867 16868 16869 16870 16871 16872 16873 16874 16875 16876 16877 16878 16879 16880 16881 16882 16883 16884 16885 16886 16887 16888 16889 16890 16891 16892 16893 16894 16895 16896 16897 16898 16899 16900 16901 16902 16903 16904 16905 16906 16907 16908 16909 16910 16911 16912 16913 16914 16915 16916 16917 16918 16919 16920 16921 16922 16923 16924 16925 16926 16927 16928 16929 16930 16931 16932 16933 16934 16935 16936 16937 16938 16939 16940 16941 16942 16943 16944 16945 16946 16947 16948 16949 16950 16951 16952 16953 16954 16955 16956 16957 16958 16959 16960 16961 16962 16963 16964 16965 16966 16967 16968 16969 16970 16971 16972 16973 16974 16975 16976 16977 16978 16979 16980 16981 16982 16983 16984 16985 16986 16987 16988 16989 16990 16991 16992 16993 16994 16995 16996 16997 16998 16999 17000 17001 17002 17003 17004 17005 17006 17007 17008 17009 17010 17011 17012 17013 17014 17015 17016 17017 17018 17019 17020 17021 17022 17023 17024 17025 17026 17027 17028 17029 17030 17031 17032 17033 17034 17035 17036 17037 17038 17039 17040 17041 17042 17043 17044 17045 17046 17047 17048 17049 17050 17051 17052 17053 17054 17055 17056 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073 17074 17075 17076 17077 17078 17079 17080 17081 17082 17083 17084 17085 17086 17087 17088 17089 17090 17091 17092 17093 17094 17095 17096 17097 17098 17099 17100 17101 17102 17103 17104 17105 17106 17107 17108 17109 17110 17111 17112 17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124 17125 17126 17127 17128 17129 17130 17131 17132 17133 17134 17135 17136 17137 17138 17139 17140 17141 17142 17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153 17154 17155 17156 17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175 17176 17177 17178 17179 17180 17181 17182 17183 17184 17185 17186 17187 17188 17189 17190 17191 17192 17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206 17207 17208 17209 17210 17211 17212 17213 17214 17215 17216 17217 17218 17219 17220 17221 17222 17223 17224 17225 17226 17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238 17239 17240 17241 17242 17243 17244 17245 17246 17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363 17364 17365 17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381 17382 17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395 17396 17397 17398 17399 17400 17401 17402 17403 17404 17405 17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432 17433 17434 17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451 17452 17453 17454 17455 17456 17457 17458 17459 17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470 17471 17472 17473 17474 17475 17476 17477 17478 17479 17480 17481 17482 17483 17484 17485 17486 17487 17488 17489 17490 17491 17492 17493 17494 17495 17496 17497 17498 17499 17500 17501 17502 17503 17504 17505 17506 17507 17508 17509 17510 17511 17512 17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523 17524 17525 17526 17527 17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539 17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551 17552 17553 17554 17555 17556 17557 17558 17559 17560 17561 17562 17563 17564 17565 17566 17567 17568 17569 17570 17571 17572 17573 17574 17575 17576 17577 17578 17579 17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591 17592 17593 17594 17595 17596 17597 17598 17599 17600 17601 17602 17603 17604 17605 17606 17607 17608 17609 17610 17611 17612 17613 17614 17615 17616 17617 17618 17619 17620 17621 17622 17623 17624 17625 17626 17627 17628 17629 17630 17631 17632 17633 17634 17635 17636 17637 17638 17639 17640 17641 17642 17643 17644 17645 17646 17647 17648 17649 17650 17651 17652 17653 17654 17655 17656 17657 17658 17659 17660 17661 17662 17663 17664 17665 17666 17667 17668 17669 17670 17671 17672 17673 17674 17675 17676 17677 17678 17679 17680 17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696 17697 17698 17699 17700 17701 17702 17703 17704 17705 17706 17707 17708 17709 17710 17711 17712 17713 17714 17715 17716 17717 17718 17719 17720 17721 17722 17723 17724 17725 17726 17727 17728 17729 17730 17731 17732 17733 17734 17735 17736 17737 17738 17739 17740 17741 17742 17743 17744 17745 17746 17747 17748 17749 17750 17751 17752 17753 17754 17755 17756 17757 17758 17759 17760 17761 17762 17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781 17782 17783 17784 17785 17786 17787 17788 17789 17790 17791 17792 17793 17794 17795 17796 17797 17798 17799 17800 17801 17802 17803 17804 17805 17806 17807 17808 17809 17810 17811 17812 17813 17814 17815 17816 17817 17818 17819 17820 17821 17822 17823 17824 17825 17826 17827 17828 17829 17830 17831 17832 17833 17834 17835 17836 17837 17838 17839 17840 17841 17842 17843 17844 17845 17846 17847 17848 17849 17850 17851 17852 17853 17854 17855 17856 17857 17858 17859 17860 17861 17862 17863 17864 17865 17866 17867 17868 17869 17870 17871 17872 17873 17874 17875 17876 17877 17878 17879 17880 17881 17882 17883 17884 17885 17886 17887 17888 17889 17890 17891 17892 17893 17894 17895 17896 17897 17898 17899 17900 17901 17902 17903 17904 17905 17906 17907 17908 17909
  
     | 
    
      #!/bin/sh
# the next line restarts using the correct interpreter \
exec tclsh "$0" "$0" "$@"
#
# xml2rfc.tcl - convert technical memos written using XML to TXT/HTML/NROFF
#
# (c) 1998-01 Invisible Worlds, Inc.
#
global prog prog_version prog_url prog_ack
set prog "xml2rfc"
set prog_version "v1.35"
set prog_url "http://xml.resource.org/"
set prog_ack \
"This document was produced
using $prog $prog_version (of %PROGURL%)
from a source in RFC-2629 XML format."
# "encoding system" is already set at this point and we want that
# because we print warnings and errors to the terminal.
# Now we want the C collation, month names, etc.
foreach v {LC_ALL LC_ADDRESS LC_COLLATE LC_CTYPE LC_IDENTIFICATION
           LC_MESSAGES LC_MEASUREMENT LC_MONETARY LC_NAME LC_NUMERIC
           LC_PAPER LC_TELEPHONE LC_TIME LANG LANGUAGE LINGUAS} {
    set env($v) C
}
#   {{{1 TclXML 1.1.1 (modified)
# earlier versions used to "package require xml 1.8", but because newer tcl
# installations have an incompatibly-versioned sgml package, this caused
# nothing but problems. hence, we just include TclXML-1.1.1 wholesale toward
# the end of the file...
#       {{{2 sgml.tcl
# sgml.tcl --
#
#       This file provides generic parsing services for SGML-based
#       languages, namely HTML and XML.
#
#       NB.  It is a misnomer.  There is no support for parsing
#       arbitrary SGML as such.
#
# Copyright (c) 1998,1999 Zveno Pty Ltd
# http://www.zveno.com/
#
# Zveno makes this software available free of charge for any purpose.
# Copies may be made of this software but all of this notice must be included
# on any copy.
#
# The software was developed for research purposes only and Zveno does not
# warrant that it is error free or fit for any purpose.  Zveno disclaims any
# liability for all claims, expenses, losses, damages and costs any user may
# incur as a result of using, copying or modifying this software.
#
# Copyright (c) 1997 ANU and CSIRO on behalf of the
# participants in the CRC for Advanced Computational Systems ('ACSys').
#
# ACSys makes this software and all associated data and documentation
# ('Software') available free of charge for any purpose.  You may make copies
# of the Software but you must include all of this notice on any copy.
#
# The Software was developed for research purposes and ACSys does not warrant
# that it is error free or fit for any purpose.  ACSys disclaims any
# liability for all claims, expenses, losses, damages and costs any user may
# incur as a result of using, copying or modifying the Software.
#
# $Id$
package provide sgml 1.6
namespace eval sgml {
    namespace export tokenise parseEvent
    namespace export parseDTD
    # Convenience routine
    proc cl x {
        return "\[$x\]"
    }
    # Define various regular expressions
    # white space
    variable Wsp " \t\r\n"
    variable noWsp [cl ^$Wsp]
    # Various XML names
    variable nmtoken [cl -a-zA-Z0-9._]+
    variable name [cl a-zA-Z_][cl -a-zA-Z0-9._]*
    # Other
    variable ParseEventNum
    if {![info exists ParseEventNum]} {
        set ParseEventNum 0
    }
    variable ParseDTDnum
    if {![info exists ParseDTDNum]} {
        set ParseDTDNum 0
    }
    # table of predefined entities for XML
    variable EntityPredef
    array set EntityPredef {
        lt <   gt >   amp &   quot \"   apos '
    }
}
# sgml::tokenise --
#
#       Transform the given HTML/XML text into a Tcl list.
#
# Arguments:
#       sgml            text to tokenize
#       elemExpr        RE to recognise tags
#       elemSub         transform for matched tags
#       args            options
#
# Valid Options:
#       -final          boolean         True if no more data is to be supplied
#       -statevariable  varName         Name of a variable used to store info
#
# Results:
#       Returns a Tcl list representing the document.
proc sgml::tokenise {sgml elemExpr elemSub args} {
    array set options {-final 1}
    catch {array set options $args}
    set options(-final) [Boolean $options(-final)]
    # If the data is not final then there must be a variable to store
    # unused data.
    if {!$options(-final) && ![info exists options(-statevariable)]} {
        return -code error {option "-statevariable" required if not final}
    }
    # Pre-process stage
    #
    # Extract the internal DTD subset, if any
    catch {upvar #0 $options(-internaldtdvariable) dtd}
    set intdtdref "\\&xml:intdtd;"
    while {[regexp {<!DOCTYPE[^[<]+\[([^]]+)\]} $sgml discard dtd2]} {
        append dtd $dtd2
        set text ""
        append text [string repeat "\n" [num_eols $dtd2]]
        regsub {(<!DOCTYPE[^[<]+)(\[[^]]+\])} $sgml "\\1$text$intdtdref" sgml
        set intdtdref ""
    }
    # Protect Tcl special characters
    regsub -all {([{}\\])} $sgml {\\\1} sgml
    # Do the translation
    if {[info exists options(-statevariable)]} {
        upvar #0 $opts(-statevariable) unused
        if {[info exists unused]} {
            regsub -all $elemExpr $unused$sgml $elemSub sgml
            unset unused
        } else {
            regsub -all $elemExpr $sgml $elemSub sgml
        }
        set sgml "{} {} {} {} \{$sgml\}"
        # Performance note (Tcl 8.0):
        #       Use of lindex, lreplace will cause parsing to list object
        if {[regexp {^([^<]*)(<[^>]*$)} [lindex $sgml end] x text unused]} {
            set sgml [lreplace $sgml end end $text]
        }
    } else {
        # Performance note (Tcl 8.0):
        #       In this case, no conversion to list object is performed
        regsub -all $elemExpr $sgml $elemSub sgml
        set sgml "{} {} {} {} \{$sgml\}"
    }
    return $sgml
}
# sgml::parseEvent --
#
#       Produces an event stream for a XML/HTML document,
#       given the Tcl list format returned by tokenise.
#
#       This procedure checks that the document is well-formed,
#       and throws an error if the document is found to be not
#       well formed.  Warnings are passed via the -warningcommand script.
#
#       The procedure only check for well-formedness,
#       no DTD is required.  However, facilities are provided for entity expansion.
#
# Arguments:
#       sgml            Instance data, as a Tcl list.
#       args            option/value pairs
#
# Valid Options:
#       -final                  Indicates end of document data
#       -elementstartcommand    Called when an element starts
#       -elementendcommand      Called when an element ends
#       -characterdatacommand   Called when character data occurs
#       -entityreferencecommand Called when an entity reference occurs
#       -processinginstructioncommand   Called when a PI occurs
#       -externalentityrefcommand       Called for an external entity reference
#
#       (Not compatible with expat)
#       -xmldeclcommand         Called when the XML declaration occurs
#       -doctypecommand         Called when the document type declaration occurs
#       -commentcommand         Called when a comment occurs
#
#       -errorcommand           Script to evaluate for a fatal error
#       -warningcommand         Script to evaluate for a reportable warning
#       -statevariable          global state variable
#       -normalize              whether to normalize names
#       -reportempty            whether to include an indication of empty elements
#
# Results:
#       The various callback scripts are invoked.
#       Returns empty string.
#
# BUGS:
#       If command options are set to empty string then they should not be invoked.
proc sgml::parseEvent {sgml args} {
    variable Wsp
    variable noWsp
    variable nmtoken
    variable name
    variable ParseEventNum
    array set options [list \
        -elementstartcommand            [namespace current]::noop       \
        -elementendcommand              [namespace current]::noop       \
        -characterdatacommand           [namespace current]::noop       \
        -processinginstructioncommand   [namespace current]::noop       \
        -externalentityrefcommand       [namespace current]::noop       \
        -xmldeclcommand                 [namespace current]::noop       \
        -doctypecommand                 [namespace current]::noop       \
        -commentcommand                 [namespace current]::noop       \
        -entityreferencecommand         {}                              \
        -warningcommand                 [namespace current]::noop       \
        -errorcommand                   [namespace current]::Error      \
        -final                          1                               \
        -emptyelement                   [namespace current]::EmptyElement       \
        -parseattributelistcommand      [namespace current]::noop       \
        -normalize                      1                               \
        -internaldtd                    {}                              \
        -reportempty                    0                               \
        -entityvariable                 [namespace current]::EntityPredef       \
    ]
    catch {array set options $args}
    if {![info exists options(-statevariable)]} {
        set options(-statevariable) [namespace current]::ParseEvent[incr ParseEventNum]
    }
    upvar #0 $options(-statevariable) state
    upvar #0 $options(-entityvariable) entities
    if {![info exists state]} {
        # Initialise the state variable
        array set state {
            mode normal
            haveXMLDecl 0
            haveDocElement 0
            context {}
            stack {}
            line 0
            lineo 0
            linet 0
        }
    }
    foreach {tag close empty param text} $sgml {
        # Keep track of lines (open, text, current/next) in the input
        set ::xdv::lineno $state(line)
        set state(lineo) $state(line)
        incr state(line) [regsub -all \n $param {} discard]
        set state(linet) $state(line)
        incr state(line) [regsub -all \n $text {} discard]
        # If the current mode is cdata or comment then we must undo what the
        # regsub has done to reconstitute the data
        switch $state(mode) {
            comment {
                # This had "[string length $param] && " as a guard -
                # can't remember why :-(
                if {[regexp ([cl ^-]*)--\$ $tag discard comm1]} {
                    # end of comment (in tag)
                    set tag {}
                    set close {}
                    set empty {}
                    set state(mode) normal
                    uplevel #0 $options(-commentcommand) [list $state(commentdata)<$comm1]
                    unset state(commentdata)
                } elseif {[regexp ([cl ^-]*)--\$ $param discard comm1]} {
                    # end of comment (in attributes)
                    uplevel #0 $options(-commentcommand) [list $state(commentdata)<$close$tag$empty>$comm1]
                    unset state(commentdata)
                    set tag {}
                    set param {}
                    set close {}
                    set empty {}
                    set state(mode) normal
                } elseif {[regexp ([cl ^-]*)-->(.*) $text discard comm1 text]} {
                    # end of comment (in text)
                    uplevel #0 $options(-commentcommand) [list $state(commentdata)<$close$tag$param$empty>$comm1]
                    unset state(commentdata)
                    set tag {}
                    set param {}
                    set close {}
                    set empty {}
                    set state(mode) normal
                } else {
                    # comment continues
                    append state(commentdata) <$close$tag$param$empty>$text
                    continue
                }
            }
            cdata {
                if {[string length $param] && [regexp ([cl ^\]]*)\]\][cl $Wsp]*\$ $tag discard cdata1]} {
                    # end of CDATA (in tag)
                    uplevel #0 $options(-characterdatacommand) [list $state(cdata)<$close$cdata1$text]
                    set text {}
                    set tag {}
                    unset state(cdata)
                    set state(mode) normal
                } elseif {[regexp ([cl ^\]]*)\]\][cl $Wsp]*\$ $param discard cdata1]} {
                    # end of CDATA (in attributes)
                    uplevel #0 $options(-characterdatacommand) [list $state(cdata)<$close$tag$cdata1$text]
                    set text {}
                    set tag {}
                    set param {}
                    unset state(cdata)
                    set state(mode) normal
                } elseif {[regexp ([cl ^\]]*)\]\][cl $Wsp]*>(.*) $text discard cdata1 text]} {
                    # end of CDATA (in text)
                    uplevel #0 $options(-characterdatacommand) [list $state(cdata)<$close$tag$param$empty>$cdata1$text]
                    set text {}
                    set tag {}
                    set param {}
                    set close {}
                    set empty {}
                    unset state(cdata)
                    set state(mode) normal
                } else {
                    # CDATA continues
                    append state(cdata) <$close$tag$param$empty>$text
                    continue
                }
            }
        }
        # default: normal mode
        # Bug: if the attribute list has a right angle bracket then the empty
        # element marker will not be seen
        set isEmpty [uplevel #0 $options(-emptyelement) [list $tag $param $empty]]
        if {[llength $isEmpty]} {
            foreach {empty tag param} $isEmpty break
        }
        switch -glob -- [string length $tag],[regexp {^\?|!.*} $tag],$close,$empty {
            0,0,, {
                # Ignore empty tag - dealt with non-normal mode above
            }
            *,0,, {
                # Start tag for an element.
                # Check for a right angle bracket in an attribute value
                # This manifests itself by terminating the value before
                # the delimiter is seen, and the delimiter appearing
                # in the text
                # BUG: If two or more attribute values have right angle
                # brackets then this will fail on the second one.
                if {[regexp [format {=[%s]*"[^"]*$} $Wsp] $param] && \
                        [regexp {([^"]*"[^>]*)>(.*)} $text discard attrListRemainder text]} {
                    append param >$attrListRemainder
                } elseif {[regexp [format {=[%s]*'[^']*$} $Wsp] $param] && \
                        [regexp {([^']*'[^>]*)>(.*)} $text discard attrListRemainder text]} {
                    append param >$attrListRemainder
                }
                # Check if the internal DTD entity is in an attribute
                # value
                regsub -all &xml:intdtd\; $param \[$options(-internaldtd)\] param
                ParseEvent:ElementOpen $tag $param options
                set state(haveDocElement) 1
            }
            *,0,/, {
                # End tag for an element.
                ParseEvent:ElementClose $tag options
            }
            *,0,,/ {
                # Empty element
                ParseEvent:ElementOpen $tag $param options -empty 1
                ParseEvent:ElementClose $tag options -empty 1
            }
            *,1,* {
                # Processing instructions or XML declaration
                switch -glob -- $tag {
                    {\?xml} {
                        # XML Declaration
                        if {$state(haveXMLDecl)} {
                            uplevel #0 $options(-errorcommand) "unexpected characters \"<$tag\" around line $state(lineo)"
                        } elseif {![regexp {\?$} $param]} {
                            uplevel #0 $options(-errorcommand) "XML Declaration missing characters \"?>\" around line $state(linet)"
                        } else {
                            # Get the version number
                            if {[regexp {[      ]*version="(-+|[a-zA-Z0-9_.:]+)"[       ]*} $param discard version] || [regexp {[       ]*version='(-+|[a-zA-Z0-9_.:]+)'[       ]*} $param discard version]} {
                                if {[string compare $version "1.0"]} {
                                    # Should we support future versions?
                                    # At least 1.X?
                                    uplevel #0 $options(-errorcommand) "document XML version \"$version\" is incompatible with XML version 1.0"
                                }
                            } else {
                                uplevel #0 $options(-errorcommand) "XML Declaration missing version information around line $state(lineo)"
                            }
                            # Get the encoding declaration
                            set encoding {}
                            regexp {[   ]*encoding="([A-Za-z]([A-Za-z0-9._]|-)*)"[      ]*} $param discard encoding
                            regexp {[   ]*encoding='([A-Za-z]([A-Za-z0-9._]|-)*)'[      ]*} $param discard encoding
                            # Get the standalone declaration
                            set standalone {}
                            regexp {[   ]*standalone="(yes|no)"[        ]*} $param discard standalone
                            regexp {[   ]*standalone='(yes|no)'[        ]*} $param discard standalone
                            # Invoke the callback
                            uplevel #0 $options(-xmldeclcommand) [list $version $encoding $standalone]
                        }
                    }
                    {\?*} {
                        # Processing instruction
                        if {   ![regsub {\?$} $param {} param]
                            && !(   ![string compare $param ""]
                                 && [regsub {\?$} $tag {} tag]
                                 && [string compare $tag ""])} {
                            uplevel #0 $options(-errorcommand) "PI: expected '?' character around line $state(linet)"
                        } else {
                            uplevel #0 $options(-processinginstructioncommand) [list [string range $tag 1 end] $param]
                        }
                    }
                    !DOCTYPE {
                        # External entity reference
                        # This should move into xml.tcl
                        # Parse the params supplied.  Looking for Name, ExternalID and MarkupDecl
                        regexp ^[cl $Wsp]*($name)(.*) $param x state(doc_name) param
                        set state(doc_name) [Normalize $state(doc_name) $options(-normalize)]
                        set externalID {}
                        set pubidlit {}
                        set systemlit {}
                        set externalID {}
                        if {[regexp -nocase ^[cl $Wsp]*(SYSTEM|PUBLIC)(.*) $param x id param]} {
                            switch [string toupper $id] {
                                SYSTEM {
                                    if {[regexp ^[cl $Wsp]+"([cl ^"]*)"(.*) $param x systemlit param] || [regexp ^[cl $Wsp]+'([cl ^']*)'(.*) $param x systemlit param]} {
                                        set externalID [list SYSTEM $systemlit] ;# "
                                    } else {
                                        uplevel #0 $options(-errorcommand) {{syntax error: SYSTEM identifier not followed by literal}}
                                    }
                                }
                                PUBLIC {
                                    if {[regexp ^[cl $Wsp]+"([cl ^"]*)"(.*) $param x pubidlit param] || [regexp ^[cl $Wsp]+'([cl ^']*)'(.*) $param x pubidlit param]} {
                                        if {[regexp ^[cl $Wsp]+"([cl ^"]*)"(.*) $param x systemlit param] || [regexp ^[cl $Wsp]+'([cl ^']*)'(.*) $param x systemlit param]} {
                                            set externalID [list PUBLIC $pubidlit $systemlit]
                                        } else {
                                            uplevel #0 $options(-errorcommand) "syntax error: PUBLIC identifier not followed by system literal around line $state(lineo)"
                                        }
                                    } else {
                                        uplevel #0 $options(-errorcommand) "syntax error: PUBLIC identifier not followed by literal around line $state(lineo)"
                                    }
                                }
                            }
                            if {[regexp -nocase ^[cl $Wsp]+NDATA[cl $Wsp]+($name)(.*) $param x notation param]} {
                                lappend externalID $notation
                            }
                        }
                        uplevel #0 $options(-doctypecommand) $state(doc_name) [list $pubidlit $systemlit $options(-internaldtd)]
                    }
                    !--* {
                        # Start of a comment
                        # See if it ends in the same tag, otherwise change the
                        # parsing mode
                        regexp {!--(.*)} $tag discard comm1
                        if {[regexp ([cl ^-]*)--[cl $Wsp]*\$ $comm1 discard comm1_1]} {
                            # processed comment (end in tag)
                            uplevel #0 $options(-commentcommand) [list $comm1_1]
                        } elseif {[regexp ([cl ^-]*)--[cl $Wsp]*\$ $param discard comm2]} {
                            # processed comment (end in attributes)
                            uplevel #0 $options(-commentcommand) [list $comm1$comm2]
                        } elseif {[regexp ([cl ^-]*)-->(.*) $text discard comm2 text]} {
                            # processed comment (end in text)
                            uplevel #0 $options(-commentcommand) [list $comm1$param>$comm2]
                        } else {
                            # start of comment
                            set state(mode) comment
                            set state(commentdata) "$comm1$param>$text"
                            continue
                        }
                    }
                    {!\[CDATA\[*} {
                        regexp {!\[CDATA\[(.*)} $tag discard cdata1
                        if {[regexp {(.*)]]$} $param discard cdata2]} {
                            # processed CDATA (end in attribute)
                            uplevel #0 $options(-characterdatacommand) [list $cdata1$cdata2$text]
                            set text {}
                        } elseif {[regexp {(.*)]]>(.*)} $text discard cdata2 text]} {
                            # processed CDATA (end in text)
                            uplevel #0 $options(-characterdatacommand) [list $cdata1$param$empty>$cdata2$text]
                            set text {}
                        } else {
                            # start CDATA
                            set state(cdata) "$cdata1$param>$text"
                            set state(mode) cdata
                            continue
                        }
                    }
                    !ELEMENT {
                        # Internal DTD declaration
                    }
                    !ATTLIST {
                    }
                    !ENTITY {
                    }
                    !NOTATION {
                    }
                    !* {
                        uplevel #0 $options(-processinginstructioncommand) [list $tag $param]
                    }
                    default {
                        uplevel #0 $options(-errorcommand) [list "unknown processing instruction \"<$tag>\" around line $state(lineo)"]
                    }
                }
            }
            *,1,* -
            *,0,/,/ {
                # Syntax error
                uplevel #0 $options(-errorcommand) [list [list syntax error: closed/empty tag: tag $tag param $param empty $empty close $close around line $state(lineo)]]
            }
        }
        # Process character data
        if {$state(haveDocElement) && [llength $state(stack)]} {
            # Check if the internal DTD entity is in the text
            regsub -all &xml:intdtd\; $text \[$options(-internaldtd)\] text
            # Look for entity references
            if {([array size entities] || [string length $options(-entityreferencecommand)]) && \
                [regexp {&[^;]+;} $text]} {
                # protect Tcl specials
                regsub -all {([][$\\])} $text {\\\1} text
                # Mark entity references
                regsub -all {&([^;]+);} $text [format {%s; %s {\1} ; %s %s} \}\} [namespace code [list Entity options $options(-entityreferencecommand) $options(-characterdatacommand) $options(-entityvariable)]] [list uplevel #0 $options(-characterdatacommand)] \{\{] text
                set text "uplevel #0 $options(-characterdatacommand) {{$text}}"
                eval $text
            } else {
                # Restore protected special characters
                regsub -all {\\([{}\\])} $text {\1} text
#                uplevel #0 $options(-characterdatacommand) [list $text]
                sgml::callback $state(lineo) \
                      $options(-characterdatacommand) [list $text]
            }
        } elseif {[string length [string trim $text]]} {
            uplevel #0 $options(-errorcommand) [list "unexpected text \"$text\" in document prolog around line $state(linet)"]
        }
    }
    # If this is the end of the document, close all open containers
    if {$options(-final) && [llength $state(stack)]} {
        eval $options(-errorcommand) [list [list element [lindex $state(stack) end] remains unclosed around line $state(line)]]
    }
    set ::xdv::lineno -1
    return {}
}
proc sgml::callback {lineno args} {
    global errorCode errorInfo
    set ::xdv::lineno $lineno
    if {[set code [catch { eval uplevel #0 $args } result]]} {
        append result " around line $lineno"
    }
    return -code $code -errorinfo $errorInfo -errorcode $errorCode $result
}
# sgml::ParseEvent:ElementOpen --
#
#       Start of an element.
#
# Arguments:
#       tag     Element name
#       attr    Attribute list
#       opts    Option variable in caller
#       args    further configuration options
#
# Options:
#       -empty boolean
#               indicates whether the element was an empty element
#
# Results:
#       Modify state and invoke callback
proc sgml::ParseEvent:ElementOpen {tag attr opts args} {
    upvar $opts options
    upvar #0 $options(-statevariable) state
    array set cfg {-empty 0}
    array set cfg $args
    if {$options(-normalize)} {
        set tag [string toupper $tag]
    }
    # Update state
    lappend state(stack) $tag
    # Parse attribute list into a key-value representation
    if {[string compare $options(-parseattributelistcommand) {}]} {
        if {[catch {uplevel #0 $options(-parseattributelistcommand) [list $attr]} attr]} {
            uplevel #0 $options(-errorcommand) [list $attr around line $state(lineo)]
            set attr {}
        }
    }
    set empty {}
    if {$cfg(-empty) && $options(-reportempty)} {
        set empty {-empty 1}
    }
    # Invoke callback
#    uplevel #0 $options(-elementstartcommand) [list $tag $attr] $empty
    sgml::callback $state(lineo) \
          $options(-elementstartcommand) [list $tag $attr] $empty
    return {}
}
# sgml::ParseEvent:ElementClose --
#
#       End of an element.
#
# Arguments:
#       tag     Element name
#       opts    Option variable in caller
#       args    further configuration options
#
# Options:
#       -empty boolean
#               indicates whether the element as an empty element
#
# Results:
#       Modify state and invoke callback
proc sgml::ParseEvent:ElementClose {tag opts args} {
    upvar $opts options
    upvar #0 $options(-statevariable) state
    array set cfg {-empty 0}
    array set cfg $args
    # WF check
    if {[string compare $tag [lindex $state(stack) end]]} {
        uplevel #0 $options(-errorcommand) [list "end tag \"$tag\" does not match open element \"[lindex $state(stack) end]\" around line $state(lineo)"]
        return
    }
    # Update state
    set state(stack) [lreplace $state(stack) end end]
    set empty {}
    if {$cfg(-empty) && $options(-reportempty)} {
        set empty {-empty 1}
    }
    # Invoke callback
#    uplevel #0 $options(-elementendcommand) [list $tag] $empty
    sgml::callback $state(lineo) \
          $options(-elementendcommand) [list $tag] $empty
    return {}
}
# sgml::Normalize --
#
#       Perform name normalization if required
#
# Arguments:
#       name    name to normalize
#       req     normalization required
#
# Results:
#       Name returned as upper-case if normalization required
proc sgml::Normalize {name req} {
    if {$req} {
        return [string toupper $name]
    } else {
        return $name
    }
}
# sgml::Entity --
#
#       Resolve XML entity references (syntax: &xxx;).
#
# Arguments:
#       opts            options array variable in caller
#       entityrefcmd    application callback for entity references
#       pcdatacmd       application callback for character data
#       entities        name of array containing entity definitions.
#       ref             entity reference (the "xxx" bit)
#
# Results:
#       Returns substitution text for given entity.
proc sgml::Entity {opts entityrefcmd pcdatacmd entities ref} {
    upvar 2 $opts options
    upvar #0 $options(-statevariable) state
    if {![string length $entities]} {
        set entities [namespace current EntityPredef]
    }
    switch -glob -- $ref {
        %* {
            # Parameter entity - not recognised outside of a DTD
        }
        #x* {
            # Character entity - hex
            if {[catch {format %c [scan [string range $ref 2 end] %x tmp; set tmp]} char]} {
                return -code error "malformed character entity \"$ref\""
            }
            uplevel #0 $pcdatacmd [list $char]
            return {}
        }
        #* {
            # Character entity - decimal
            if {[catch {format %c [scan [string range $ref 1 end] %d tmp; set tmp]} char]} {
                return -code error "malformed character entity \"$ref\""
            }
            uplevel #0 $pcdatacmd [list $char]
            return {}
        }
        default {
            # General entity
            upvar #0 $entities map
            if {[info exists map($ref)]} {
                if {![regexp {<|&} $map($ref)]} {
                    # Simple text replacement - optimise
                    uplevel #0 $pcdatacmd [list $map($ref)]
                    return {}
                }
                # Otherwise an additional round of parsing is required.
                # This only applies to XML, since HTML doesn't have general entities
                # Must parse the replacement text for start & end tags, etc
                # This text must be self-contained: balanced closing tags, and so on
                set tokenised [tokenise $map($ref) $::xml::tokExpr $::xml::substExpr]
                set final $options(-final)
                unset options(-final)
                eval parseEvent [list $tokenised] [array get options] -final 0
                set options(-final) $final
                return {}
            } elseif {[string length $entityrefcmd]} {
                uplevel #0 $entityrefcmd [list $ref]
                return {}
            }
        }
    }
    # If all else fails leave the entity reference untouched
    uplevel #0 $pcdatacmd [list &$ref\;]
    return {}
}
####################################
#
# DTD parser for SGML (XML).
#
# This DTD actually only handles XML DTDs.  Other language's
# DTD's, such as HTML, must be written in terms of a XML DTD.
#
# A DTD is represented as a three element Tcl list.
# The first element contains the content models for elements,
# the second contains the attribute lists for elements and
# the last element contains the entities for the document.
#
####################################
# sgml::parseDTD --
#
#       Entry point to the SGML DTD parser.
#
# Arguments:
#       dtd     data defining the DTD to be parsed
#       args    configuration options
#
# Results:
#       Returns a three element list, first element is the content model
#       for each element, second element are the attribute lists of the
#       elements and the third element is the entity map.
proc sgml::parseDTD {dtd args} {
    variable Wsp
    variable ParseDTDnum
    array set opts [list \
        -errorcommand           [namespace current]::noop \
        state                   [namespace current]::parseDTD[incr ParseDTDnum]
    ]
    array set opts $args
    set exp <!([cl ^$Wsp>]+)[cl $Wsp]*([cl ^$Wsp]+)[cl $Wsp]*([cl ^>]*)>
    set sub {{\1} {\2} {\3} }
    regsub -all $exp $dtd $sub dtd
    foreach {decl id value} $dtd {
        catch {DTD:[string toupper $decl] $id $value} err
    }
    return [list [array get contentmodel] [array get attributes] [array get entities]]
}
# Procedures for handling the various declarative elements in a DTD.
# New elements may be added by creating a procedure of the form
# parse:DTD:_element_
# For each of these procedures, the various regular expressions they use
# are created outside of the proc to avoid overhead at runtime
# sgml::DTD:ELEMENT --
#
#       <!ELEMENT ...> defines an element.
#
#       The content model for the element is stored in the contentmodel array,
#       indexed by the element name.  The content model is parsed into the
#       following list form:
#
#               {}      Content model is EMPTY.
#                       Indicated by an empty list.
#               *       Content model is ANY.
#                       Indicated by an asterix.
#               {ELEMENT ...}
#                       Content model is element-only.
#               {MIXED {element1 element2 ...}}
#                       Content model is mixed (PCDATA and elements).
#                       The second element of the list contains the
#                       elements that may occur.  #PCDATA is assumed
#                       (ie. the list is normalised).
#
# Arguments:
#       id      identifier for the element.
#       value   other information in the PI
proc sgml::DTD:ELEMENT {id value} {
    dbgputs DTD_parse [list DTD:ELEMENT $id $value]
    variable Wsp
    upvar opts state
    upvar contentmodel cm
    if {[info exists cm($id)]} {
        eval $state(-errorcommand) element [list "element \"$id\" already declared"]
    } else {
        switch -- $value {
            EMPTY {
                set cm($id) {}
            }
            ANY {
                set cm($id) *
            }
            default {
                if {[regexp [format {^\([%s]*#PCDATA[%s]*(\|([^)]+))?[%s]*\)*[%s]*$} $Wsp $Wsp $Wsp $Wsp] discard discard mtoks]} {
                    set cm($id) [list MIXED [split $mtoks |]]
                } else {
                    if {[catch {CModelParse $state(state) $value} result]} {
                        eval $state(-errorcommand) element [list $result]
                    } else {
                        set cm($id) [list ELEMENT $result]
                    }
                }
            }
        }
    }
}
# sgml::CModelParse --
#
#       Parse an element content model (non-mixed).
#       A syntax tree is constructed.
#       A transition table is built next.
#
#       This is going to need alot of work!
#
# Arguments:
#       state   state array variable
#       value   the content model data
#
# Results:
#       A Tcl list representing the content model.
proc sgml::CModelParse {state value} {
    upvar #0 $state var
    # First build syntax tree
    set syntaxTree [CModelMakeSyntaxTree $state $value]
    # Build transition table
    set transitionTable [CModelMakeTransitionTable $state $syntaxTree]
    return [list $syntaxTree $transitionTable]
}
# sgml::CModelMakeSyntaxTree --
#
#       Construct a syntax tree for the regular expression.
#
#       Syntax tree is represented as a Tcl list:
#       rep {:choice|:seq {{rep list1} {rep list2} ...}}
#       where:  rep is repetition character, *, + or ?. {} for no repetition
#               listN is nested expression or Name
#
# Arguments:
#       spec    Element specification
#
# Results:
#       Syntax tree for element spec as nested Tcl list.
#
#       Examples:
#       (memo)
#               {} {:seq {{} memo}}
#       (front, body, back?)
#               {} {:seq {{} front} {{} body} {? back}}
#       (head, (p | list | note)*, div2*)
#               {} {:seq {{} head} {* {:choice {{} p} {{} list} {{} note}} } {* div2}}
#       (p | a | ul)+
#               + {:choice {{} p} {{} a} {{} ul}}
proc sgml::CModelMakeSyntaxTree {state spec} {
    upvar #0 $state var
    variable Wsp
    variable name
    # Translate the spec into a Tcl list.
    # None of the Tcl special characters are allowed in a content model spec.
    if {[regexp {\$|\[|\]|\{|\}} $spec]} {
        return -code error "illegal characters in specification"
    }
    regsub -all [format {(%s)[%s]*(\?|\*|\+)?[%s]*(,|\|)?} $name $Wsp $Wsp] $spec [format {%sCModelSTname %s {\1} {\2} {\3}} \n $state] spec
    regsub -all {\(} $spec "\nCModelSTopenParen $state " spec
    regsub -all [format {\)[%s]*(\?|\*|\+)?[%s]*(,|\|)?} $Wsp $Wsp] $spec [format {%sCModelSTcloseParen %s {\1} {\2}} \n $state] spec
    array set var {stack {} state start}
    eval $spec
    # Peel off the outer seq, its redundant
    return [lindex [lindex $var(stack) 1] 0]
}
# sgml::CModelSTname --
#
#       Processes a name in a content model spec.
#
# Arguments:
#       state   state array variable
#       name    name specified
#       rep     repetition operator
#       cs      choice or sequence delimiter
#
# Results:
#       See CModelSTcp.
proc sgml::CModelSTname {state name rep cs args} {
    if {[llength $args]} {
        return -code error "syntax error in specification: \"$args\""
    }
    CModelSTcp $state $name $rep $cs
}
# sgml::CModelSTcp --
#
#       Process a content particle.
#
# Arguments:
#       state   state array variable
#       name    name specified
#       rep     repetition operator
#       cs      choice or sequence delimiter
#
# Results:
#       The content particle is added to the current group.
proc sgml::CModelSTcp {state cp rep cs} {
    upvar #0 $state var
    switch -glob -- [lindex $var(state) end]=$cs {
        start= {
            set var(state) [lreplace $var(state) end end end]
            # Add (dummy) grouping, either choice or sequence will do
            CModelSTcsSet $state ,
            CModelSTcpAdd $state $cp $rep
        }
        :choice= -
        :seq= {
            set var(state) [lreplace $var(state) end end end]
            CModelSTcpAdd $state $cp $rep
        }
        start=| -
        start=, {
            set var(state) [lreplace $var(state) end end [expr {$cs == "," ? ":seq" : ":choice"}]]
            CModelSTcsSet $state $cs
            CModelSTcpAdd $state $cp $rep
        }
        :choice=| -
        :seq=, {
            CModelSTcpAdd $state $cp $rep
        }
        :choice=, -
        :seq=| {
            return -code error "syntax error in specification: incorrect delimiter after \"$cp\", should be \"[expr {$cs == "," ? "|" : ","}]\""
        }
        end=* {
            return -code error "syntax error in specification: no delimiter before \"$cp\""
        }
        default {
            return -code error "syntax error"
        }
    }
}
# sgml::CModelSTcsSet --
#
#       Start a choice or sequence on the stack.
#
# Arguments:
#       state   state array
#       cs      choice oir sequence
#
# Results:
#       state is modified: end element of state is appended.
proc sgml::CModelSTcsSet {state cs} {
    upvar #0 $state var
    set cs [expr {$cs == "," ? ":seq" : ":choice"}]
    if {[llength $var(stack)]} {
        set var(stack) [lreplace $var(stack) end end $cs]
    } else {
        set var(stack) [list $cs {}]
    }
}
# sgml::CModelSTcpAdd --
#
#       Append a content particle to the top of the stack.
#
# Arguments:
#       state   state array
#       cp      content particle
#       rep     repetition
#
# Results:
#       state is modified: end element of state is appended.
proc sgml::CModelSTcpAdd {state cp rep} {
    upvar #0 $state var
    if {[llength $var(stack)]} {
        set top [lindex $var(stack) end]
        lappend top [list $rep $cp]
        set var(stack) [lreplace $var(stack) end end $top]
    } else {
        set var(stack) [list $rep $cp]
    }
}
# sgml::CModelSTopenParen --
#
#       Processes a '(' in a content model spec.
#
# Arguments:
#       state   state array
#
# Results:
#       Pushes stack in state array.
proc sgml::CModelSTopenParen {state args} {
    upvar #0 $state var
    if {[llength $args]} {
        return -code error "syntax error in specification: \"$args\""
    }
    lappend var(state) start
    lappend var(stack) [list {} {}]
}
# sgml::CModelSTcloseParen --
#
#       Processes a ')' in a content model spec.
#
# Arguments:
#       state   state array
#       rep     repetition
#       cs      choice or sequence delimiter
#
# Results:
#       Stack is popped, and former top of stack is appended to previous element.
proc sgml::CModelSTcloseParen {state rep cs args} {
    upvar #0 $state var
    if {[llength $args]} {
        return -code error "syntax error in specification: \"$args\""
    }
    set cp [lindex $var(stack) end]
    set var(stack) [lreplace $var(stack) end end]
    set var(state) [lreplace $var(state) end end]
    CModelSTcp $state $cp $rep $cs
}
# sgml::CModelMakeTransitionTable --
#
#       Given a content model's syntax tree, constructs
#       the transition table for the regular expression.
#
#       See "Compilers, Principles, Techniques, and Tools",
#       Aho, Sethi and Ullman.  Section 3.9, algorithm 3.5.
#
# Arguments:
#       state   state array variable
#       st      syntax tree
#
# Results:
#       The transition table is returned, as a key/value Tcl list.
proc sgml::CModelMakeTransitionTable {state st} {
    upvar #0 $state var
    # Construct nullable, firstpos and lastpos functions
    array set var {number 0}
    foreach {nullable firstpos lastpos} [       \
        TraverseDepth1st $state $st {
            # Evaluated for leaf nodes
            # Compute nullable(n)
            # Compute firstpos(n)
            # Compute lastpos(n)
            set nullable [nullable leaf $rep $name]
            set firstpos [list {} $var(number)]
            set lastpos [list {} $var(number)]
            set var(pos:$var(number)) $name
        } {
            # Evaluated for nonterminal nodes
            # Compute nullable, firstpos, lastpos
            set firstpos [firstpos $cs $firstpos $nullable]
            set lastpos  [lastpos  $cs $lastpos  $nullable]
            set nullable [nullable nonterm $rep $cs $nullable]
        }       \
    ] break
    set accepting [incr var(number)]
    set var(pos:$accepting) #
    # var(pos:N) maps from position to symbol.
    # Construct reverse map for convenience.
    # NB. A symbol may appear in more than one position.
    # var is about to be reset, so use different arrays.
    foreach {pos symbol} [array get var pos:*] {
        set pos [lindex [split $pos :] 1]
        set pos2symbol($pos) $symbol
        lappend sym2pos($symbol) $pos
    }
    # Construct the followpos functions
    catch {unset var}
    followpos $state $st $firstpos $lastpos
    # Construct transition table
    # Dstates is [union $marked $unmarked]
    set unmarked [list [lindex $firstpos 1]]
    while {[llength $unmarked]} {
        set T [lindex $unmarked 0]
        lappend marked $T
        set unmarked [lrange $unmarked 1 end]
        # Find which input symbols occur in T
        set symbols {}
        foreach pos $T {
            if {$pos != $accepting && [lsearch $symbols $pos2symbol($pos)] < 0} {
                lappend symbols $pos2symbol($pos)
            }
        }
        foreach a $symbols {
            set U {}
            foreach pos $sym2pos($a) {
                if {[lsearch $T $pos] >= 0} {
                    # add followpos($pos)
                    if {$var($pos) == {}} {
                        lappend U $accepting
                    } else {
                        eval lappend U $var($pos)
                    }
                }
            }
            set U [makeSet $U]
            if {[llength $U] && [lsearch $marked $U] < 0 && [lsearch $unmarked $U] < 0} {
                lappend unmarked $U
            }
            set Dtran($T,$a) $U
        }
    }
    return [list [array get Dtran] [array get sym2pos] $accepting]
}
# sgml::followpos --
#
#       Compute the followpos function, using the already computed
#       firstpos and lastpos.
#
# Arguments:
#       state           array variable to store followpos functions
#       st              syntax tree
#       firstpos        firstpos functions for the syntax tree
#       lastpos         lastpos functions
#
# Results:
#       followpos functions for each leaf node, in name/value format
proc sgml::followpos {state st firstpos lastpos} {
    upvar #0 $state var
    switch -- [lindex [lindex $st 1] 0] {
        :seq {
            for {set i 1} {$i < [llength [lindex $st 1]]} {incr i} {
                followpos $state [lindex [lindex $st 1] $i]                     \
                        [lindex [lindex $firstpos 0] [expr $i - 1]]     \
                        [lindex [lindex $lastpos 0] [expr $i - 1]]
                foreach pos [lindex [lindex [lindex $lastpos 0] [expr $i - 1]] 1] {
                    eval lappend var($pos) [lindex [lindex [lindex $firstpos 0] $i] 1]
                    set var($pos) [makeSet $var($pos)]
                }
            }
        }
        :choice {
            for {set i 1} {$i < [llength [lindex $st 1]]} {incr i} {
                followpos $state [lindex [lindex $st 1] $i]                     \
                        [lindex [lindex $firstpos 0] [expr $i - 1]]     \
                        [lindex [lindex $lastpos 0] [expr $i - 1]]
            }
        }
        default {
            # No action at leaf nodes
        }
    }
    switch -- [lindex $st 0] {
        ? {
            # We having nothing to do here ! Doing the same as
            # for * effectively converts this qualifier into the other.
        }
        * {
            foreach pos [lindex $lastpos 1] {
                eval lappend var($pos) [lindex $firstpos 1]
                set var($pos) [makeSet $var($pos)]
            }
        }
    }
}
# sgml::TraverseDepth1st --
#
#       Perform depth-first traversal of a tree.
#       A new tree is constructed, with each node computed by f.
#
# Arguments:
#       state   state array variable
#       t       The tree to traverse, a Tcl list
#       leaf    Evaluated at a leaf node
#       nonTerm Evaluated at a nonterminal node
#
# Results:
#       A new tree is returned.
proc sgml::TraverseDepth1st {state t leaf nonTerm} {
    upvar #0 $state var
    set nullable {}
    set firstpos {}
    set lastpos {}
    switch -- [lindex [lindex $t 1] 0] {
        :seq -
        :choice {
            set rep [lindex $t 0]
            set cs [lindex [lindex $t 1] 0]
            foreach child [lrange [lindex $t 1] 1 end] {
                foreach {childNullable childFirstpos childLastpos} \
                        [TraverseDepth1st $state $child $leaf $nonTerm] break
                lappend nullable $childNullable
                lappend firstpos $childFirstpos
                lappend lastpos  $childLastpos
            }
            eval $nonTerm
        }
        default {
            incr var(number)
            set rep [lindex [lindex $t 0] 0]
            set name [lindex [lindex $t 1] 0]
            eval $leaf
        }
    }
    return [list $nullable $firstpos $lastpos]
}
# sgml::firstpos --
#
#       Computes the firstpos function for a nonterminal node.
#
# Arguments:
#       cs              node type, choice or sequence
#       firstpos        firstpos functions for the subtree
#       nullable        nullable functions for the subtree
#
# Results:
#       firstpos function for this node is returned.
proc sgml::firstpos {cs firstpos nullable} {
    switch -- $cs {
        :seq {
            set result [lindex [lindex $firstpos 0] 1]
            for {set i 0} {$i < [llength $nullable]} {incr i} {
                if {[lindex [lindex $nullable $i] 1]} {
                    eval lappend result [lindex [lindex $firstpos [expr $i + 1]] 1]
                } else {
                    break
                }
            }
        }
        :choice {
            foreach child $firstpos {
                eval lappend result $child
            }
        }
    }
    return [list $firstpos [makeSet $result]]
}
# sgml::lastpos --
#
#       Computes the lastpos function for a nonterminal node.
#       Same as firstpos, only logic is reversed
#
# Arguments:
#       cs              node type, choice or sequence
#       lastpos         lastpos functions for the subtree
#       nullable        nullable functions forthe subtree
#
# Results:
#       lastpos function for this node is returned.
proc sgml::lastpos {cs lastpos nullable} {
    switch -- $cs {
        :seq {
            set result [lindex [lindex $lastpos end] 1]
            for {set i [expr [llength $nullable] - 1]} {$i >= 0} {incr i -1} {
                if {[lindex [lindex $nullable $i] 1]} {
                    eval lappend result [lindex [lindex $lastpos $i] 1]
                } else {
                    break
                }
            }
        }
        :choice {
            foreach child $lastpos {
                eval lappend result $child
            }
        }
    }
    return [list $lastpos [makeSet $result]]
}
# sgml::makeSet --
#
#       Turn a list into a set, ie. remove duplicates.
#
# Arguments:
#       s       a list
#
# Results:
#       A set is returned, which is a list with duplicates removed.
proc sgml::makeSet s {
    foreach r $s {
        if {[llength $r]} {
            set unique($r) {}
        }
    }
    return [array names unique]
}
# sgml::nullable --
#
#       Compute the nullable function for a node.
#
# Arguments:
#       nodeType        leaf or nonterminal
#       rep             repetition applying to this node
#       name            leaf node: symbol for this node, nonterm node: choice or seq node
#       subtree         nonterm node: nullable functions for the subtree
#
# Results:
#       Returns nullable function for this branch of the tree.
proc sgml::nullable {nodeType rep name {subtree {}} } {
    switch -glob -- $rep:$nodeType {
        :leaf -
        +:leaf {
            return [list {} 0]
        }
        \\*:leaf -
        \\?:leaf {
            return [list {} 1]
        }
        \\*:nonterm -
        \\?:nonterm {
            return [list $subtree 1]
        }
        :nonterm -
        +:nonterm {
            switch -- $name {
                :choice {
                    set result 0
                    foreach child $subtree {
                        set result [expr $result || [lindex $child 1]]
                    }
                }
                :seq {
                    set result 1
                    foreach child $subtree {
                        set result [expr $result && [lindex $child 1]]
                    }
                }
            }
            return [list $subtree $result]
        }
    }
}
# These regular expressions are defined here once for better performance
namespace eval sgml {
    variable Wsp
    # Watch out for case-sensitivity
    set attlist_exp [cl $Wsp]*([cl ^$Wsp]+)[cl $Wsp]*([cl ^$Wsp]+)[cl $Wsp]*(#REQUIRED|#IMPLIED)
    set attlist_enum_exp [cl $Wsp]*([cl ^$Wsp]+)[cl $Wsp]*\\(([cl ^)]*)\\)[cl $Wsp]*("([cl ^")])")? ;# "
    set attlist_fixed_exp [cl $Wsp]*([cl ^$Wsp]+)[cl $Wsp]*([cl ^$Wsp]+)[cl $Wsp]*(#FIXED)[cl $Wsp]*([cl ^$Wsp]+)
    set param_entity_exp [cl $Wsp]*([cl ^$Wsp]+)[cl $Wsp]*([cl ^"$Wsp]*)[cl $Wsp]*"([cl ^"]*)"
    set notation_exp [cl $Wsp]*([cl ^$Wsp]+)[cl $Wsp]*(.*)
}
# sgml::DTD:ATTLIST --
#
#       <!ATTLIST ...> defines an attribute list.
#
# Arguments:
#       id      Element an attribute list is being defined for.
#       value   data from the PI.
#
# Results:
#       Attribute list variables are modified.
proc sgml::DTD:ATTLIST {id value} {
    variable attlist_exp
    variable attlist_enum_exp
    variable attlist_fixed_exp
    dbgputs DTD_parse [list DTD:ATTLIST $id $value]
    upvar opts state
    upvar attributes am
    if {[info exists am($id)]} {
        eval $state(-errorcommand) attlist [list "attribute list for element \"$id\" already declared"]
    } else {
        # Parse the attribute list.  If it were regular, could just use foreach,
        # but some attributes may have values.
        regsub -all {([][$\\])} $value {\\\1} value
        regsub -all $attlist_exp $value {[DTDAttribute {\1} {\2} {\3}]} value
        regsub -all $attlist_enum_exp $value {[DTDAttribute {\1} {\2} {\3}]} value
        regsub -all $attlist_fixed_exp $value {[DTDAttribute {\1} {\2} {\3} {\4}]} value
        subst $value
        set am($id) [array get attlist]
    }
}
# sgml::DTDAttribute --
#
#       Parse definition of a single attribute.
#
# Arguments:
#       name    attribute name
#       type    type of this attribute
#       default default value of the attribute
#       value   other information
proc sgml::DTDAttribute {name type default {value {}} } {
    upvar attlist al
    # This needs further work
    set al($name) [list $default $value]
}
# sgml::DTD:ENTITY --
#
#       <!ENTITY ...> PI
#
# Arguments:
#       id      identifier for the entity
#       value   data
#
# Results:
#       Modifies the caller's entities array variable
proc sgml::DTD:ENTITY {id value} {
    variable param_entity_exp
    dbgputs DTD_parse [list DTD:ENTITY $id $value]
    upvar opts state
    upvar entities ents
    if {[string compare % $id]} {
        # Entity declaration
        if {[info exists ents($id)]} {
            eval $state(-errorcommand) entity [list "entity \"$id\" already declared"]
        } else {
            if {![regexp {"([^"]*)"} $value x entvalue] && ![regexp {'([^']*)'} $value x entvalue]} {
                eval $state(-errorcommand) entityvalue [list "entity value \"$value\" not correctly specified"]
            } ;# "
            set ents($id) $entvalue
        }
    } else {
        # Parameter entity declaration
        switch -glob [regexp $param_entity_exp $value x name scheme data],[string compare {} $scheme] {
            0,* {
                eval $state(-errorcommand) entityvalue [list "parameter entity \"$value\" not correctly specified"]
            }
            *,0 {
                # SYSTEM or PUBLIC declaration
            }
            default {
                set ents($id) $data
            }
        }
    }
}
# sgml::DTD:NOTATION --
proc sgml::DTD:NOTATION {id value} {
    variable notation_exp
    upvar opts state
    if {[regexp $notation_exp $value x scheme data] == 2} {
    } else {
        eval $state(-errorcommand) notationvalue [list "notation value \"$value\" incorrectly specified"]
    }
}
### Utility procedures
# sgml::noop --
#
#       A do-nothing proc
#
# Arguments:
#       args    arguments
#
# Results:
#       Nothing.
proc sgml::noop args {
    return 0
}
# sgml::identity --
#
#       Identity function.
#
# Arguments:
#       a       arbitrary argument
#
# Results:
#       $a
proc sgml::identity a {
    return $a
}
# sgml::Error --
#
#       Throw an error
#
# Arguments:
#       args    arguments
#
# Results:
#       Error return condition.
proc sgml::Error args {
    uplevel return -code error [list $args]
}
### Following procedures are based on html_library
# sgml::zapWhite --
#
#       Convert multiple white space into a single space.
#
# Arguments:
#       data    plain text
#
# Results:
#       As above
proc sgml::zapWhite data {
    regsub -all "\[ \t\r\n\]+" $data { } data
    return $data
}
proc sgml::Boolean value {
    regsub {1|true|yes|on} $value 1 value
    regsub {0|false|no|off} $value 0 value
    return $value
}
proc sgml::dbgputs {where text} {
    variable dbg
    catch {if {$dbg} {puts stdout "DBG: $where ($text)"}}
}
#       }}}2 sgml.tcl
#       {{{2 xml.tcl
# xml.tcl --
#
#       This file provides XML services.
#       These services include a XML document instance and DTD parser,
#       as well as support for generating XML.
#
# Copyright (c) 1998,1999 Zveno Pty Ltd
# http://www.zveno.com/
#
# Zveno makes this software and all associated data and documentation
# ('Software') available free of charge for non-commercial purposes only. You
# may make copies of the Software but you must include all of this notice on
# any copy.
#
# The Software was developed for research purposes and Zveno does not warrant
# that it is error free or fit for any purpose.  Zveno disclaims any
# liability for all claims, expenses, losses, damages and costs any user may
# incur as a result of using, copying or modifying the Software.
#
# Copyright (c) 1997 Australian National University (ANU).
#
# ANU makes this software and all associated data and documentation
# ('Software') available free of charge for non-commercial purposes only. You
# may make copies of the Software but you must include all of this notice on
# any copy.
#
# The Software was developed for research purposes and ANU does not warrant
# that it is error free or fit for any purpose.  ANU disclaims any
# liability for all claims, expenses, losses, damages and costs any user may
# incur as a result of using, copying or modifying the Software.
#
# $Id$
package provide xml 1.8
# package require sgml 1.6
namespace eval xml {
    # Procedures for parsing XML documents
    namespace export parser
    # Procedures for parsing XML DTDs
    namespace export DTDparser
    # Counter for creating unique parser objects
    variable ParserCounter 0
    # Convenience routine
    proc cl x {
        return "\[$x\]"
    }
    # Define various regular expressions
    # white space
    variable Wsp " \t\r\n"
    variable noWsp [cl ^$Wsp]
    # Various XML names and tokens
    # BUG: NameChar does not include CombiningChar or Extender
    variable NameChar [cl -a-zA-Z0-9._:]
    variable Name [cl a-zA-Z_:]$NameChar*
    variable Nmtoken $NameChar+
    # Tokenising expressions
    variable tokExpr <(/?)([cl ^$Wsp>]+)([cl $Wsp]*[cl ^>]*)>
    variable substExpr "\}\n{\\2} {\\1} {} {\\3} \{"
    # table of predefined entities
    variable EntityPredef
    array set EntityPredef {
        lt <   gt >   amp &   quot \"   apos '
    }
}
# xml::parser --
#
#       Creates XML parser object.
#
# Arguments:
#       args    Unique name for parser object
#               plus option/value pairs
#
# Recognised Options:
#       -final                  Indicates end of document data
#       -elementstartcommand    Called when an element starts
#       -elementendcommand      Called when an element ends
#       -characterdatacommand   Called when character data occurs
#       -processinginstructioncommand   Called when a PI occurs
#       -externalentityrefcommand       Called for an external entity reference
#
#       (Not compatible with expat)
#       -xmldeclcommand         Called when the XML declaration occurs
#       -doctypecommand         Called when the document type declaration occurs
#
#       -errorcommand           Script to evaluate for a fatal error
#       -warningcommand         Script to evaluate for a reportable warning
#       -statevariable          global state variable
#       -reportempty            whether to provide empty element indication
#
# Results:
#       The state variable is initialised.
proc xml::parser {args} {
    variable ParserCounter
    if {[llength $args] > 0} {
        set name [lindex $args 0]
        set args [lreplace $args 0 0]
    } else {
        set name parser[incr ParserCounter]
    }
    if {[info command [namespace current]::$name] != {}} {
        return -code error "unable to create parser object \"[namespace current]::$name\" command"
    }
    # Initialise state variable and object command
    upvar \#0 [namespace current]::$name parser
    set sgml_ns [namespace parent]::sgml
    array set parser [list name $name                   \
        -final 1                                        \
        -elementstartcommand ${sgml_ns}::noop           \
        -elementendcommand ${sgml_ns}::noop             \
        -characterdatacommand ${sgml_ns}::noop          \
        -processinginstructioncommand ${sgml_ns}::noop  \
        -externalentityrefcommand ${sgml_ns}::noop      \
        -xmldeclcommand ${sgml_ns}::noop                \
        -doctypecommand ${sgml_ns}::noop                \
        -warningcommand ${sgml_ns}::noop                \
        -statevariable [namespace current]::$name       \
        -reportempty 0                                  \
        internaldtd {}                                  \
    ]
    proc [namespace current]::$name {method args} \
        "eval ParseCommand $name \$method \$args"
    eval ParseCommand [list $name] configure $args
    return [namespace current]::$name
}
# xml::ParseCommand --
#
#       Handles parse object command invocations
#
# Valid Methods:
#       cget
#       configure
#       parse
#       reset
#
# Arguments:
#       parser  parser object
#       method  minor command
#       args    other arguments
#
# Results:
#       Depends on method
proc xml::ParseCommand {parser method args} {
    upvar \#0 [namespace current]::$parser state
    switch -- $method {
        cget {
            return $state([lindex $args 0])
        }
        configure {
            foreach {opt value} $args {
                set state($opt) $value
            }
        }
        parse {
            ParseCommand_parse $parser [lindex $args 0]
        }
        reset {
            if {[llength $args]} {
                return -code error "too many arguments"
            }
            ParseCommand_reset $parser
        }
        default {
            return -code error "unknown method \"$method\""
        }
    }
    return {}
}
# xml::ParseCommand_parse --
#
#       Parses document instance data
#
# Arguments:
#       object  parser object
#       xml     data
#
# Results:
#       Callbacks are invoked, if any are defined
proc xml::ParseCommand_parse {object xml} {
    upvar \#0 [namespace current]::$object parser
    variable Wsp
    variable tokExpr
    variable substExpr
    set parent [namespace parent]
    if {![string compare :: $parent]} {
        set parent {}
    }
    set tokenised [lrange \
            [${parent}::sgml::tokenise $xml \
            $tokExpr \
            $substExpr \
            -internaldtdvariable [namespace current]::${object}(internaldtd)] \
        5 end]
    eval ${parent}::sgml::parseEvent \
        [list $tokenised \
            -emptyelement [namespace code ParseEmpty] \
            -parseattributelistcommand [namespace code ParseAttrs]] \
        [array get parser -*command] \
        [array get parser -entityvariable] \
        [array get parser -reportempty] \
        -normalize 0 \
        -internaldtd [list $parser(internaldtd)]
    return {}
}
# xml::ParseEmpty --
#
#       Used by parser to determine whether an element is empty.
#       This should be dead easy in XML.  The only complication is
#       that the RE above can't catch the trailing slash, so we have
#       to dig it out of the tag name or attribute list.
#
#       Tcl 8.1 REs should fix this.
#
# Arguments:
#       tag     element name
#       attr    attribute list (raw)
#       e       End tag delimiter.
#
# Results:
#       "/" if the trailing slash is found.  Optionally, return a list
#       containing new values for the tag name and/or attribute list.
proc xml::ParseEmpty {tag attr e} {
    if {[string match */ [string trimright $tag]] && \
            ![string length $attr]} {
        regsub {/$} $tag {} tag
        return [list / $tag $attr]
    } elseif {[string match */ [string trimright $attr]]} {
        regsub {/$} [string trimright $attr] {} attr
        return [list / $tag $attr]
    } else {
        return {}
    }
}
# xml::ParseAttrs --
#
#       Parse element attributes.
#
# There are two forms for name-value pairs:
#
#       name="value"
#       name='value'
#
# Watch out for the trailing slash on empty elements.
#
# Arguments:
#       attrs   attribute string given in a tag
#
# Results:
#       Returns a Tcl list representing the name-value pairs in the
#       attribute string
proc xml::ParseAttrs attrs {
    variable Wsp
    variable Name
    # First check whether there's any work to do
    if {![string compare {} [string trim $attrs]]} {
        return {}
    }
    # Strip the trailing slash on empty elements
    regsub [format {/[%s]*$} " \t\n\r"] $attrs {} atList
    set mode name
    set result {}
    foreach component [split $atList =] {
        switch $mode {
            name {
                set component [string trim $component]
                if {[regexp $Name $component]} {
                    lappend result $component
                } else {
                    return -code error "invalid attribute name \"$component\""
                }
                set mode value:start
            }
            value:start {
                set component [string trimleft $component]
                set delimiter [string index $component 0]
                set value {}
                switch -- $delimiter {
                    \" -
                    ' {
                        if {[regexp [format {%s([^%s]*)%s(.*)} $delimiter $delimiter $delimiter] $component discard value remainder]} {
                            lappend result $value
                            set remainder [string trim $remainder]
                            if {[string length $remainder]} {
                                if {[regexp $Name $remainder]} {
                                    lappend result $remainder
                                    set mode value:start
                                } else {
                                    return -code error "invalid attribute name \"$remainder\""
                                }
                            } else {
                                set mode end
                            }
                        } else {
                            set value [string range $component 1 end]
                            set mode value:continue
                        }
                    }
                    default {
                        return -code error "invalid value for attribute \"[lindex $result end]\""
                    }
                }
            }
            value:continue {
                if {[regexp [format {([^%s]*)%s(.*)} $delimiter $delimiter] $component discard valuepart remainder]} {
                    append value = $valuepart
                    lappend result $value
                    set remainder [string trim $remainder]
                    if {[string length $remainder]} {
                        if {[regexp $Name $remainder]} {
                            lappend result $remainder
                            set mode value:start
                        } else {
                            return -code error "invalid attribute name \"$remainder\""
                        }
                    } else {
                        set mode end
                    }
                } else {
                    append value = $component
                }
            }
            end {
                return -code error "unexpected data found after end of attribute list"
            }
        }
    }
    switch $mode {
        name -
        end {
            # This is normal
        }
        default {
            return -code error "unexpected end of attribute list"
        }
    }
    return $result
}
proc xml::OLDParseAttrs {attrs} {
    variable Wsp
    variable Name
    # First check whether there's any work to do
    if {![string compare {} [string trim $attrs]]} {
        return {}
    }
    # Strip the trailing slash on empty elements
    regsub [format {/[%s]*$} " \t\n\r"] $attrs {} atList
    # Protect Tcl special characters
    #regsub -all {([[\$\\])} $atList {\\\1} atList
    regsub -all & $atList {\&} atList
    regsub -all {\[} $atList {\&ob;} atList
    regsub -all {\]} $atList {\&cb;} atlist
    # NB. sgml package delivers braces and backslashes quoted
    regsub -all {\\\{} $atList {\&oc;} atList
    regsub -all {\\\}} $atList {\&cc;} atlist
    regsub -all {\$} $atList {\$} atList
    regsub -all {\\\\} $atList {\&bs;} atList
    regsub -all [format {(%s)[%s]*=[%s]*"([^"]*)"} $Name $Wsp $Wsp] \
            $atList {[set parsed(\1) {\2}; set dummy {}] } atList       ;# "
    regsub -all [format {(%s)[%s]*=[%s]*'([^']*)'} $Name $Wsp $Wsp] \
            $atList {[set parsed(\1) {\2}; set dummy {}] } atList
    set leftovers [subst $atList]
    if {[string length [string trim $leftovers]]} {
        return -code error "syntax error in attribute list \"$attrs\""
    }
    return [ParseAttrs:Deprotect [array get parsed]]
}
# xml::ParseAttrs:Deprotect --
#
#       Reverse map Tcl special characters previously protected
#
# Arguments:
#       attrs   attribute list
#
# Results:
#       Characters substituted
proc xml::ParseAttrs:Deprotect attrs {
    regsub -all &\; $attrs \\& attrs
    regsub -all &ob\; $attrs \[ attrs
    regsub -all &cb\; $attrs \] attrs
    regsub -all &oc\; $attrs \{ attrs
    regsub -all &cc\; $attrs \} attrs
    regsub -all &dollar\; $attrs \$ attrs
    regsub -all &bs\; $attrs \\\\ attrs
    return $attrs
}
# xml::ParseCommand_reset --
#
#       Initialize parser data
#
# Arguments:
#       object  parser object
#
# Results:
#       Parser data structure initialised
proc xml::ParseCommand_reset object {
    upvar \#0 [namespace current]::$object parser
    array set parser [list \
            -final 1            \
            internaldtd {}      \
    ]
}
# xml::noop --
#
# A do-nothing proc
proc xml::noop args {}
### Following procedures are based on html_library
# xml::zapWhite --
#
#       Convert multiple white space into a single space.
#
# Arguments:
#       data    plain text
#
# Results:
#       As above
proc xml::zapWhite data {
    regsub -all "\[ \t\r\n\]+" $data { } data
    return $data
}
#
# DTD parser for XML is wholly contained within the sgml.tcl package
#
# xml::parseDTD --
#
#       Entry point to the XML DTD parser.
#
# Arguments:
#       dtd     XML data defining the DTD to be parsed
#       args    configuration options
#
# Results:
#       Returns a three element list, first element is the content model
#       for each element, second element are the attribute lists of the
#       elements and the third element is the entity map.
proc xml::parseDTD {dtd args} {
    return [eval [expr {[namespace parent] == {::} ? {} : [namespace parent]}]::sgml::parseDTD [list $dtd] $args]
}
#       }}}2 xml.tcl
#   }}}1 TclXML 1.1.1 (modified)
#   {{{1 textutil package (unless externally available)
if {[catch { package require textutil }]} {
namespace eval textutil {
    namespace export strRepeat
    variable HaveStrRepeat [ expr {![ catch { string repeat a 1 } ]} ]
    if {0} {
        # Problems with the deactivated code:
        # - Linear in 'num'.
        # - Tests for 'string repeat' in every call!
        #   (Ok, just the variable, still a test every call)
        # - Fails for 'num == 0' because of undefined 'str'.
        proc StrRepeat { char num } {
            variable HaveStrRepeat
            if { $HaveStrRepeat == 0 } then {
                for { set i 0 } { $i < $num } { incr i } {
                    append str $char
                }
            } else {
                set str [ string repeat $char $num ]
            }
            return $str
        }
    }
}
if {$::textutil::HaveStrRepeat} {
    proc ::textutil::strRepeat {char num} {
        return [string repeat $char $num]
    }
} else {
    proc ::textutil::strRepeat {char num} {
        if {$num <= 0} {
            # No replication required
            return ""
        } elseif {$num == 1} {
            # Quick exit for recursion
            return $char
        } elseif {$num == 2} {
            # Another quick exit for recursion
            return $char$char
        } elseif {0 == ($num % 2)} {
            # Halving the problem results in O (log n) complexity.
            set result [strRepeat $char [expr {$num / 2}]]
            return "$result$result"
        } else {
            # Uneven length, reduce problem by one
            return "$char[strRepeat $char [incr num -1]]"
        }
    }
}
#source [ file join [ file dirname [ info script ] ] adjust.tcl ]
#source [ file join [ file dirname [ info script ] ] split.tcl ]
#source [ file join [ file dirname [ info script ] ] tabify.tcl ]
#source [ file join [ file dirname [ info script ] ] trim.tcl ]
namespace eval ::textutil {
    namespace eval adjust {
        variable StrRepeat [ namespace parent ]::strRepeat
        variable Justify  left
        variable Length   72
        variable FullLine 0
        variable StrictLength 0
        namespace export adjust
        # This will be redefined later. We need it just to let
        # a chance for the next import subcommand to work
        #
        proc adjust { text args } { }
    }
    namespace import -force adjust::adjust
    namespace export adjust
}
#########################################################################
proc ::textutil::adjust::adjust { text args } {
    if { [ string length [ string trim $text ] ] == 0 } then {
        return ""
    }
    Configure $args
    Adjust text newtext
    return $newtext
}
proc ::textutil::adjust::Configure { args } {
    variable Justify   left
    variable Length    72
    variable FullLine  0
    variable StrictLength 0
    set args [ lindex $args 0 ]
    foreach { option value } $args {
        switch -exact -- $option {
            -full {
                if { ![ StringIsBoolean -strict $value ] } then {
                    error "expected boolean but got \"$value\""
                }
                set FullLine [ StringIsTrue $value ]
            }
            -justify {
                set lovalue [ string tolower $value ]
                switch -exact -- $lovalue {
                    left -
                    right -
                    center -
                    plain {
                        set Justify $lovalue
                    }
                    default {
                        error "bad value \"$value\": should be center, left, plain or right"
                    }
                }
            }
            -length {
                if { ![ StringIsInteger $value ] } then {
                    error "expected positive integer but got \"$value\""
                }
                if { $value < 1 } then {
                    error "expected positive integer but got \"$value\""
                }
                set Length $value
            }
            -strictlength {
                if { ![ StringIsBoolean -strict $value ] } then {
                    error "expected boolean but got \"$value\""
                }
                set StrictLength [ StringIsTrue $value ]
            }
            default {
                error "bad option \"$option\": must be -full, -justify, -length, or -strictlength"
            }
        }
    }
    return ""
}
proc ::textutil::adjust::StringIsBoolean { arg value } {
    switch -- [string tolower $value] {
        0 - false - no - off { return 1 }
        default { return [StringIsTrue $value] }
    }
}
proc ::textutil::adjust::StringIsTrue { value } {
    switch -- [string tolower $value] {
        1 - true - yes - on { return 1 }
        default { return 0 }
    }
}
proc ::textutil::adjust::StringIsInteger { value } {
    if {[catch { incr value }]} {
        return 0
    }
    return 1
}
proc ::textutil::adjust::Adjust { varOrigName varNewName } {
    variable Length
    variable StrictLength
    upvar $varOrigName orig
    upvar $varNewName  text
    regsub -all -- "(\n)|(\t)"     $orig  " "  text
    regsub -all -- " +"            $text  " "  text
    regsub -all -- "(^ *)|( *\$)"  $text  ""   text
    set ltext [ split $text ]
    if { $StrictLength } then {
        # Limit the length of a line to $Length. If any single
        # word is long than $Length, then split the word into multiple
        # words.
        set i 0
        foreach tmpWord $ltext {
            if { [ string length $tmpWord ] > $Length } then {
                # Since the word is longer than the line length,
                # remove the word from the list of words.  Then
                # we will insert several words that are less than
                # or equal to the line length in place of this word.
                set ltext [ lreplace $ltext $i $i ]
                incr i -1
                set j 0
                # Insert a series of shorter words in place of the
                # one word that was too long.
                while { $j < [ string length $tmpWord ] } {
                    # Calculate the end of the string range for this word.
                    if { [ expr { [string length $tmpWord ] - $j } ] > $Length } then {
                        set end [ expr { $j + $Length - 1} ]
                    } else {
                        set end [ string length $tmpWord ]
                    }
                    set ltext [ linsert $ltext [ expr {$i + 1} ] [ string range $tmpWord $j $end ] ]
                    incr i
                    incr j [ expr { $end - $j + 1 } ]
                }
            }
            incr i
        }
    }
    set line [ lindex $ltext 0 ]
    set pos [ string length $line ]
    set text ""
    set numline 0
    set numword 1
    set words(0) 1
    set words(1) [ list $pos $line ]
    foreach word [ lrange $ltext 1 end ] {
        set size [ string length $word ]
        if { ( $pos + $size ) < $Length } then {
            append line " $word"
            incr numword
            incr words(0)
            set words($numword) [ list $size $word ]
            incr pos
            incr pos $size
        } else {
            if { [ string length $text ] != 0 } then {
                append text "\n"
            }
            append text [ Justification $line [ incr numline ] words ]
            set line "$word"
            set pos $size
            catch { unset words }
            set numword 1
            set words(0) 1
            set words(1) [ list $size $word ]
        }
    }
    if { [ string length $text ] != 0 } then {
        append text "\n"
    }
    append text [ Justification $line end words ]
    return $text
}
proc ::textutil::adjust::Justification { line index arrayName } {
    variable Justify
    variable Length
    variable FullLine
    variable StrRepeat
    upvar $arrayName words
    set len [ string length $line ]
    if { $Length == $len } then {
        return $line
    }
    # Special case:
    # for the last line, and if the justification is set to 'plain'
    # the real justification is 'left' if the length of the line
    # is less than 90% (rounded) of the max length allowed. This is
    # to avoid expansion of this line when it is too small: without
    # it, the added spaces will 'unbeautify' the result.
    #
    set justify $Justify
    if { ( "$index" == "end" ) && \
             ( "$Justify" == "plain" ) && \
             ( $len < round($Length * 0.90) ) } then {
        set justify left
    }
    # For a left justification, nothing to do, but to
    # add some spaces at the end of the line if requested
    #
    if { "$justify" == "left" } then {
        set jus ""
        if { $FullLine } then {
            set jus [ $StrRepeat " " [ expr { $Length - $len } ] ]
        }
        return "${line}${jus}"
    }
    # For a right justification, just add enough spaces
    # at the beginning of the line
    #
    if { "$justify" == "right" } then {
        set jus [ $StrRepeat " " [ expr { $Length - $len } ] ]
        return "${jus}${line}"
    }
    # For a center justification, add half of the needed spaces
    # at the beginning of the line, and the rest at the end
    # only if needed.
    if { "$justify" == "center" } then {
        set mr [ expr { ( $Length - $len ) / 2 } ]
        set ml [ expr { $Length - $len - $mr } ]
        set jusl [ $StrRepeat " " $ml ]
        set jusr [ $StrRepeat " " $mr ]
        if { $FullLine } then {
            return "${jusl}${line}${jusr}"
        } else {
            return "${jusl}${line}"
        }
    }
    # For a plain justiciation, it's a little bit complex:
    # if some spaces are missing, then
    # sort the list of words in the current line by
    # decreasing size
    # foreach word, add one space before it, except if
    # it's the first word, until enough spaces are added
    # then rebuild the line
    #
    if { "$justify" == "plain" } then {
        set miss [ expr { $Length - [ string length $line ] } ]
        if { $miss == 0 } then {
            return "${line}"
        }
        for { set i 1 } { $i < $words(0) } { incr i } {
            lappend list [ eval list $i $words($i) 1 ]
        }
        lappend list [ eval list $i $words($words(0)) 0 ]
        set list [ SortList $list decreasing 1 ]
        set i 0
        while { $miss > 0 } {
            set elem [ lindex $list $i ]
            set nb [ lindex $elem 3 ]
            incr nb
            set elem [ lreplace $elem 3 3 $nb ]
            set list [ lreplace $list $i $i $elem ]
            incr miss -1
            incr i
            if { $i == $words(0) } then {
                set i 0
            }
        }
        set list [ SortList $list increasing 0 ]
        set line ""
        foreach elem $list {
            set jus [ $StrRepeat " " [ lindex $elem 3 ] ]
            set word [ lindex $elem 2 ]
            if { [ lindex $elem 0 ] == $words(0) } then {
                append line "${jus}${word}"
            } else {
                append line "${word}${jus}"
            }
        }
        return "${line}"
    }
    error "Illegal justification key \"$justify\""
}
proc ::textutil::adjust::SortList { list dir index } {
    if { [ catch { lsort -integer -$dir -index $index $list } sl ] != 0 } then {
        error "$sl"
    }
    return $sl
}
}
#   }}}1 textutil package (unless externally available)
#   {{{1 Top-level parsing
global parser
if {![info exists parser]} {
    set parser ""
}
proc xml2rfc {input {output ""} {remote ""} {cdP 1}} {
    global prog
    global errorCode errorInfo
    global parser
    global passno
    global passmax
    global errorP
    global ifile mode unpaginated ofile
    global out_fd
    global remoteP
    global xml2rfc_warnings
    set xml2rfc_warnings ""
    if {![string compare [file extension $input] ""]} {
        append input .xml
    }
    set inputD [file dirname [set ifile $input]]
    if {$cdP} {
        catch { cd $inputD }
    }
    if {![string compare $output ""]} {
        set output [file rootname $input].txt
    }
    if {[string compare $remote ""]} {
        set ofile $remote
        set remoteP 1
    } else {
        set ofile $output
        set remoteP 0
    }
    set ofile [file rootname [file tail $ofile]]
    if {![string compare $input $output]} {
        error "input and output files must be different"
    }
    if {[file exists [set file [file join $inputD .$prog.rc]]]} {
        catch { source $file }
    }
    unex_init
    set unpaginated 0
    switch -- [set mode [string range [file extension $output] 1 end]] {
        html - nr - txt {}
        unpg {
            set unpaginated 1
            set mode txt
        }
        xml {}
        default {
            error "unsupported output type: $mode"
        }
    }
    set code [catch {
        set in_fd [open $input { RDONLY }]
        catch { fconfigure $in_fd -encoding binary -translation lf }
        set data [prexml [read $in_fd]]
        catch { close $in_fd }
        set in_fd ""
        if {![string compare $mode xml]} {
            global prog_version
            set out_fd [open $output { WRONLY CREAT TRUNC }]
            catch { fconfigure $out_fd -encoding utf-8 }
            set comment [clock format [clock seconds] \
                            -format "<!-- automatically generated by $prog $prog_version on %Y-%m-%dT%H:%M:%SZ -->" \
                            -gmt true]
            regsub {\n} $data "\n$comment\n" data
            puts -nonewline $out_fd $data
            catch { close $out_fd }
            set out_fd ""
            # break from catch
            break
        }
        if {![string compare $parser ""]} {
            global emptyA
            set parser [xml::parser]
            catch { array unset emptyA }
            $parser configure \
                        -elementstartcommand          { begin               } \
                        -elementendcommand            { end                 } \
                        -characterdatacommand         { pcdata              } \
                        -processinginstructioncommand { pi                  } \
                        -xmldeclcommand               { xmldecl             } \
                        -doctypecommand               { doctype             } \
                        -entityreferencecommand       ""                      \
                        -errorcommand                 { unexpected error    } \
                        -warningcommand               { unexpected warning  } \
                        -entityvariable               emptyA                  \
                        -final                        1                       \
                        -reportempty                  0
        }
        set errorP 0
        set passmax 2
        set out_fd ""
        for {set passno 1} {$passno <= $passmax} {incr passno} {
            if {$passno >= 6} {
                error "too many passes (document doesn't stabilize)"
            }
            if {$passno >= 2} {
                set out_fd [open $output { WRONLY CREAT TRUNC }]
                catch { fconfigure $out_fd -encoding utf-8 }
            }
            pass start
            $parser parse $data
            pass end
            catch { close $out_fd }
            set out_fd ""
            if {$errorP} {
                break
            }
        }
    } result]
    set ecode $errorCode
    set einfo $errorInfo
    catch { close $in_fd }
    set in_fd ""
    catch { close $out_fd }
    set out_fd ""
    if {$code == 3} {
        # break ($mode == xml)
        set code 0
    } elseif {$code == 1} {
        set result [around2fl $result]
        catch {
            global stack
            global guiP
            if {[set i [llength $stack]] > 0} {
                set text \
  "Context (format:  \"file_basename:line_in_file:#elem_num:<elem ...>\"):"
                while {$i > 0} {
                    set frame [lindex $stack [incr i -1]]
                    set attrs 0; unset attrs
                    array set attrs [list av ""]
                    array set attrs [lrange $frame 1 end]
                    append text "\n    "
                    append text [linefile::get_fake_file $attrs(fnum) 1]:
                    append text $attrs(line):#$attrs(elemN):
                    append text "<[lindex $frame 0]"
                    foreach {k v} $attrs(av) {
                        regsub -all -- \" $v {\"} v
                        append text " $k=\"$v\""
                    }
                    append text ">"
                }
                append result "\n\n$text"
                if {$guiP < 0} {
                    append result "\n$einfo"
                }
            }
        }
    }
    return -code $code -errorinfo $einfo -errorcode $ecode $result
}
proc xml2txt {input} {
    xml2rfc $input [file rootname $input].txt
}
proc xml2html {input} {
    xml2rfc $input [file rootname $input].html
}
proc xml2nroff {input} {
    return [xml2rfc $input [file rootname $input].nr]
###
    puts stderr "making xml->txt"
    xml2rfc $input [file rootname $input].txt
    file rename -force [file rootname $input].txt  [file rootname $input].orig
    puts stderr "making xml->rf"
    xml2rfc $input [file rootname $input].nr
    puts stderr "making rf->txt"
    exec nroff -ms < [file rootname $input].nr \
       | /usr/users/mrose/docs/fix.pl \
       | sed -e 1,3d \
       > [file rootname $input].txt
}
proc xml2unpg {input} {
    xml2rfc $input [file rootname $input].unpg
}
proc xml2ref {input output {formats {}} {item ""}} {
    global prog
    global errorCode errorInfo
    if {![string compare $input $output]} {
        error "input and output files must be different"
    }
    if {[file exists [set file [file join [set inputD [file dirname $input]] \
                                          .$prog.rc]]]} {
        source $file
    }
    set refT [ref::init]
    if {[set code [catch { ref::transform $refT $input $formats } result]]} {
        set ecode $errorCode
        set einfo $errorInfo
        catch { ref::fin $refT }
        return -code $code -errorinfo $einfo -errorcode $ecode $result
    }
    ref::fin $refT
    array set ref $result
    set out_fd [open $output { WRONLY CREAT TRUNC }]
    catch { fconfigure $out_fd -encoding utf-8 }
    set code [catch {
        puts -nonewline $out_fd $ref(body)
        flush $out_fd
    } result]
    set ecode $errorCode
    set einfo $errorInfo
    catch { close $out_fd }
    set out_fd ""
    if {($code == 0) \
            && ([string compare $item ""]) \
            && ([string compare $ref(info) ""])} {
        set out_fd [open $item { WRONLY CREAT TRUNC }]
        catch { fconfigure $out_fd -encoding utf-8 }
        set code [catch {
            puts -nonewline $out_fd $ref(info)
            flush $out_fd
        } result]
        set ecode $errorCode
        set einfo $errorInfo
        catch { close $out_fd }
        set out_fd ""
        #catch { file mtime $item $ref(mtime) }
    }
    return -code $code -errorinfo $einfo -errorcode $ecode $result
}
#   }}}1 Top-level parsing
#   {{{1 XML preprocessor
#       {{{2 Some XML preprocessor globals
global httpP
if {[catch { package require http 2 }]} {
    set httpP 0
} else {
    set httpP 1
    catch {
        package require autoproxy
        autoproxy::init
    }
    # Make sure it's auto-loaded before attempting to modify its variable.
    ::http::config
    set ::http::defaultCharset unknown
}
proc check_vrsn {} {
    global env
    global guiP
    global prog_version prog_url
    if {[info exists env(DOCUMENT_ROOT)]} {
        return
    }
    if {$guiP == 1} {
        update
    }
    if {[string first "pre" $prog_version] > 0} {
        set file beta
    } else {
        set file version
    }
    catch {
        ::http::geturl ${prog_url}authoring/$file \
                       -command check_vrsn_command -timeout 3000
    }
}
proc check_vrsn_idle {} {
    catch { update }
}
proc check_vrsn_command {token} {
    global guiP
    global prog prog_version
    upvar #0 $token state
    if {($state(status) == "ok") \
            && ([::http::ncode $token] == 200) \
            && ([string compare $prog_version \
                        [set body [string trim $state(body)]]]) < 0} {
        set text "$body is now available, you are running $prog_version"
        if {$guiP != 1} {
            puts stdout "$prog: $text"
        } else {
            set w .fyi
            catch { destroy $w }
            toplevel    $w -class Dialog
            wm title    $w "$prog: fyi"
            wm iconname $w Dialog
            frame  $w.top
            pack   $w.top -side    top    -fill both  -expand 1
            frame  $w.bot
            pack   $w.bot -side    bottom -fill both
            label  $w.msg -justify left   -text $text
            pack   $w.msg -side    right  -fill both  -expand 1 \
                          -in      $w.top -padx 3m    -pady   3m
            label  $w.bmp -bitmap  info
            pack   $w.bmp -side    left \
                          -in      $w.top -padx 3m    -pady   3m
            button $w.bye -text    Dismiss \
                          -command "destroy $w"
            pack   $w.bye -in      $w.bot
        }
    }
    catch { ::http::cleanup $token }
}
global xml_library_path
set xml_library_path {.}
#       }}}2 Some XML preprocessor globals
#       {{{2 XML preprocessor entry function
proc prexml {stream} {
    global env tcl_platform
    global intentities extentities extfiles exturis
    global xml_library_path
    global ifile
    if {[catch { set xml_library_path $env(XML_LIBRARY) }]} {
        set xml_library_path [list [file dirname $ifile]]
    }
    switch -- $tcl_platform(platform) {
        windows { set c ";" }
        default { set c ":" }
    }
    set xml_library_path [split $xml_library_path $c]
    set stream [prexml_cdata $stream]
    set ifnum [linefile::new_file $ifile $ifile]
    catch { array unset intentities }
    catch { array unset extentities }
    catch { array unset extfiles }
    catch { array unset exturis }
    if {   [regexp -- {^<\?xml[ \t\r\n]} $stream]
        && ([set plen [string first "?>" $stream]] >= 0)} {
        set XMLDecl [string range $stream 0 [incr plen]]
        set stream [string range $stream [incr plen] end]
    } else {
        error "input file \"$ifile\" does not begin with an XML declaration"
    }
    set stream [prexml_convert $XMLDecl $stream $ifile]
    # Now that we are in UTF-8.
    set stream [str_norm_eol $stream \
                [expr   [regexp -- {[ \t\r\n]version="1\.[1-9][0-9]*"} $XMLDecl] \
                     || [regexp -- {[ \t\r\n]version='1\.[1-9][0-9]*'} $XMLDecl]]]
    linefile::init
    set n [num_eols $XMLDecl]
    set XMLDecl "<?xml version=\"1.0\" encoding=\"UTF-8\"[string repeat \n $n]?>"
    linefile::push_fnum $ifnum
    return $XMLDecl[prexml_stream $stream [expr 1 + $n]]
}
#       }}}2 XML preprocessor entry function
#       {{{2 XML preprocessor initial conversions
proc prexml_convert {XMLDecl stream file {default_charset UTF-8}} {
    if {   [regexp -- {[ \t\r\n]encoding="([A-Za-z][A-Za-z0-9._-]*)"} $XMLDecl x charset]
        || [regexp -- {[ \t\r\n]encoding='([A-Za-z][A-Za-z0-9._-]*)'} $XMLDecl x charset]
        || [string compare [set charset $default_charset] ""]} {
            if {![string compare [set enc [cs2enc $charset]] ""]} {
                set enc ascii
                unexpected warning \
  "unknown encoding/charset \"$charset\" in XML declaration of file \"$file\"; trying US-ASCII"
            }
    } else {
        set enc utf-8
    }
    catch { set stream [encoding convertfrom $enc $stream] }
    return $stream
}
proc prexml_cdata {stream} {
    set litN [string length [set litS "<!\[CDATA\["]]
    set litO [string length [set litT "\]\]>"]]
    set data ""
    while {[set x [string first $litS $stream]] >= 0} {
        append data [string range $stream 0 [expr $x-1]]
        set stream [string range $stream [expr $x+$litN] end]
        if {[set x [string first $litT $stream]] < 0} {
            error "missing close to CDATA"
        }
        set y [string range $stream 0 [expr $x-1]]
        regsub -all -- {&} $y {\&} y
        regsub -all -- {<} $y {\<}  y
        regsub -all -- {>} $y {\>}  y
        append data $y
        set stream [string range $stream [expr $x+$litO] end]
    }
    append data $stream
    return $data
}
#       }}}2 XML preprocessor initial conversions
#       {{{2 XML preprocessor stream (file) handling
proc prexml_stream {stream {myline 1} {no_initial_pi 0}} {
    # Uses uplevel proc prexml_error.
    # Uses uplevel proc prexml_flush_blank.
    # Uses uplevel proc prexml_flush_new.
    # Uses uplevel proc prexml_flush_pi.
    # Uses uplevel proc prexml_flush_includes.
    # Uses uplevel proc prexml_prep_entity.
    global extentities intentities
    if {[info level] > 32} {
        error "recursion detected in XML preprocessing of included files and entities"
    }
    # Some useful regexp literals.
    set wsp  {[ \t\r\n]}
    set dqev \"(\[^\"\]*)\"
    set sqev \'(\[^\'\]*)\'
    set nme  {([A-Za-z_:][A-Za-z0-9._:-]*)}
    set rem  (.*)
    set myfnum [linefile::get_real_fnum]
    if {$no_initial_pi} {
        set data ""
    } else {
        set data [linefile::make_pi $myfnum $myline 1]
    }
    # We don't modify stream but scan across it and build data.
    for {
        # Loop Initialization.
        set pending_pi 0
        set new_data ""
        set new_lines 0
        set blank_lines 0
        set includes ""
        set start 0
        # Loop test.
    } {[regexp -indices -start $start -- {<\?rfc|<!ENTITY|&} $stream x]} {
        # Loop continuation.
        prexml_flush_new
        prexml_flush_includes
    } {
        # Loop body.
        set a [lindex $x 0]
        set b [lindex $x 1]
        set m [string range $stream $a $b]
        if {$a > $start} {
            prexml_flush_blank
            prexml_flush_pi
            set initial [string range $stream $start [expr $a - 1]]
            incr myline [num_eols $initial]
            append data $initial
            unset initial
        }
        incr b
        switch -- $m {
            <?rfc {
                if {![regexp -indices -start $b -- {\?>} $stream x]} {
                    prexml_error "missing close to $m"
                }
                set c [lindex $x 0]
                set pi [string range $stream $b [expr $c - 1]]
                incr new_lines [num_eols $pi]
                set start [incr c 2]
                # We'll normally append new_data later,
                # after $pi has been tweaked.
                if {![regexp -- ^$wsp $pi]} {
                    append new_data $m $pi ?>
                    continue
                }
                prexml_flush_pi
                set kept_pi_dirs 0
                set pil [string length $pi]
                set pi2 $pi
                while {1} {
                    set pi2s [expr $pil - [set pi2l [string length $pi2]]]
                    foreach {key val pi2} [pi_rfc_next $pi2] {break}
                    if {![string compare $key ""]} {
                        global mode
                        # We may be able to provide a better message later.
                        if {   [string compare $val ""]
                            && ![string compare $mode xml]} {
                            prexml_error "stopped preprocessing faulty rfc-PI at \"$val\""
                        }
                        # This makes sure the faulty rfc-PI is kept for later stages.
                        incr kept_pi_dirs
                        break
                    }
                    switch -- $key {
                        include {
                            set pi [streplace $pi $pi2s [expr $pi2l - [string length $pi2] + 1] "" 3]
                            foreach {fnum include charset} [prexml_find $val] {break}
                            set include [prexml_tweak_include $include $fnum $charset]
                            if {[string compare $include ""]} {
                                linefile::push_fnum $fnum
                                append includes [prexml_stream $include 1]
                                linefile::pop_fake_fnum
                            }
                        }
                        linefile {
                            incr kept_pi_dirs
                            if {![regexp -- {^([0-9]+)(:(.*))?$} \
                                         $val a b c d]} {
                                # Type of message must not attempt to
                                # supply its own line information which
                                # is not set up at this point.
                                unexpected warning \
  "ignoring invalid rfc-PI linefile-directive value \"$val\" around input line $myline in \"[linefile::get_fake_file $myfnum]\""
                                continue
                            }
                            prexml_flush_blank
                            if {[string length $c]} {
                                # May be empty.  User's choice!
                                set new_myfile $d
                            }
                            set new_myline $b
                        }
                        default {
                            incr kept_pi_dirs
                        }
                    }
                }
                # Do this after processing the whole PI so that
                # intermixed error or warning messages are not affected.
                if {[info exists new_myline]} {
                    if {[info exists new_myfile]} {
                        set myfnum [linefile::set_file $new_myfile]
                        unset new_myfile
                    }
                    set myline $new_myline
                    unset new_myline
                    set new_lines 0
                }
                if {$kept_pi_dirs} {
                    prexml_flush_blank
                    append new_data $m $pi ?>
                } else {
                    incr blank_lines $new_lines
                    set new_lines 0
                }
            }
            <!ENTITY {
                if {![regexp -indices -start $b -- {>} $stream x]} {
                    prexml_error "missing close to $m"
                }
                set c [lindex $x 0]
                set entdecl [string range $stream $b [expr $c - 1]]
                set n [num_eols $entdecl]
                set start [incr c]
                if {![regexp -- ^$wsp $entdecl]} {
                    append new_data $m $entdecl >
                    incr new_lines $n
                    continue
                }
                if {$n} {
                    prexml_flush_pi
                }
                # These are _new_ blank lines.
                incr blank_lines $n
                set entdecl [string trimleft $entdecl]
                if {[string first "%" $entdecl] == 0} {
                    set entdecl [string trimleft [string range $entdecl 1 end]]
                    unexpected warning "treating parameter entity as parsed (remove % in entity declaration)"
                }
                if {![regexp -- ^$nme$rem $entdecl x entity entdef]} {
                    prexml_error "expecting $m entity-name ..."
                }
                append new_data "<!-- xml2rfc-processed-entity " $entity " -->"
                if {   [regexp -- ^$wsp+$dqev$rem $entdef x arg1 y]
                    || [regexp -- ^$wsp+$sqev$rem $entdef x arg1 y]} {
                    set fnum $myfnum
                    set include [prexml_cdata $arg1]
                    set line [expr $myline + $new_lines + $blank_lines \
                                   - [num_eols $include$y]]
                    set intentities($entity) [prexml_prep_entity]
                    continue
                }
                if {![regexp -nocase -- \
                             ^$wsp*(SYSTEM|PUBLIC)$rem \
                             $entdef x idtype entid]} {
                    prexml_error \
  "expecting $m $entity SYSTEM, PUBLIC, 'def', or \"def\""
                }
                if {   ![regexp -- ^$wsp+$dqev$rem $entid x arg1 arg2]
                    && ![regexp -- ^$wsp+$sqev$rem $entid x arg1 arg2]} {
                    prexml_error "expecting literal after $m $entity $idtype"
                }
                set idtype [string toupper $idtype]
                switch -- $idtype {
                    SYSTEM {
                        set l [prexml_find $arg1]
                    }
                    PUBLIC {
                        if {   ![regexp -- ^$wsp+$dqev $arg2 z arg2]
                            && ![regexp -- ^$wsp+$sqev $arg2 z arg2]} {
                            prexml_error "expecting literal after $m $entity $idtype"
                        }
                        set l [prexml_find $arg2]
                    }
                }
                foreach {fnum include charset} $l {break}
                set include [prexml_tweak_include $include $fnum $charset]
                set line 1
                set extentities($entity) [prexml_prep_entity]
            }
            & {
                set start $b
                if {![regexp -indices -start $b -- {;} $stream x]} {
                    append new_data &
                    continue
                }
                set c [lindex $x 0]
                set entity [string trim [string range $stream $b [expr $c - 1]]]
                if {[info exists intentities($entity)]} {
                    set l $intentities($entity)
                } elseif {[info exists extentities($entity)]} {
                    set l $extentities($entity)
                } else {
                    append new_data &
                    continue
                }
                foreach {inc_fnum inc_line include end_fnum} $l {break}
                if {[string compare $include ""]} {
                    append includes [linefile::make_pi $inc_fnum $inc_line]
                    append includes $include
                    linefile::set_fake_fnum $end_fnum
                }
                set start [incr c]
            }
        }
    }
    prexml_flush_blank
    if {$start < [string length $stream]} {
        prexml_flush_pi
        append data [string range $stream $start end]
    }
    return $data
}
#       }}}2 XML preprocessor stream (file) handling
#       {{{2 Uplevel procs meant for use by prexml_stream
proc prexml_error {e} {
    upvar myfnum myfnum myline myline
    error "$e around input line $myline in \"[linefile::get_fake_file $myfnum]\""
}
proc prexml_flush_blank {} {
    uplevel 1 {
        if {$blank_lines} {
            incr myline $blank_lines
            append data <!-- [string repeat "\n" $blank_lines] -->
            set blank_lines 0
        }
    }
}
proc prexml_flush_new {} {
    uplevel 1 {
        if {[string compare $new_data ""]} {
            prexml_flush_blank
            prexml_flush_pi
            incr myline $new_lines
            append data $new_data
            set new_data ""
            set new_lines 0
        }
    }
}
proc prexml_flush_pi {} {
    uplevel 1 {
        if {$pending_pi} {
            prexml_flush_blank
            append data [linefile::make_pi $myfnum $myline]
            set pending_pi 0
        }
    }
}
proc prexml_flush_includes {} {
    uplevel 1 {
        if {[string compare $includes ""]} {
            prexml_flush_blank
            append data $includes
            set includes ""
            set pending_pi 1
        }
    }
}
proc prexml_prep_entity {} {
    uplevel 1 {
        if {[string compare $include ""]} {
            linefile::push_fnum $fnum
            set include [prexml_stream $include $line 1]
            set end_fnum [linefile::pop_fake_fnum]
        } else {
            set end_fnum $myfnum
        }
        return [list $fnum $line $include $end_fnum]
    }
}
#       }}}2 Uplevel procs meant for use by prexml_stream
#       {{{2 Regular, non-uplevel, support procs for prexml_stream.
proc prexml_find {uf} {
    # Remote absolute path.
    if {[string first "http://" $uf] == 0} {
        return [prexml_find_uri $uf $uf]
    }
    # Local absolute path.
    if {![string compare [file pathtype $uf] absolute]} {
        set f [file_normalize $uf]
        return [prexml_find_file $uf $f]
    }
    set fulldir [linefile::get_real_fulldir]
    # Local fulldir + relative path.
    if {[string first "://" $fulldir] < 0} {
        set f [file_normalize [file join $fulldir $uf]]
        if {![catch { set v [prexml_find_file $uf $f] }]} {
            return $v
        }
    }
    # Scan XML_LIBRARY directories.
    global xml_library_path
    foreach dir $xml_library_path {
        set f [file_normalize [file join $dir $uf]]
        if {![catch { set v [prexml_find_file $uf $f] }]} {
            return $v
        }
    }
    # Remote fulldir + relative path.  (Go to network last.)
    if {[string first "http://" $fulldir] == 0} {
        set u $fulldir/$uf
        while {[regsub -- {^([^?#]*[^/?#])/\./} $u {\1/} u]} {}
        while {[regsub -expanded -- {^([^?#]*[^/?#])
                                     /([^/?#]
                                      |[^/?#][^/?#.]
                                      |[^/?#.][^/?#]
                                      |[^/?#]{3,})
                                     /\.\./} $u {\1/} u]} {}
        while {[regsub -- {^([^?#]*[^/?#])/\.\./} $u {\1/} u]} {}
        return [prexml_find_uri $uf $u]
    }
    error "unable to find external file \"$uf\" or \"$uf.xml\""
}
proc file_normalize {path} {
    if {![catch { file normalize $path } result]} {
        return $result
    }
# we could do a lot of work here, but we won't...
    switch -- [string range $path 0 0] {
        "/" {
        }
        "~" {
            set comps [file split $path]
            set path [eval file join [glob [lindex $comps 0]] \
                                     [lrange $comps 1 end]]
        }
        default {
            set path [file join [pwd] $path]
        }
    }
    set result {}
    foreach comp [set comps [file split $path]] {
        switch -- $comp {
            "." {
            }
            ".." {
                set result [lrange $result 0 end-1]
            }
            "/" {
            }
            default {
                lappend result $comp
            }
        }
    }
    return [eval file join "/" $result]
}
proc prexml_find_file {s f} {
    global extfiles
    if {   [info exists extfiles([set fx $f])]
        || [info exists extfiles([set fx $f.xml])]} {
        set fnum [linefile::new_file $s $fx]
        return [concat $fnum $extfiles($fx)]
    }
    set foundP 0
    catch {
        if {   ![file exists [set file [set fx $f    ]]]
            && ![file exists [set file [set fx $f.xml]]]} {
            break
        }
        set fd ""
        catch {
            set fd [open $file { RDONLY }]
            catch { fconfigure $fd -encoding binary -translation lf }
            set content [prexml_cdata [read $fd]]
            set foundP 1
        }
        catch { close $fd }
    }
    if {!$foundP} {
        error "unable to find external file \"$s\" or \"$s.xml\""
    }
    set fnum [linefile::new_file $s $fx]
    set extfiles($fx) [list $content UTF-8]
    return [list $fnum $content UTF-8]
}
proc prexml_find_uri {s u} {
    global exturis
    global httpP
    if {   [info exists exturis([set ux $u    ])]
        || [info exists exturis([set ux $u.xml])]} {
        set fnum [linefile::new_file $s $ux]
        return [concat $fnum $exturis($ux)]
    }
    if {!$httpP} {
        error "unable to find http package"
    }
    # Note that, as of writing, the http package still does not grasp
    # that IANA charset names and Tcl encoding names are generally
    # incompatible (e.g., "iso8859-1" is a Tcl encoding name but not an
    # IANA charset name), so it cannot be trusted with these conversions.
    set httpV [package present http]
    regexp -- {^[0-9]+\.[0-9]+} $httpV httpV
    set code "http package failed"
    catch {
        if {$httpV >= 2.4} {
            set httpT [http::geturl $u -binary true]
        } else {
            set httpT [http::geturl $u]
        }
        set code [http::code $httpT]
        if {![string compare [lindex $code 1] 404]} {
            set u $u.xml
            if {$httpV >= 2.4} {
                set httpT [http::geturl $u -binary true]
            } else {
                set httpT [http::geturl $u]
            }
            set code [http::code $httpT]
        }
    }
    if {[string compare [lindex $code 1] 200]} {
        error "$u: $code"
    }
    upvar #0 $httpT httpS
    set content [http::data $httpT]
    # An XMLDecl or TextDecl can still override this.
    set default_charset UTF-8
    if {$httpV >= 2.4} {
        if {[string compare $httpS(charset) unknown]} {
            set default_charset $httpS(charset)
        } elseif {[regexp -nocase -- {^text([\t /;]|$)} $httpS(type)]} {
            set default_charset ISO-8859-1
        }
    } elseif {[regexp -nocase -- ^text $httpS(type)]} {
        # Undo the systematic utf-8 encoding conversion done by this
        # old http package.  We already lost before this point if it
        # wasn't originally utf-8 content because the conversion
        # massaged anything that didn't look like well-formed utf-8!
        catch { set content [encoding convertto utf-8 $content] }
    }
    set content [prexml_cdata $content]
    http::cleanup $httpT
    set fnum [linefile::new_file $s $u]
    set exturis($u) [list $content $default_charset]
    return [list $fnum $content $default_charset]
}
proc prexml_tweak_include {include {convert_fnum -1} {default_charset UTF-8}} {
    set start 0
    set XMLDecl ""
    set body [string trimleft $include]
    if {   [regexp -nocase -- {^<\?xml[ \t\r\n]} $body]
        && [set len [string first "?>" $body]] >= 0} {
        set start [expr [string length $include] - [string length $body]]
        set end [expr $start + $len + 1]
        set XMLDecl [string range $include $start $end]
        set len [string length $include]
        set include [streplace $include $start $end "" 2]
        incr end [expr [set len2 [string length $include]] - $len]
        set include [streplace $include 0 $start \
                               [str_norm_eol [string range $include 0 $start]]]
        incr end [expr [string length $include] - $len2]
        set start [expr $end + 1]
    }
    if {$convert_fnum >= 0} {
        set include [prexml_convert $XMLDecl $include \
                                    [linefile::get_fake_file $convert_fnum] \
                                    $default_charset]
    }
    # Now that we are in UTF-8.
    set xml11 [expr   [regexp -- {[ \t\r\n]version="1\.[1-9][0-9]*"} $XMLDecl] \
                   || [regexp -- {[ \t\r\n]version='1\.[1-9][0-9]*'} $XMLDecl]]
    set include [str_norm_eol $include $xml11]
    set body [string trimleft [string range $include $start end]]
    if {   [regexp -nocase -- {^<!DOCTYPE[ \t\r\n]} $body]
        && [set len [string first ">" $body]] >= 0} {
        set start [expr [string length $include] - [string length $body]]
        if {   [set len2 [string first {[} $body]] < $len
            && [string first {]} $body] > $len} {
            set include [streplace $include $start [expr $start + $len2] "" 2]
            set start [string first {]} $include]
            set len [string first ">" [string range $include $start end]]
            set include [streplace $include $start [expr $start + $len] "" 2]
        } else {
            set end [expr $start + $len]
            set include [streplace $include $start $end "" 2]
        }
    }
    return $include
}
#       }}}2 Regular, non-uplevel, support procs for prexml_stream.
#   }}}1 XML preprocessor
#   {{{1 Utility functions
proc sum_list {list} {
    set total 0
    foreach i $list {
        if {[string compare $i ""]} {
            incr total $i
        }
    }
    return $total
}
proc add_lists {lx ly} {
    set lz {}
    foreach x $lx y $ly {
        if {![string is integer $x]} {
            set x 0
        }
        if {![string is integer $y]} {
            set y 0
        }
        lappend lz [expr $x + $y]
    }
    return $lz
}
proc subtract_lists {lx ly} {
    set lz {}
    foreach x $lx y $ly {
        if {![string is integer $x]} {
            set x 0
        }
        if {![string is integer $y]} {
            set y 0
        }
        lappend lz [expr $x - $y]
    }
    return $lz
}
proc num_eols {text} {
    # Number of "\n" in $text, even if last line unterminated.
    return [regexp -all -- "\n" $text]
}
proc around2fl {result} {
    global pcdata_line_offset
    global ifile
    set y [regexp -nocase -- { around line ([1-9][0-9]*)} \
                  $result x lineno]
    if {$y > 1} {
        return $result
    } elseif {$y == 0} {
        if {[set lineno $::xdv::lineno] < 0} {
            return $result
        }
        append result [set x " around line $lineno"]
    }
    set file [linefile::get_fake_file]
    set line [linefile::get_line [expr $lineno + $pcdata_line_offset]]
    set tail " around input line $line"
    if {[string compare $file $ifile]} {
        append tail " in \"$file\""
    }
    regsub -- $x $result $tail result
    return $result
}
#   }}}1 Utility functions
#   {{{1 The linefile stuff in its own namespace
namespace eval linefile {
    variable  offset 1  fncache {{}}  real_stack {0}  fake_stack {0}
}
proc linefile::init {} {
    variable offset
    variable real_stack
    variable fake_stack
    set offset 1
    set real_stack {0}
    set fake_stack {0}
}
proc linefile::get_line {{lineno -1}} {
    variable offset
    if {$lineno < 0} {
        set lineno $::xdv::lineno
    }
    return [expr $lineno + $offset]
}
proc linefile::set_line {line} {
    variable offset
    set offset [expr $line - $::xdv::lineno]
}
proc linefile::new_file {file {fullpath ""}} {
    variable fncache
    set fn [list $file $fullpath]
    if {[set fnum [lsearch -exact $fncache $fn]] < 0} {
        set fnum [llength $fncache]
        lappend fncache $fn
    }
    return $fnum
}
proc linefile::get_real_fnum {} {
    variable real_stack
    lindex $real_stack end
}
proc linefile::get_fake_fnum {} {
    variable fake_stack
    lindex $fake_stack end
}
proc linefile::get_real_key {{fnum -1}} {
    variable fncache
    if {$fnum < 0} {
        set fnum [get_real_fnum]
    }
    lindex $fncache $fnum
}
proc linefile::get_fake_key {{fnum -1}} {
    variable fncache
    if {$fnum < 0} {
        set fnum [get_fake_fnum]
    }
    lindex $fncache $fnum
}
proc linefile::get_fake_file {{fnum -1} {basename 0}} {
    set file [lindex [get_fake_key $fnum] 0]
    set sep "[file join \[/ \]]"
    if {$basename > 0} {
        # Only keep base name of file.
        regsub -- "^.*$sep" $file {} file
    }
    return $file
}
proc linefile::get_real_fullpath {{fnum -1}} {
    lindex [get_real_key $fnum] 1
}
proc linefile::get_real_fulldir {{fnum -1}} {
    set fullpath [lindex [get_real_key $fnum] 1]
    if {[string first :// $fullpath] >= 0} {
        set sep {[/]}
    } else {
        set sep "[file join \[/ \]]"
    }
    set fulldir ""
    regexp -- "^(.*)$sep" $fullpath x fulldir
    if {   ![string compare $fulldir ""]
        && ![regexp -- "^${sep}+" $fullpath fulldir]} {
        global tcl_platform
        switch -- $tcl_platform(platform) {
            macintosh { set dir : }
            default   { set dir . }
        }
    }
    return $fulldir
}
proc linefile::set_real_fnum {fnum} {
    variable real_stack
    set real_stack [lreplace real_stack end end $fnum]
    return $fnum
}
proc linefile::set_fake_fnum {fnum} {
    variable fake_stack
    set fake_stack [lreplace fake_stack end end $fnum]
    return $fnum
}
proc linefile::set_file {file {fullpath ""}} {
    set fnum [new_file $file $fullpath]
    if {[string compare $fullpath ""]} {
        set_real_fnum $fnum
    } else {
        set_fake_fnum $fnum
    }
}
proc linefile::push_fnum {fnum} {
    variable real_stack
    variable fake_stack
    lappend real_stack $fnum
    lappend fake_stack $fnum
    return $fnum
}
proc linefile::push_file {file {fullpath ""}} {
    push_fnum [new_file $file $fullpath]
}
proc linefile::pop_fake_fnum {} {
    variable real_stack
    variable fake_stack
    set fnum [lindex $fake_stack end]
    set real_stack [lreplace $real_stack end end]
    set fake_stack [lreplace $fake_stack end end]
    return $fnum
}
proc linefile::make_pi {fnum line {force_file 0}} {
    if {$force_file || $fnum != [get_fake_fnum]} {
        set_fake_fnum $fnum
        set file [get_fake_file $fnum]
        regsub -all -- & $file {\&} file
        if {[string first \" $file] < 0} {
            set lcf \"$line:$file\"
        } elseif {[string first \' $file] < 0} {
            set lcf \'$line:$file\'
        } else {
            regsub -all -- \" $file {\"} file
            set lcf \"$line:$file\"
        }
    } else {
        set lcf \"$line\"
    }
    return "<?rfc linefile=$lcf?>"
}
#   }}}1 The linefile stuff in its own namespace
#   {{{1 XML linkage
#       {{{2 Main function
# globals used in parsing
#
#     counter - used for generating reference numbers
#       depth -  ..
#       elemN - index of current element
#        elem - array, indexed by elemN, having:
#               list of element attributes,
#               plus in pass 1
#                   .ANCHOR
#                   .CHILDREN
#                   .COUNTER
#                   .CTEXT
#                   .EDITNO
#                   .FMTCOUNTER
#                   .LONGEST_ROMAN
#                   .MAX
#                   .MIN
#                   .NAME
#               plus in further passes
#                   .ANNOTATIONS
#                   .FMTTOKEN
#                   .FORMAT
#                   .STYLE
#                   .WIDTH
#      passno - 1 or 2 (or maybe 3, if generating a TOC)
#       stack - the stack of elements, each frame having:
#               { element-name "elemN" elemN "children" { elemN... }
#                 "ctext" yes-or-no }
#        xref - array, indexed by anchor, having:
#               { "type" element-name "elemN" elemN "value" reference-number }
proc pass {tag} {
    global options
    global counter depth elemN elem stack xref
    global passno passmax pass_was_stable
    global anchorN
    global elemZ
    global crefs erefs
    global root
    switch -- $tag {
        start {
            unexpected notice "pass $passno..."
            set pass_was_stable 1
            if {$passno == 1} {
                set pass_was_stable 0
                catch { array unset counter }
                set counter(firstxref) {}
                catch { array unset depth }
                catch { array unset elem }
                catch { array unset xref }
                catch { array unset crefs }
                catch { array unset erefs }
                set anchorN 0
                set root [list {}]
            } else {
                catch { unset counter(references) }
                array unset counter list/*
            }
            set elemN 0
            catch { array unset options }
            # In order to allow defaulting based on rfcedstyle,
            # "compact" and "subcompact" must not be on this list.
            # In order to allow warning about the changed default,
            # "symrefs" must not be on this list.
            array set options [list artworkdelimiter    ""            \
                                    artworklines        0             \
                                    authorship          yes           \
                                    autobreaks          yes           \
                                    background          ""            \
                                    colonspace          no            \
                                    comments            no            \
                                    docmapping          no            \
                                    editing             no            \
                                    emoticonic          no            \
                                    footer              ""            \
                                    header              ""            \
                                    inline              no            \
                                    iprnotified         no            \
                                    linkmailto          yes           \
                                    notedraftinprogress yes           \
                                    private             ""            \
                                    refparent           "References"  \
                                    rfcedstyle          no            \
                                    rfcprocack          no            \
                                    slides              no            \
                                    sortrefs            no            \
                                    strict              no            \
                                    toc                 no            \
                                    tocappendix         yes           \
                                    tocdepth            3             \
                                    tocindent           yes           \
                                    tocnarrow           yes           \
                                    tocompact           yes           \
                                    topblock            yes           \
                                    useobject           no]
            normalize_options
            set stack 0; unset stack
            linefile::init
        }
        end {
            set elemZ $elemN
            if {$passno == 1} {
                # We can only see line numbers from the preprocessed XML.
                # linefile::get_line won't work once we hit the first include.
                linefile::init
                linefile::set_file "internally-preprocessed XML"
                xdv::validate_tree [lindex [lindex $root 0] 0] \
                     rfc2629.cmodel  rfc2629.rattrs rfc2629.oattrs \
                     rfc2629.anchors rfc2629.pcdata
            }
            if {$passno == $passmax && !$pass_was_stable} {
                incr passmax
            }
        }
    }
}
#       }}}2 Main function
#       {{{2 Some globals
global required ctexts categories
# This must be kept in lexicographical order for string compare.
set required {
               appendix   { title  }
               eref       { target }
               format     { type }
               iref       { item }
               note       { title  }
               section    { title  }
# backwards-compatibility... (the attributes are actually mandatory)
#              seriesInfo { name value }
               xref       { target }
             }
set ctexts   { area artwork city code country cref email eref facsimile
               keyword organization phone postamble preamble region seriesInfo
               spanx street t title ttcol uri workgroup xref }
#       }}}2 Some globals
#       {{{2 Categories and IPR status texts
# From the rfc-editor/instructions2authors.txt file, Appendix A, Subsection A.1.
# Currently draft-rfc-editor-rfc2223bis-08, which is expired.
# It says "This memo does not..." but the RFC Editor uses "It does not...".
# Authoritative source of "Historic" text unknown.
set categories \
             { {std  "Standards Track" STD
"This document specifies an Internet standards track protocol for the Internet
community, and requests discussion and suggestions for improvements.
Please refer to the current edition of the “Internet Official Protocol
Standards” (STD 1) for the standardization state and status of this
protocol.
Distribution of this memo is unlimited."}
               {bcp      "Best Current Practice" BCP
"This document specifies an Internet Best Current Practices for the Internet
Community, and requests discussion and suggestions for improvements.
Distribution of this memo is unlimited."}
               {info     "Informational" FYI
"This memo provides information for the Internet community.
It does not specify an Internet standard of any kind.
Distribution of this memo is unlimited."}
               {exp      "Experimental" EXP
"This memo defines an Experimental Protocol for the Internet community.
It does not specify an Internet standard of any kind.
Discussion and suggestions for improvement are requested.
Distribution of this memo is unlimited."}
               {historic "Historic" ""
"This memo describes a historic protocol for the Internet community.
It does not specify an Internet standard of any kind.
Distribution of this memo is unlimited."} }
# From
#     RFC 2026 (BCP 9)
#         ?
#     RFC 3667 (obsolete version of BCP 78)
#         Section 5.1  IPR Disclosure Acknowledgement
#         Section 5.2  Derivative Works Limitation
#             Notices a and b
#             Extracted Material appendage
#     RFC 3978 (obsolete version of BCP 78)
#         Section 5.1  IPR Disclosure Acknowledgement
#         Section 5.2  Derivative Works Limitation
#             Notices a and b
#             Extracted Material appendage
#     IETF Trust's Legal Provisions Relating to IETF Documents
#             (referred to from current version of BCP 78)
#         Section 6.a Submission Compliance
#         Section 6.c Derivative Works and Publication Limitations
#     February, 2009 update to Trust's Legal Provisions
#         trust200902 and noDerivativesTrust200902 have the same text
#         as the respective 200811 values.  noModificationTrust200902
#         is slightly modified from the 200811 wording, and
#         pre5378Trust200902 is new in this revision.
set iprstatus \
             { {full2026
"This document is an Internet-Draft and is
in full conformance with all provisions of Section 10 of RFC 2026."}
               {noDerivativeWorks2026
"This document is an Internet-Draft and is
in full conformance with all provisions of Section 10 of RFC 2026
except that the right to produce derivative works is not granted."}
               {noDerivativeWorksNow
"This document is an Internet-Draft and is
in full conformance with all provisions of Section 10 of RFC 2026
except that the right to produce derivative works is not granted.
(If this document becomes part of an IETF working group activity,
then it will be brought into full compliance with Section 10 of RFC 2026.)"}
               {none
"This document is an Internet-Draft and is
NOT offered in accordance with Section 10 of RFC 2026,
and the author does not provide the IETF with any rights other
than to publish as an Internet-Draft."}
               {full3667
"This document is an Internet-Draft and is subject to all provisions
of Section 3 of RFC 3667.
By submitting this Internet-Draft,
each author represents that any applicable patent or other IPR claims of which
he or she is aware have been or will be disclosed,
and any of which he or she become aware will be disclosed,
in accordance with RFC 3668."}
               {noModification3667
"This document is an Internet-Draft and is subject to all provisions
of Section 3 of RFC 3667.
By submitting this Internet-Draft,
each author represents that any applicable patent or other IPR claims of which
he or she is aware have been or will be disclosed,
and any of which he or she become aware will be disclosed,
in accordance with RFC 3668.
This document may not be modified,
and derivative works of it may not be created,
except to publish it as an RFC and to translate it into languages other
than English%IPREXTRACT%."}
               {noDerivatives3667
"This document is an Internet-Draft and is subject to all provisions
of Section 3 of RFC 3667 except for the right to produce derivative works.
By submitting this Internet-Draft,
each author represents that any applicable patent or other IPR claims of which
he or she is aware have been or will be disclosed,
and any of which he or she become aware will be disclosed,
in accordance with RFC 3668.
This document may not be modified,
and derivative works of it may not be created%IPREXTRACT%."}
               {full3978
"By submitting this Internet-Draft,
each author represents that any applicable patent or other IPR claims of which
he or she is aware have been or will be disclosed,
and any of which he or she becomes aware will be disclosed,
in accordance with Section 6 of BCP 79."}
               {noModification3978
"By submitting this Internet-Draft,
each author represents that any applicable patent or other IPR claims of which
he or she is aware have been or will be disclosed,
and any of which he or she becomes aware will be disclosed,
in accordance with Section 6 of BCP 79.
This document may not be modified,
and derivative works of it may not be created,
except to publish it as an RFC and to translate it into languages other
than English%IPREXTRACT%."}
               {noDerivatives3978
"By submitting this Internet-Draft,
each author represents that any applicable patent or other IPR claims of which
he or she is aware have been or will be disclosed,
and any of which he or she becomes aware will be disclosed,
in accordance with Section 6 of BCP 79.
This document may not be modified,
and derivative works of it may not be created%IPREXTRACT%."}
               {trust200811
"This Internet-Draft is submitted to IETF in full
conformance with the provisions of BCP 78 and BCP 79."}
               {noModificationTrust200811
"This Internet-Draft is submitted to IETF in full
conformance with the provisions of BCP 78 and BCP 79.
This document may not be modified, and derivative works of it may
not be created, except to format it for publication as an RFC and
to translate it into languages other than English."}
               {noDerivativesTrust200811
"This Internet-Draft is submitted to IETF in full
conformance with the provisions of BCP 78 and BCP 79.
This document may not be modified, and derivative works of it may
not be created, and it may not be published except as an Internet-Draft."}
               {trust200902
"This Internet-Draft is submitted %TOIETF% in full
conformance with the provisions of BCP 78 and BCP 79."}
               {noModificationTrust200902
"This Internet-Draft is submitted %TOIETF% in full
conformance with the provisions of BCP 78 and BCP 79.
This document may not be modified, and derivative works of it may
not be created, except to format it for publication as an RFC or
to translate it into languages other than English."}
               {noDerivativesTrust200902
"This Internet-Draft is submitted %TOIETF% in full
conformance with the provisions of BCP 78 and BCP 79.
This document may not be modified, and derivative works of it may
not be created, and it may not be published except as an Internet-Draft."}
               {pre5378Trust200902
"This Internet-Draft is submitted %TOIETF% in full
conformance with the provisions of BCP 78 and BCP 79.
This document may contain material from IETF Documents or IETF
Contributions published or made publicly available before November
10, 2008. The person(s) controlling the copyright in some of this
material may not have granted the IETF Trust the right to allow
modifications of such material outside the IETF Standards Process.
Without obtaining an adequate license from the person(s) controlling
the copyright in such materials, this document may not be modified
outside the IETF Standards Process, and derivative works of it may
not be created outside the IETF Standards Process, except to format
it for publication as an RFC or to translate it into languages other
than English."}
 }
#       }}}2 Categories and IPR status texts
#       {{{2 Start and end tag callbacks
proc begin {name {av {}} } {
    global counter depth elemN elem passno stack xref
    global anchorN
    global options
    global required ctexts categories iprstatus
    global root
    # because TclXML... quotes attribute values containing "]"
    set kv ""
    foreach {k v} $av {
        lappend kv $k
        regsub -all -- {\\\[}  $v {[} v
        regsub -all -- "\\\\{" $v "{" v
        regsub -all -- "\\\\}" $v "}" v
        lappend kv $v
    }
    set av $kv
    incr elemN
    if {$passno == 1} {
        set elem($elemN) $av
        array set attrs $av
        set attrs(.lineno) $::xdv::lineno
        lappend root [list $name [array get attrs]]
        unset attrs(.lineno)
        foreach { n a } $required {
            switch -- [string compare $n $name] {
                -1 { continue }
                0 {
                    foreach v $a {
                        if {[catch { set attrs($v) }]} {
                            unexpected error \
                                "missing $v attribute in #$elemN:<$name> element"
                        }
                    }
                    break
                }
                1 { break }
            }
        }
        switch -- [set type $name] {
            rfc {
                if {![catch { set attrs(category) }]} {
                    if {[lsearch0 $categories $attrs(category)] < 0} {
                        unexpected error \
                            "category=\"$attrs(category)\" attribute unknown in #$elemN:<rfc>"
                    }
                    if {(![string compare $attrs(category) historic]) \
                            && (![catch { set attrs(seriesNo) }])} {
                        unexpected error \
                            "historic documents have no document series in #$elemN:<rfc>"
                    }
                }
                if {![catch { set attrs(ipr) }]} {
                    #regsub -- {BCP78$} $attrs(ipr) 3978 ipr
                    if {[lsearch0 $iprstatus $attrs(ipr)] < 0} {
                        unexpected error \
                            "ipr=\"$attrs(ipr)\" attribute unknown in #$elemN:<rfc>"
                   }
                    if {   [regexp -- {[0-9]$} $attrs(ipr)]
                        && ![regexp -- {trust200902$} [string tolower $attrs(ipr)]]} {
                        unexpected warning \
                            "ipr=\"$attrs(ipr)\" attribute value is outdated compared to Trust Legal Provisions of 2/2009"
                    }
                    #if {[string compare $attrs(ipr) $ipr]} {
                    #    set attrs(ipr) $ipr
                    #    set elem($elemN) [array get attrs]
                    #}
                }
                if {![catch { set attrs(submissionType) }]} {
                    switch -- $attrs(submissionType) {
                        IETF - IRTF - IAB - independent {}
                        default {
                            unexpected error \
                                "submissionType=\"$attrs(submissionType)\" attribute unknown in #$elemN:<rfc>"
                        }
                    }
                }
                global entities oentities xentities uentities
                global prog prog_version
                if {[catch { set number $attrs(number) }]} {
                    set number XXXX
                }
                set entities  [linsert $oentities 0 {&rfc\.number;} $number]
                set xentities [linsert $xentities 0 {&rfc\.number;} $number]
                set uentities [linsert $uentities 0 {&rfc\.number;} $number]
            }
            back {
                set depth(section) 0; unset depth(section)
            }
            abstract {
                if {[lsearch0 $stack back] < 0} {
                    set counter(abstract) 1
                }
            }
            section - appendix {
                if {[lsearch0 $stack back] >= 0} {
                    set type appendix
                }
                if {![string compare $type section]} {
                    if {[catch { set depth(section) }]} {
                        set depth(section) 0
                        set counter(section) 0
                    }
                    incr depth(section)
                } else {
                    if {[catch { set depth(appendix) }]} {
                        set depth(appendix) 0
                        set counter(appendix) 0
                    }
                    incr depth(appendix)
                }
                set counter($type) \
                         [counting $counter($type) $depth($type)]
                set l [split $counter($type) .]
                if {![string compare $type appendix]} {
                    set type appendix
                    set l [lreplace $l 0 0 \
                                [string index " ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
                                    [lindex $l 0]]]
                }
                set attrs(.COUNTER) [set value [join $l .]]
                if {[catch { set attrs(anchor) }]} {
                    set attrs(anchor) anchor[incr anchorN]
                }
                set attrs(.ANCHOR) $attrs(anchor)
                if {[catch { set attrs(toc) }]} {
                    set attrs(toc) default
                }
                set elem($elemN) [array get attrs]
                switch -- [set t [string tolower $attrs(title)]] {
                    "iana considerations" - "security considerations" {
                        set counter($t) 1
                    }
                }
            }
            list {
                if {[catch { set depth(list) }]} {
                    set depth(list) 0
                    set counter(list) 0
                }
                incr depth(list)
                if {   [info exists attrs(counter)]
                    && [string compare [set c $attrs(counter)] ""]} {
                    if {![info exists counter(list/$c)]} {
                        set counter(list/$c) 0
                        set counter(list-max/$c) 0
                        set counter(list-longest-roman/$c) 1
                    }
                    set attrs(.MIN) [expr $counter(list-max/$c) + 1]
                } else {
                    set attrs(.MIN) 1
                }
                set attrs(.MAX) 0
                set attrs(.LONGEST_ROMAN) 1
                set elem($elemN) [array get attrs]
            }
            t {
                if {[catch { set counter(editno) }]} {
                    set counter(editno) 0
                }
                incr counter(editno)
                set attrs(.EDITNO) $counter(editno)
                if {[set l [llast0 $stack list]] >= 0} {
                    set counter(list) [counting $counter(list) $depth(list)]
                    set attrs(.COUNTER) $counter(list)
                    set value $attrs(.COUNTER)
                    set le [lindex [lindex $stack $l] 2]
                    array set lv $elem($le)
                    if {   [info exists lv(counter)]
                        && [string compare [set c $lv(counter)] ""]} {
                        set x [incr counter(list/$c)]
                        set z 1
                    } else {
                        set x [lindex [split $attrs(.COUNTER) .] end]
                        set z 0
                    }
                    set attrs(.FMTCOUNTER) $x
                    # Also update counter(list*/$c) values now, not in end,
                    # in case someone decides to reuse the $c counter
                    # in an inner list (which would be weird, but hey).
                    if {$x > $lv(.MAX)} {
                        set lv(.MAX) $x
                        if {$z} {
                            if {$x > $counter(list-max/$c)} {
                                set counter(list-max/$c) $x
                            }
                        }
                    }
                    set y $lv(.LONGEST_ROMAN)
                    if {   $x != $y
                        && [string length [offset2romans $x]] >
                           [string length [offset2romans $y]]} {
                        set lv(.LONGEST_ROMAN) $x
                        if {$z} {
                            set y $counter(list-longest-roman/$c)
                            if {   $x != $y
                                && [string length [offset2romans $x]] >
                                   [string length [offset2romans $y]]} {
                                set counter(list-longest-roman/$c) $x
                            }
                        }
                    }
                    set elem($le) [array get lv]
                } else {
                    set frame [lindex $stack end]
                    set value 1
                    foreach child [lindex $frame 4] {
                        array set c $elem($child)
                        if {![string compare $c(.NAME) t]} {
                            incr value
                        }
                    }
                }
                set elem($elemN) [array get attrs]
            }
            figure {
                if {[info exists attrs(anchor)]} {
                    if {[catch { set counter(figure) }]} {
                        set counter(figure) 0
                    }
                    incr counter(figure)
                    set attrs(.COUNTER) [set value $counter(figure)]
                    set elem($elemN) [array get attrs]
                }
            }
            preamble - postamble {
                if {[catch { set counter(editno) }]} {
                    set counter(editno) 0
                }
                incr counter(editno)
                set attrs(.EDITNO) $counter(editno)
                set elem($elemN) [array get attrs]
            }
            texttable {
                if {[info exists attrs(anchor)]} {
                    if {[catch { set counter(table) }]} {
                        set counter(table) 0
                    }
                    incr counter(table)
                    set attrs(.COUNTER) [set value $counter(table)]
                    set elem($elemN) [array get attrs]
                }
            }
            references {
                if {[catch { set depth(references) }]} {
                    set depth(references) 0
                    if {[catch { set counter(section) }]} {
                        set counter(section) 0
                    }
                    set counter(section) [counting $counter(section) 1]
                }
                incr depth(references)
                set counter(section) [counting $counter(section) 2]
                set l [split $counter(section) .]
                set attrs(.COUNTER) [set value [join $l .]]
                if {[catch { set attrs(anchor) }]} {
                    set attrs(anchor) anchor[incr anchorN]
                }
                set attrs(.ANCHOR) $attrs(anchor)
                if {[catch { set attrs(toc) }]} {
                    set attrs(toc) default
                }
                set elem($elemN) [array get attrs]
                if {[info exists attrs(title)]} {
                    switch -- [set t [string tolower $attrs(title)]] {
                        "normative reference" - "normative references" {
                            set counter(normative) 1
                        }
                        "informative reference" - "informative references" {
                            set counter(informative) 1
                        }
                    }
                }
            }
            reference {
                if {$options(.SYMREFS)} {
                    if {![info exists attrs(anchor)]} {
                        unexpected error "anchor required when using symrefs"
                    }
                    set value $attrs(anchor)
                } else {
                    if {[catch { set counter(reference) }]} {
                        set counter(reference) 0
                    }
                    incr counter(reference)
                    set value $counter(reference)
                }
                set attrs(.COUNTER) $value
                set elem($elemN) [array get attrs]
            }
            eref {
                if {($options(.STRICT)) && ([lsearch0 $stack abstract] >= 0)} {
                    unexpected error "eref element in abstract"
                }
            }
            xref {
                if {($options(.STRICT)) && ([lsearch0 $stack abstract] >= 0)} {
                    unexpected error "xref element in abstract"
                }
                set target $attrs(target)
                if {(![info exists counter(firstxref)]) \
                        || [lsearch -exact $counter(firstxref) $target] < 0} {
                    lappend counter(firstxref) $target
                }
            }
            cref {
                if {[catch { set attrs(anchor) }]} {
                    set attrs(anchor) anchor[incr anchorN]
                }
                if {$options(.SYMREFS)} {
                    set value $attrs(anchor)
                } else {
                    if {[catch { set counter(comment) }]} {
                        set counter(comment) 0
                    }
                    incr counter(comment)
                    set value Comment.$counter(comment)
                }
                set attrs(.COUNTER) $value
                set elem($elemN) [array get attrs]
            }
        }
        if {![catch { set anchor $attrs(anchor) }]} {
            if {![catch { set xref($anchor) }]} {
                array set x $xref($anchor)
                unexpected error \
  "anchor=\"$anchor\" attribute currently points to #$x(elemN):<$x(type)> and cannot be redefined in new #$elemN:<$name>"
            }
            set xref($anchor) [list type $type elemN $elemN value $value]
        }
        if {$elemN > 1} {
            set frame [lindex $stack end]
            set children [lindex $frame 4]
            lappend children $elemN
            set frame [lreplace $frame 4 4 $children]
            set stack [lreplace $stack end end $frame]
        }
    } else {
        # passno > 1
        if {0 && (![string compare $passno/$name 2/eref])} {
            array set attrs $elem($elemN)
            if {[catch { set counter(reference) }]} {
                set counter(reference) 0
            }
            incr counter(reference)
            set attrs(.COUNTER) $counter(reference)
            set elem($elemN) [array get attrs]
        }
        switch -- $name {
            rfc - reference - annotation {
                pass2begin_$name $elemN
            }
            front - abstract - note - section - appendix - t - list
                  - figure - artwork - preamble - postamble
                  - texttable - ttcol - c - iref - vspace - back {
                if {[lsearch0 $stack references] < 0} {
                    pass2begin_$name $elemN
                }
            }
            xref - eref - cref - spanx {
                if {([lsearch0 $stack references] < 0) \
                        || ([lsearch0 $stack annotation] >= 0)} {
                    pass2begin_$name $elemN
                }
            }
        }
    }
    if {[lsearch -exact $ctexts $name] >= 0} {
        set ctext yes
        if {$passno == 1} {
            set attrs(.CTEXT) ""
            set elem($elemN) [array get attrs]
        }
    } else {
        set ctext no
    }
    lappend stack [list $name elemN $elemN children "" ctext $ctext av $av \
                        line [linefile::get_line] \
                        fnum [linefile::get_fake_fnum]]
}
proc counting {tcount tdepth} {
    set x [llength [set l [split $tcount .]]]
    if {$x > $tdepth} {
        set l [lrange $l 0 [expr $tdepth-1]]
        set x $tdepth
    } elseif {$x < $tdepth} {
        lappend l 0
        incr x
    }
    incr x -1
    set l [lreplace $l $x $x [expr [lindex $l $x]+1]]
    return [join $l .]
}
# end element
proc end {name} {
    global counter depth elem passno stack xref
    global root
    set frame [lindex $stack end]
    set stack [lreplace $stack end end]
    array set av [lrange $frame 1 end]
    set elemX $av(elemN)
    if {$passno == 1} {
        set f2 [lindex $root end]
        set root [lreplace $root end end]
        set parent [lindex $root end]
        lappend parent $f2
        set root [lreplace $root end end $parent]
        array set attrs $elem($elemX)
        set attrs(.CHILDREN) $av(children)
        set attrs(.NAME) $name
        set elem($elemX) [array get attrs]
        switch -- $name {
            section - appendix {
                if {[lsearch0 $stack back] >= 0} {
                    set name appendix
                }
                incr depth($name) -1
            }
            list {
                if {[incr depth(list) -1] == 0} {
                    set counter(list) 0
                }
            }
            back {
                if {[llength [set c [find_element references \
                                                     $attrs(.CHILDREN)]]] \
                        == 1} {
                    array set cv $elem($c)
                    set cv(.COUNTER) [lindex [split $cv(.COUNTER) .] 0]
                    set elem($c) [array get cv]
                }
            }
        }
        return
    }
    # passno > 1
    switch -- $name {
        rfc - front - t - list - figure - artwork
            - preamble - postamble - texttable - c - back {
            if {[lsearch0 $stack references] < 0} {
                pass2end_$name $elemX
            }
        }
        references - annotation {
            pass2end_$name $elemX
        }
    }
}
#       }}}2 Start and end tag callbacks
#       {{{2 Character data (PCDATA) callback
proc pcdata {text} {
    global depth elem passno stack xref
    global mode
    global root
    global page_width page_basic_indent
    if {[string length $text] <= 0} {
        # Really empty.
        return
    }
    set chars [string trim $text]
    set text [str_norm_eol $text]
    set frame [lindex $stack end]
    set spans {}
    set divs  {}
    if {([lsearch0 $stack references] >= 0) \
            && ([lsearch0 $stack annotation] < 0)} {
        set pre -1
    } else {
        switch -- [lindex $frame 0] {
            artwork {
                if {$passno == 1} {
                    set pre 1
                } else {
                    # Will end up positive by incrementation and checks.
                    set pre [current_align_bias]
                    set elemX [lindex $frame 2]
                    # It won't work to get attrs from $frame.
                    array set attrs $elem($elemX)
                    if {[info exists attrs(.TEXTWIDTH)]} {
                        set align [current_align]
                        set tw $attrs(.TEXTWIDTH)
                        set rw [expr $page_width - $page_basic_indent - $tw]
                        switch -- $align {
                            left - "" {}
                            center { incr pre [expr ($rw + 1) / 2] }
                            right  { incr pre [expr $rw] }
                            default {
                                unexpected error \
                                    "align=\"$align\" attribute is invalid"
                            }
                        }
                        if {$pre > $rw} {
                            set pre $rw
                        }
                        switch -- $align {
                            center - right {
                                if {$pre < 0} {
                                    set pre 0
                                }
                            }
                        }
                    }
                    if {$pre < [current_align_bias]} {
                        unexpected warning "artwork outdented [expr [current_align_bias] - $pre] characters to avoid overrunning right margin"
                    }
                    incr pre $page_basic_indent
                    if {$pre < 0} {
                        set pre 0
                    }
                    # pre = 1 + total indent
                    incr pre
                    # Typed-<artwork> validation.
                    set type ""
                    catch { set type $attrs(type) }
                    if {[info exists attrs(.VALID)]} {
                        set valid $attrs(.VALID)
                        catch { set spans $attrs(.SPANS) }
                        catch { set divs  $attrs(.DIVS)  }
                        catch { set data  $attrs(.SDATA) }
                    } else {
                        set data [ent_expand $text]
                        foreach {valid spans divs} [ \
                            artwork::validate_highlight $type $data \
                        ] {break}
                        set attrs(.VALID) $valid
                        if {[llength $spans] > 0 || [llength $divs] > 0} {
                            set attrs(.SPANS) $spans
                            set attrs(.DIVS)  $divs
                            set attrs(.SDATA) $data
                        }
                        set elem($elemX) [array get attrs]
                    }
                }
            }
            t - preamble - postamble - c - annotation {
                set pre 0
            }
            default {
                set pre -1
            }
        }
    }
    if {$passno == 1} {
        if {$pre < 0 && [string length $chars] <= 0} {
            # Just white space.  Pass 1 doesn't want to see
            # PCDATA in the wrong places, but further passes
            # *need* some among it to generate correct output.
            return
        }
        array set attrs [lindex [set f2 [lindex $root end]] 1]
        set attrs(.pcdata) 1
        set root [lreplace $root end end \
                           [lreplace $f2 1 1 [array get attrs]]]
        catch { array unset attrs }
        array set av [lrange $frame 1 end]
        set elemX $av(elemN)
        array set attrs $elem($elemX)
        if {![string compare $av(ctext) yes]} {
            if {[lsearch0 $stack spanx] < 0} {
                append attrs(.CTEXT) $chars
            } else {
                append attrs(.CTEXT) $text
            }
        }
        set elem($elemX) [array get attrs]
        return
    }
    if {$pre < 0} {
        return
    }
    if {[info exists data] && ([llength $spans] > 0 || [llength $divs] > 0)} {
        set text $data
    }
    pcdata_$mode $text $pre 0 $spans $divs
    # Complain after having generated the output in case of hard error.
    if {[info exists valid] && !$valid} {
        if {[info exists spans]} {
            set x 0
            set p 0
            set l 0
            while {[set x [lsearch0 $spans err $x]] >= 0} {
                set i [lindex [lindex $spans $x] 1]
                # This line number will be 0-based,
                # but most people start their <artwork>
                # with a blank line (this being XML, not SGML).
                incr l [num_eols [string range $data $p [expr $i - 1]]]
                set p $i
                regexp -start $i -- {[^\n]*} $data token
                regsub -all -- \" $token {\"} token
                unexpected [unex_condtype] \
  "content is not valid type=\"$type\" near \"$token\" at line-offset $l within <artwork>"
                incr x
            }
        } else {
            unexpected [unex_condtype] \
                "<artwork> content is not valid type=\"$type\""
        }
    }
}
#       }}}2 Character data (PCDATA) callback
#       {{{2 Processing instructions (PIs)
proc pi {args} {
    global options
    global passno stack
    global mode
    switch -- [lindex $args 0]/[llength $args] {
        xml/2 {
            if {([string first "version=\"1.0\"" [lindex $args 1]] < 0) \
                    && ([string first "version='1.0'" [lindex $args 1]] < 0)} {
                unexpected error "unexpected <?xml ...?>"
            }
        }
        rfc/2 {
            set n 0
            set text [lindex $args 1]
            set lines [num_eols $text]
            while {1} {
                set l [pi_rfc_next $text]
                set key  [lindex $l 0]
                set val  [lindex $l 1]
                set text [lindex $l 2]
                if {![string compare $key ""]} {
                    if {[string compare $val ""]} {
                        unexpected error \
                            "stopped processing faulty rfc-PI at \"$val\""
                    }
                    break
                }
                switch -- $key {
                    include { continue }
                    linefile {
                        if {![regexp -- {^([0-9]+)(:(.*))?$} \
                                     $val a b c d]} {
                            unexpected warning \
  "ignoring invalid rfc-PI linefile-directive value \"$val\""
                            continue
                        }
                        if {[string length $c]} {
                            # May be empty.  User's choice!
                            set new_file $d
                        }
                        set new_line $b
                        continue
                    }
                }
                if {   [info exists options($key)]
                    || (   [string is lower $key]
                        && [info exists options(.[string toupper $key])])} {
                    set options($key) $val
                    incr n
                } elseif {$passno > 1} {
                    if {([catch { pi_$mode $key $val }]) && ($options(.STRICT))} {
                        regsub -all -- \" $val {\"} val
                        unexpected error \
                            "invalid rfc-PI directive: $key=\"$val\""
                    }
                }
            }
            if {$n > 0} {
                normalize_options
            }
            # Do this at the end so that intermixed
            # error or warning messages are not affected.
            if {[info exists new_line]} {
                if {[info exists new_file]} {
                    linefile::set_file $new_file
                }
                linefile::set_line [expr $new_line - $lines]
            }
        }
        default {
            if {![string compare [lindex $args 0] xml-stylesheet]} {
                return
            }
            set text [string trim [join $args " "]]
            unexpected warning "unknown PI: $text"
        }
    }
}
proc pi_rfc_next {text} {
    set text [string trimleft $text]
    set key ""
    set val $text
    # Some useful regexp literals.
    set wsp  {[ \t\r\n]}
    set dqev \"(\[^\"\]*)\"
    set sqev \'(\[^\'\]*)\'
    set nme  {([A-Za-z_:][A-Za-z0-9._:-]*)}
    set rem  (.*)
    if {   [regexp -- ^$nme=$dqev$rem$ $text x k v rest]
        || [regexp -- ^$nme=$sqev$rem$ $text x k v rest]
        || [regexp -- ^$nme=${nme}($|$wsp)$rem$ $text x k v y rest]} {
        set key $k
        set val [chars_expand $v]
        set text [string trimleft $rest]
    }
    return [list $key $val $text]
}
#       }}}2 Processing instructions (PIs)
#       {{{2 Options (rfc-PI directives) processing
proc normalize_options {} {
    global passmax
    global options
    global mode
    global remoteP
    if {$remoteP} {
        set options(slides) no
    }
    foreach {o O} [list authorship          .AUTHORSHIP           \
                        autobreaks          .AUTOBREAKS           \
                        colonspace          .COLONSPACE           \
                        comments            .COMMENTS             \
                        compact             .COMPACT              \
                        docmapping          .DOCMAPPING           \
                        editing             .EDITING              \
                        emoticonic          .EMOTICONIC           \
                        inline              .INLINE               \
                        iprnotified         .IPRNOTIFIED          \
                        linkmailto          .LINKMAILTO           \
                        notedraftinprogress .NOTEDRAFTINPROGRESS  \
                        rfcedstyle          .RFCEDSTYLE           \
                        rfcprocack          .RFCPROCACK           \
                        slides              .SLIDES               \
                        sortrefs            .SORTREFS             \
                        strict              .STRICT               \
                        subcompact          .SUBCOMPACT           \
                        symrefs             .SYMREFS              \
                        toc                 .TOC                  \
                        tocappendix         .TOCAPPENDIX          \
                        tocindent           .TOCINDENT            \
                        tocnarrow           .TOCNARROW            \
                        tocompact           .TOCOMPACT            \
                        topblock            .TOPBLOCK             \
                        useobject           .USEOBJECT]          {
        if {![info exists options($o)]} {
            continue
        }
        switch -- $options($o) {
            yes - true - 1 {
                set options($O) 1
            }
            default {
                set options($O) 0
            }
        }
    }
    foreach {o O} [list artworklines .ARTWORKLINES \
                        tocdepth     .TOCDEPTH] {
        if {[catch { incr options($o) 0 }]} {
            unexpected error "invalid $o value '$options($o)'"
        }
        set options($O) $options($o)
    }
    foreach {o O} [list footer  .FOOTER \
                        header  .HEADER  \
                        private .PRIVATE] {
        set options($O) 0
        if {[string compare $options($o) ""]} {
            set options($O) 1
        }
    }
    switch -- $mode {
        nr - txt {
            set options(.SLIDES) 0
            # needed for annotations with mark-up to work correctly...
            set passmax 3
        }
        html {
            if {$options(.SLIDES)} {
                set options(.TOC) 0
            }
            if {$options(.SLIDES)} {
                set passmax 3
            }
        }
    }
    if {!$options(.COMMENTS)} {
        set options(.INLINE) 0
    }
    if {![info exists options(symrefs)]} {
        # 2 triggers warning of changed default
        set options(.SYMREFS) 2
    }
    if {![info exists options(compact)]} {
        set options(.COMPACT) $options(.RFCEDSTYLE)
    }
    if {![info exists options(subcompact)]} {
        if {$options(.RFCEDSTYLE)} {
            set options(.SUBCOMPACT) 0
        } else {
            set options(.SUBCOMPACT) $options(.COMPACT)
        }
    }
    if {$options(.PRIVATE)} {
        set options(.HEADER) 1
        set options(.FOOTER) 1
    }
    if {$options(.DOCMAPPING)} {
        set options(.TOPTAG) "h1"
    } else {
        set options(.TOPTAG) "h3"
    }
}
#       }}}2 Options (rfc-PI directives) processing
#       {{{2 XML and DTD declaration callbacks
proc xmldecl {version encoding standalone} {
    if {[string compare $version 1.0]} {
        unexpected error "invalid XML version: $version"
    }
}
proc doctype {element public system internal} {
    global stack
    global intentities extentities
    if {[info exists stack]} {
        return
    }
    if {   [string compare $element rfc]
        || (   [string compare $public ""]
            && ![regexp -- {-//IETF//DTD RFC 2629.*//EN} $public])
        || ![regexp -- {^(|.*/)rfc.*\.dtd$} $system]} {
        unexpected error "invalid DOCTYPE: $element+$public+$system+$internal"
    }
    for {set start 0} \
        {[regexp -indices -start $start -- \
          {<!-- xml2rfc-processed-entity ([A-Za-z_:][A-Za-z0-9._:-]*) -->} \
          $internal x entity]} \
        {set start $b} {
        set a [lindex $x 0]
        set b [lindex $x 1]
        set ea [lindex $entity 0]
        set eb [lindex $entity 1]
        set entity_proper([string range $internal $ea $eb]) 1
    }
    foreach e {int ext} {
        foreach entity [array names ${e}entities] {
            if {![info exists entity_proper($entity)]} {
                unexpected warning \
                    "${e}ernal entity $entity defined outside DOCTYPE, so is invalid XML"
            }
        }
    }
}
#       }}}2 XML and DTD declaration callbacks
#       {{{2 The unexpected (error printing)
global already_warned
catch { array unset already_warned }
proc unex_init {} {
    global already_warned
    catch { array unset already_warned }
}
proc unexpected {args} {
    global prog
    global guiP
    set text [join [lrange $args 1 end] " "]
    switch -- [set type [lindex $args 0]] {
        error {
            global errorP
            set errorP 1
            if {$guiP != 1} {
                set text "$prog: error: $text"
            }
            return -code error $text
        }
        notice {
            if {$guiP == -1} {
                puts stdout $text
            }
        }
        default {
            global already_warned
            append text [around2fl ""]
            if {[info exists already_warned($text)]} {
                return
            }
            set already_warned($text) 1
            #append text [around2fl ""]
            switch -- $guiP {
                1 { tk_dialog .unexpected "$prog: $type" $text $type 0 OK }
                0 {
                    global env
                    if {[llength [array names env REQUEST_METHOD]] <= 0} {
                        # Not under CGI.
                        puts stderr "$prog: $type: $text"
                    } else {
                        lappend xml2rfc_warnings "$prog: $type: $text"
                    }
                }
                -1 { puts stdout "$type: $text" }
            }
        }
    }
}
proc unex_condtype {} {
    global options
    if {$options(.STRICT)} {
        return error
    } else {
        return warning
    }
}
#       }}}2 The unexpected (error printing)
#       {{{2 Other IPR texts
global validity1 validity2
# From RFC 3978 (BCP 78), Section 5.5.
set validity1 {
"This document and the information contained herein are provided
on an “AS IS” basis and THE CONTRIBUTOR,
THE ORGANIZATION HE/SHE REPRESENTS OR IS SPONSORED BY (IF ANY),
THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE DISCLAIM
ALL WARRANTIES,
EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE
INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED
WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE."
}
# draft-ietf-ipr-ietf-trust-update to validity1
set validity2 {
"This document and the information contained herein are provided
on an “AS IS” basis and THE CONTRIBUTOR,
THE ORGANIZATION HE/SHE REPRESENTS
OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY, THE IETF TRUST
AND THE INTERNET ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT
THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY
IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR
PURPOSE."
}
global copylong1 copylong2 copylong3 copylong4 copylong5 copyurl
# From RFC 2026 (BCP 9), Section 10.4, Notice C;
# Section 10 is now replaced by BCPs 78 and 79.
set copylong1 {
"Copyright © The Internet Society (%YEAR%). All Rights Reserved."
"This document and translations of it may be copied and furnished to
others, and derivative works that comment on or otherwise explain it
or assist in its implementation may be prepared, copied, published and
distributed, in whole or in part, without restriction of any kind,
provided that the above copyright notice and this paragraph are
included on all such copies and derivative works. However, this
document itself may not be modified in any way, such as by removing
the copyright notice or references to the Internet Society or other
Internet organizations, except as needed for the purpose of
developing Internet standards in which case the procedures for
copyrights defined in the Internet Standards process must be
followed, or as required to translate it into languages other than
English."
"The limited permissions granted above are perpetual and will not be
revoked by the Internet Society or its successors or assigns."
"This document and the information contained herein is provided on an
“AS IS” basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE."
}
# From RFC 3978 (BCP 78), Section 5.4.
# For independent submissions, as opposed to IETF ones,
# there is an additional " and at www.rfc-editor.org/copyright.html"
# right after "BCP 78";
# this additional text is at the RFC Editor's discretion.
# <ftp://ftp.isi.edu/in-notes/rfc-editor/boilerplate.ietfsub.1Mar05.txt>
# <ftp://ftp.isi.edu/in-notes/authors/lastpage.ietfsub.nroff>
set copylong2 {
"Copyright © The Internet Society (%YEAR%)."
"This document is subject to the rights,
licenses and restrictions contained in BCP 78,
and except as set forth therein,
the authors retain all their rights."
}
# <ftp://ftp.isi.edu/in-notes/rfc-editor/boilerplate.indsub.1Mar05.txt>
# <ftp://ftp.isi.edu/in-notes/authors/lastpage.indsub.nroff>
set copylong3 {
"Copyright © The Internet Society (%YEAR%)."
"This document is subject to the rights,
licenses and restrictions contained in BCP 78
and at %COPYURL%, and except as set forth therein,
the authors retain all their rights."
}
# RFC 4748 modification to copylong2
set copylong4 {
"Copyright © The IETF Trust (%YEAR%)."
"This document is subject to the rights,
licenses and restrictions contained in BCP 78,
and except as set forth therein,
the authors retain all their rights."
}
# RFC 4748 modification to copylong3
set copylong5 {
"Copyright © The IETF Trust (%YEAR%)."
"This document is subject to the rights,
licenses and restrictions contained in BCP 78
and at %COPYURL%, and except as set forth therein,
the authors retain all their rights."
}
set copyurl "http://www.rfc-editor.org/copyright.html"
global iprlong1 iprlong2 iprurl ipremail
set iprurl "http://www.ietf.org/ipr"
set ipremail "ietf-ipr@ietf.org"
# From RFC 2026 (BCP 9), Section 10.4, Notices A and B;
# Section 10 is now replaced by BCPs 78 and 79.
set iprlong1 {
"The IETF takes no position regarding the validity or scope of
any intellectual property or other rights that might be claimed
to  pertain to the implementation or use of the technology
described in this document or the extent to which any license
under such rights might or might not be available; neither does
it represent that it has made any effort to identify any such
rights. Information on the IETF's procedures with respect to
rights in standards-track and standards-related documentation
can be found in BCP 11. Copies of claims of rights made
available for publication and any assurances of licenses to
be made available, or the result of an attempt made
to obtain a general license or permission for the use of such
proprietary rights by implementors or users of this
specification can be obtained from the IETF Secretariat."
"The IETF invites any interested party to bring to its
attention any copyrights, patents or patent applications, or
other proprietary rights which may cover technology that may be
required to practice this standard. Please address the
information to the IETF Executive Director."
}
# From RFC 3979 (BCP 79), Section 5.
set iprlong2 {
"The IETF takes no position regarding the validity or scope of any
Intellectual Property Rights or other rights that might be claimed
to pertain to the implementation or use of the technology
described in this document or the extent to which any license
under such rights might or might not be available; nor does it
represent that it has made any independent effort to identify any
such rights.
Information on the procedures with respect to
rights in RFC documents can be found in BCP 78 and BCP 79."
"Copies of IPR disclosures made to the IETF Secretariat and any
assurances of licenses to be made available,
or the result of an attempt made to obtain a general license or
permission for the use of such proprietary rights by implementers or
users of this specification can be obtained from the IETF on-line IPR
repository at %IPRURL%."
"The IETF invites any interested party to bring to its attention
any copyrights,
patents or patent applications,
or other
proprietary rights that may cover technology that may be required
to implement this standard.
Please address the information to the IETF at %IPREMAIL%."
}
global iprextra
# From RFC 2026 (BCP 9), Section 10.4, Notice D;
# Section 10 is now replaced by BCPs 78 and 79,
# which don't feature such text.
set iprextra {
"The IETF has been notified of intellectual property rights
claimed in regard to some or all of the specification contained
in this document. For more information consult the online list
of claimed rights."
}
global funding funding1 funding2
# Appears in all rfc-editor/boilerplate*.txt files.
# Something the RFC Editor adds at his/her discretion.
# (Authoritative) source:  this email
#     From: Brian E Carpenter <brian@hursley.ibm.com>
#     Organization: IBM Internet Division
#     To: jkrey@ISI.EDU
#     CC: iab@ISI.EDU, iesg@ISI.EDU, rfc-ed@ISI.EDU
#     Subject: Re: RFC Editor Contract signed...
#     ...
#     Secondly, I don't think this is such a big deal, but let's
#     deem that the conclusion of the discussion is to put this
#     small acknowledgment at the end rather than at the beginning.
#
# The RFC Editor stopped adding this boilerplate as of
# 21 August 2007.  See http://www.rfc-editor.org/news.html .
set funding1 \
"Funding for the RFC Editor function is currently provided by
the Internet Society."
set funding2 \
"Funding for the RFC Editor function is provided by
the IETF Administrative Support Activity (IASA)."
# get the publication date in seconds; returns 0 when not available
proc get_publication_date_seconds {date} {
    global elem
    array set dv $elem($date)
    set three [clock format [clock seconds] -format "%B %Y %d"]
    if {[catch { set dv(year) }]} {
        set dv(year) [lindex $three 1]
    }
    if {[catch { set dv(month) }]} {
        if {(![string compare $dv(year) [lindex $three 1]])} {
            set dv(month) [lindex $three 0]
            set dv(day) [string trimleft [lindex $three 2] 0]
        } else {
            unexpected error "I can't synthesize a date in $dv(year)"
        }
    } elseif {[catch { set dv(day) }]} {
        if {(![string compare $dv(month) [lindex $three 0]]) \
                && (![string compare $dv(year) [lindex $three 1]])} {
            set dv(day) [string trimleft [lindex $three 2] 0]
        }
    }
    set elem($date) [array get dv]
    
    if {[catch { set day $dv(day) }]} {
        set day 1
    }
    if {[catch {set secs [clock scan "$dv(month) $day, $dv(year)" -gmt true]}]} {
        set secs 0
    }
    
    return $secs
}
#       }}}2 Other IPR texts
#       {{{2 Pass 2 (and subsequent) stuff for the whole document
proc pass2begin_rfc {elemX} {
    global counter elem passno xref
    global options copyrightP iprP
    global copyshort copyshort1 copyshort2 copyshort3 copyshortTrust200811 \
           copyshortTrust200909 copyshortTrust200902 \
           codeComponents200909 pre5378escapeClause
    global funding funding1 funding2
    global backP
    set backP 0
    array set attrs [list number     ""   obsoletes      ""   updates   "" \
                          seriesNo   ""   ipr            "" \
                          iprExtract ""   submissionType IETF xml:lang  en]
    array set attrs $elem($elemX)
    set elem($elemX) [array get attrs]
    set front [find_element front $attrs(.CHILDREN)]
    array set fv $elem($front)
    if {(!$options(.PRIVATE)) \
            && (![string compare $attrs(number) ""]) \
            && (![string compare $attrs(ipr) ""])} {
        unexpected error \
                   "rfc element needs either a number or an ipr attribute"
    }
    if {![string compare $attrs(ipr) none]} {
        set copyrightP 0
    } else {
        set copyrightP 1
        set iprP 1
    }
    set newP 9
    if {![info exists fv(.PARSEDDATE)]} {
        set date [find_element date $fv(.CHILDREN)]
        set secs [get_publication_date_seconds $date]
        set fv(.PARSEDDATE) $secs
        set elem($front) [array get fv]
    }
    if {[catch { clock format $fv(.PARSEDDATE) -format "%Y%m%d" -gmt true } \
               ymd]} {
        # Should differentiate between PARSEDATE not set (e.g., early pass)
        # vs. PARSEDATE set to 0 (i.e., couldn't parse date)
        set ymd ""
    }
    
    if {[string compare $attrs(number) ""]} {
        if {$attrs(number) <= 2499} {
            set newP 0
        } elseif {$attrs(number) <= 3707} {
            set newP 1
        } elseif {$attrs(number) <= 4321} {
            set newP 2
        } elseif {$attrs(number) <= 4671} {
            # 4671 is a guess
            set newP 3
        } elseif {($attrs(number) < 5000) ||
            ([lsearch {5020 5021 5034 5052 5065 5094} $attrs(number)] > -1)} {
            set newP 4
        } elseif {$ymd < "20081101"} {
            set newP 5
        } elseif {$ymd < "20090201"} {
            set newP 6
        } elseif {$ymd < "20090901" ||
            ([lsearch {5582 5621 5632 5645 5646 5681} $attrs(number)] > -1)} {
            # TLP 2009 09 copyright notice beginning with Sep 2009, except
            # for the RFCs listed above
            set newP 7
        } elseif {$ymd < "20100101"} {
            set newP 8
        }
    } elseif {[string compare $attrs(ipr) ""]} {
        if {   [string first "3667" $attrs(ipr)] >= 0
            || [string first "3978" $attrs(ipr)] >= 0} {
            set newP 5
        } elseif {[string first "trust" [string tolower $attrs(ipr)]] < 0} {
            set newP 1
        } elseif {$ymd < "20091101"} {
            # TLP 2009 09 copyright notice beginning with Nov 2009
            set newP 7
        } elseif {$ymd < "20100401"} {
            # TLP 2010 01 copyright notice beginning with Apr 2010
            set newP 8
        }
        # note: no support for 2008 11 TLP text in IDs
    }
    if {$newP == 9} {
        set copyshort $copyshortTrust200909
        if {![catch { set attrs(submissionType) }]} {
          switch -- $attrs(submissionType) {
            IETF {
              regsub -all -- %CODECOMPONENTS% $copyshort $codeComponents200909 copyshort
              # in the code components statement, say "Simplied BSD License"
              regsub -all -- %SIMPLIFIED% $copyshort "Simplified " copyshort
            }
            default {
              regsub -all -- %CODECOMPONENTS% $copyshort "" copyshort
            }
          }
        }
          
        # RFCs: include escape clause in Copyright Notice
        # IDs: include in Status Of This Memo (produced elsewhere), for date before Nov 2009
        if {![string compare $attrs(ipr) "pre5378Trust200902"] && \
            ([string compare $attrs(number) ""] || $ymd >= "20091101")} {
            lappend copyshort $pre5378escapeClause
        }
        set funding ""
        set copyrightP -1
        set iprP 0
    } elseif {$newP == 8} {
        set copyshort $copyshortTrust200909
        # pre-201004: append code component clause unconditionally
        regsub -all -- %CODECOMPONENTS% $copyshort $codeComponents200909 copyshort
        # in the code components statement, say "BSD License"
        regsub -all -- %SIMPLIFIED% $copyshort "" copyshort
          
        # RFCs: include escape clause in Copyright Notice
        # IDs: include in Status Of This Memo (produced elsewhere), for date before Nov 2009
        if {![string compare $attrs(ipr) "pre5378Trust200902"] && \
            ([string compare $attrs(number) ""] || $ymd >= "20091101")} {
            lappend copyshort $pre5378escapeClause
        }
        set funding ""
        set copyrightP -1
        set iprP 0
    } elseif {$newP == 7} {
        set copyshort $copyshortTrust200902
        # RFCs: include escape clause in Copyright Notice
        # IDs: include in Status Of This Memo (produced elsewhere)
        if {![string compare $attrs(ipr) "pre5378Trust200902"] && \
            [string compare $attrs(number) ""]} {
            lappend copyshort $pre5378escapeClause
        }
        set funding ""
        set copyrightP -1
        set iprP 0
    } elseif {$newP == 6} {
        set copyshort $copyshortTrust200811
        set funding ""
        set copyrightP -1
        set iprP 0
    } elseif {$newP == 5} {
        set copyshort ""
        set funding ""
    } elseif {$newP == 4} {
        set copyshort $copyshort3
        set funding $funding2
    } elseif {$newP == 3} {
        set copyshort $copyshort2
        set funding $funding2
    } elseif {$newP == 2} {
        set copyshort $copyshort2
        set funding $funding1
    } elseif {$newP == 1} {
        set copyshort $copyshort1
        set funding $funding1
    } else {
        set copyshort $copyshort1
        set funding ""
    }
    if {   $passno == 2
        && [info exists counter(firstxref)]
        && [llength [set back [find_element back $attrs(.CHILDREN)]]] == 1} {
        set warnonly [expr !$options(.SORTREFS) || $options(.SYMREFS)]
        catch { array unset bv }
        array set bv $elem($back)
        set firstxref [list ""]
        foreach target $counter(firstxref) {
            if {   ![catch { array set av $xref($target) }]
                && ![string compare $av(type) reference]} {
                lappend firstxref $target
            }
        }
        set offset 0
        foreach refs [find_element references $bv(.CHILDREN)] {
            catch { array unset sv }
            array set sv $elem($refs)
            foreach ref [find_element reference $sv(.CHILDREN)] {
                catch { array unset rv }
                array set rv $elem($ref)
                if {![info exists rv(anchor)]} {
                    continue
                }
                if {[set x [lsearch $firstxref $rv(anchor)]] < 0} {
                    set x [llength $firstxref]
                    lappend firstxref $rv(anchor)
                    unexpected warning "no <xref> in <rfc> targets <reference anchor='$rv(anchor)'>"
                }
                if {!$warnonly} {
                    set rv(.COUNTER) $x
                    set elem($ref) [array get rv]
                }
            }
            if {$warnonly} {
                continue
            }
            foreach ref [lsort -command sort_references \
                                [find_element reference $sv(.CHILDREN)]] {
                catch { array unset rv }
                array set rv $elem($ref)
                set rv(.COUNTER) [incr offset]
                set elem($ref) [array get rv]
                set target $rv(anchor)
                catch { array unset xv }
                array set xv $xref($target)
                set xv(value) $offset
                set xref($target) [array get xv]
            }
        }
    }
}
# Sort irefs by:
#  $elem(item)
#  $elem(subitem)
#  $elem(flags)
# Use lsort -dictionary to get dictionary comparison if we're
# comparing item and subitem; just use string compare on flags.
proc iref_sort {elemA elemB} {
    global elem
    array set a $elem($elemA)
    array set b $elem($elemB)
    set aval $a(item)
    set bval $b(item)
    if {[string compare $aval $bval] == 0} {
        set aval $a(subitem)
        set bval $b(subitem)
        if {[string compare $aval $bval] == 0} {
            return [string compare $a(flags) $b(flags)]
        }
    }
    # use lsort to get dictionary order on items
    set result [lindex [lsort -dictionary [list $aval $bval]] 0]
    if {[string compare $aval $result] == 0} {
        return -1
    } else {
        return 1
    }
}
proc pass2end_rfc {elemX} {
    global elem
    global elemZ
    global mode
    global options
    global pageno
    global copyurl
    array set attrs $elem($elemX)
    set front [find_element front $attrs(.CHILDREN)]
    array set fv $elem($front)
    if {[catch { clock format $fv(.PARSEDDATE) -format "%Y%m%d" -gmt true } \
               ymd]} {
        # Should differentiate between PARSEDATE not set (e.g., early pass)
        # vs. PARSEDATE set to 0 (i.e., couldn't parse date)
        set ymd ""
    }
    set date [find_element date $fv(.CHILDREN)]
    array set dv $elem($date)
    if {$options(.SYMREFS) == 2} {
        unexpected warning "<?rfc symrefs=?> now defaults to \"yes\""
    }
    ###########
    # Authors #
    ###########
    set authors ""
    foreach child [find_element author $fv(.CHILDREN)] {
        array set av [list initials "" surname "" fullname "" role ""]
        array set av $elem($child)
        set organization [find_element organization $av(.CHILDREN)]
        if {[llength $organization] == 1} {
          array set ov [list abbrev ""]
          if {[string compare $organization ""]} {
              array set ov $elem($organization)
          }
        }
        set block1 ""
        if {[string compare $av(fullname) ""]} {
            if {![string compare $av(role) editor]} {
                append av(fullname) " (editor)"
            }
            lappend block1 $av(fullname)
        }
        if {[llength $organization] == 1 && [string compare $ov(.CTEXT) ""]} {
            lappend block1 $ov(.CTEXT)
        }
        set address [find_element address $av(.CHILDREN)]
        set block2 ""
        if {[llength $address] == 1} {
            array set zv $elem($address)
            set postal [find_element postal $zv(.CHILDREN)]
            if {[llength $postal] == 1} {
                array set pv $elem($postal)
                foreach street [find_element street $pv(.CHILDREN)] {
                    array set sv $elem($street)
                    if {[string compare $sv(.CTEXT) ""]} {
                        lappend block1 $sv(.CTEXT)
                    }
                }
                set s ""
                foreach e {city region code} t {"" ", " "  "} {
                    set f [find_element $e $pv(.CHILDREN)]
                    if {[llength $f] == 1} {
                        catch { array unset fv }
                        array set fv $elem($f)
                        if {[string compare $s ""]} {
                            append s $t
                        }
                        append s $fv(.CTEXT)
                    }
                }
                if {[string compare $s ""]} {
                    lappend block1 $s
                }
                set f [find_element country $pv(.CHILDREN)]
                if {[llength $f] == 1} {
                    catch { array unset fv }
                    array set fv $elem($f)
                    lappend block1 $fv(.CTEXT)
                }
            }
            set block2 ""
            foreach e {phone facsimile email uri} {
                set f [find_element $e $zv(.CHILDREN)]
                if {[llength $f] == 1} {
                    catch { array unset fv }
                    array set fv $elem($f)
                    lappend block2 [list $e $fv(.CTEXT)]
                }
            }
        }
        lappend authors [list $block1 $block2]
    }
    if {($options(.STRICT)) && ([set l [llength $authors]] > 5)} {
        unexpected error "$l authors, maximum of 5 allowed"
    }
    #######
    # IPR #
    #######
    set newP 3
    if {[string compare $attrs(number) ""]} {
        # TODO: set newP using PARSEDDATE for all the options
        if {$attrs(number) <= 3707} {
            set newP 0
        } elseif {$attrs(number) <= 4671} {
            # 4671 is a guess
            set newP 1
        } elseif {$ymd < "20081101"} {
            set newP 2
        }
    } elseif {[string compare $attrs(ipr) ""]} {
        if {   [string first "3667" $attrs(ipr)] >=0
            || [string first "3978" $attrs(ipr)] >=0} {
            set newP 2
        } elseif {[string first "trust" [string tolower $attrs(ipr)]] < 0} {
            set newP 0
        }
    }
    if {$newP} {
        global copylong2 copylong3 copylong4 copylong5 validity1 validity2
        if {$newP == 1} {
                switch -- $attrs(submissionType) {
                    IETF {
                        set copylong $copylong2
                    }
                    independent {
                        set copylong $copylong3
                    }
                    default {
                        unexpected error \
                            "submissionType=\"$attrs(submissionType)\" unexpected for this boilerplate"
                    }
                }
                set validity $validity1
        } elseif {$newP == 2} {
                switch -- $attrs(submissionType) {
                    IETF {
                        set copylong $copylong4
                    }
                    independent {
                        set copylong $copylong5
                    }
                    default {
                        unexpected error \
                            "submissionType=\"$attrs(submissionType)\" unexpected for this boilerplate"
                    }
                }
                set validity $validity2
        } else {
                # IETF Trust removed these statements at the back
                set copylong ""
                set validity ""
        }
    } else {
        global copylong1
        set copylong $copylong1
        set validity ""
    }
    regsub -all -- %YEAR% $copylong $dv(year) copying
    if {![string compare $mode html]} {
        regsub -all -- %COPYURL% $copying "<a href='$copyurl'>$copyurl</a>" copying
    } else {
        regsub -all -- %COPYURL% $copying $copyurl copying
    }
    if {![catch { set who $attrs(disclaimant) }]} {
        # This is an undocumented non-IETF extension.
        lappend copying \
"%WHO% expressly disclaims any and all warranties regarding this
contribution including any warranty that (a) this contribution does
not violate the rights of others, (b) the owners, if any, of other
rights in this contribution have been informed of the rights and
permissions granted to IETF herein, and (c) any required
authorizations from such owners have been obtained.
This document and the information contained herein is provided on
an “AS IS” basis and %UWHO% DISCLAIMS ALL WARRANTIES, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE
OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY
IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR
PURPOSE." \
 \
"IN NO EVENT WILL %UWHO% BE LIABLE TO ANY OTHER PARTY INCLUDING
THE IETF AND ITS MEMBERS FOR THE COST OF PROCURING SUBSTITUTE GOODS
OR SERVICES, LOST PROFITS, LOSS OF USE, LOSS OF DATA, OR ANY
INCIDENTAL, CONSEQUENTIAL, INDIRECT, OR SPECIAL DAMAGES WHETHER
UNDER CONTRACT, TORT, WARRANTY, OR OTHERWISE, ARISING IN ANY WAY
OUT OF THIS OR ANY OTHER AGREEMENT RELATING TO THIS DOCUMENT,
WHETHER OR NOT SUCH PARTY HAD ADVANCE NOTICE OF THE POSSIBILITY OF
SUCH DAMAGES."
        regsub -all -- %WHO% $copying $who copying
        regsub -all -- %UWHO% $copying [string toupper $who] copying
    }
    if {$newP} {
        global iprlong2
        set iprstmt $iprlong2
    } else {
        global iprlong1
        set iprstmt $iprlong1
        if {$options(.IPRNOTIFIED)} {
            global iprextra
            set iprstmt [concat $iprstmt $iprextra]
        }
    }
    #########
    # Index #
    #########
    set elems ""
    # use \uFFFD REPLACEMENT CHARACTER to separate items in the key of $index,
    # assuming that never legitimately appears in iref elements.
    array set index ""
    for {set elemY 1} {$elemY <= $elemZ} {incr elemY} {
        catch { array unset iv }
        array set iv $elem($elemY)
        if {[string compare $iv(.NAME) iref]} {
            continue
        }
        lappend elems $elemY
        lappend index($iv(item)\uFFFD$iv(subitem)\uFFFD$iv(flags)) $iv(.ANCHOR)
    }
    set elems [lsort -command iref_sort $elems]
    set irefs ""
    set L ""
    set K ""
    set previtem ""
    foreach elemY $elems {
        catch { array unset iv }
        array set iv $elem($elemY)
        set key $iv(item)
        set subkey $iv(subitem)
        set flags $iv(flags)
        set curitem "$key\uFFFD$subkey\uFFFD$flags"
        if {$curitem == $previtem} {
            continue
        }
        set previtem $curitem
        set iref ""
        if {[string compare [set c [string toupper [string index $key 0]]] \
                    $L]} {
            lappend iref [set L $c]
            set K ""
        } else {
            lappend iref ""
        }
        if {[string compare $key $K]} {
            lappend iref [set K $key]
        } else {
            lappend iref ""
        }
        lappend iref $subkey
        lappend iref $flags
        lappend iref $index($curitem)
        lappend irefs $iref
    }
    set attrs(.ANCHOR) [rfc_$mode $irefs $authors $iprstmt $copying $newP $validity]
    set elem($elemX) [array get attrs]
    if {([string compare $mode html]) \
            && ($options(.STRICT)) && (!$options(.TOC)) \
            && ($pageno > 15)} {
        unexpected error "no table of contents, but $pageno pages"
    }
}
#       }}}2 Pass 2 (and subsequent) stuff for the whole document
#       {{{2 Front texts (either for the rfc or a reference)
global copyshort copyshort1 copyshort2 idinfo idinfo2 idaburl idshurl
set idaburl "http://www.ietf.org/ietf/1id-abstracts.txt"
set idshurl "http://www.ietf.org/shadow.html"
# From RFC 2223, Section 6.
set copyshort1 \
{"Copyright © The Internet Society (%YEAR%). All Rights Reserved."}
# From the rfc-editor/instructions2authors.txt file, Section 4.3.
# Currently draft-rfc-editor-rfc2223bis-08, which is expired.
set copyshort2 \
{"Copyright © The Internet Society (%YEAR%)."}
# RFC 4748 modification to copyshort2
set copyshort3 \
{"Copyright © The IETF Trust (%YEAR%)."}
# Trust Copyright and License
# various dates, some incl pre5378 escape clause
set copyshortTrust200811 \
{"Copyright (c) %YEAR% IETF Trust and the persons identified as the
document authors.  All rights reserved."
"This document is subject to BCP 78 and the IETF Trust's Legal
Provisions Relating to IETF Documents
(http://trustee.ietf.org/license-info) in effect on the date of
publication of this document.  Please review these documents
carefully, as they describe your rights and restrictions with respect
to this document."}
set copyshortTrust200902 \
{"Copyright (c) %YEAR% IETF Trust and the persons identified as the
document authors.  All rights reserved."
"This document is subject to BCP 78 and the IETF Trust's Legal
Provisions Relating to IETF Documents in effect on the date of
publication of this document (http://trustee.ietf.org/license-info).
Please review these documents carefully, as they describe your
rights and restrictions with respect to this document."}
set pre5378escapeClause \
"This document may contain material from IETF Documents or IETF
Contributions published or made publicly available before November
10, 2008.  The person(s) controlling the copyright in some of this
material may not have granted the IETF Trust the right to allow
modifications of such material outside the IETF Standards Process.
Without obtaining an adequate license from the person(s) controlling
the copyright in such materials, this document may not be modified
outside the IETF Standards Process, and derivative works of it may
not be created outside the IETF Standards Process, except to format
it for publication as an RFC or to translate it into languages other
than English."
set copyshortTrust200909 \
{"Copyright (c) %YEAR% IETF Trust and the persons identified as the
document authors.  All rights reserved."
"This document is subject to BCP 78 and the IETF Trust's Legal
Provisions Relating to IETF Documents
(http://trustee.ietf.org/license-info) in effect on the date of
publication of this document.  Please review these documents
carefully, as they describe your rights and restrictions with respect
to this document.%CODECOMPONENTS%"}
set codeComponents200909 \
" Code Components extracted from this document must
include Simplified BSD License text as described in Section 4.e of
the Trust Legal Provisions and are provided without warranty as
described in the %SIMPLIFIED%BSD License."
# From the ietf/1id-guidelines.txt file, Section 5.
set idinfo {
"%IPR%"
"Internet-Drafts are working documents of the Internet Engineering
Task Force (IETF), its areas, and its working groups.
Note that other groups may also distribute working documents as
Internet-Drafts."
"Internet-Drafts are draft documents valid for a maximum of six months
and may be updated, replaced, or obsoleted by other documents at any time.
It is inappropriate to use Internet-Drafts as reference material or to cite
them other than as “work in progress.”"
"The list of current Internet-Drafts can be accessed at
%IDABURL%."
"The list of Internet-Draft Shadow Directories can be accessed at
%IDSHURL%."
"This Internet-Draft will expire on %EXPIRES%."
}
# Shorter idinfo approved as an alternative by the IESG on 2010-1-5 and
# announced on 2010-2-8:
# http://www.ietf.org/mail-archive/web/ietf-announce/current/msg07008.html
set idinfo2 {
"%IPR%"
"Internet-Drafts are working documents of the Internet Engineering
Task Force (IETF).  Note that other groups may also distribute
working documents as Internet-Drafts.  The list of current
Internet-Drafts is at http://datatracker.ietf.org/drafts/current/."
"Internet-Drafts are draft documents valid for a maximum of six months
and may be updated, replaced, or obsoleted by other documents at any time.
It is inappropriate to use Internet-Drafts as reference material or to cite
them other than as “work in progress.”"
"This Internet-Draft will expire on %EXPIRES%."
}
#       }}}2 Front texts (either for the rfc or a reference)
#       {{{2 Remaining pass 2 (and subsequent) stuff
proc pass2begin_front {elemX} {
    global counter elem xref
    global options
    global mode ofile
    global categories copyshort idinfo idinfo2 idaburl idshurl iprstatus
    global page_width center_fill_width
    global depth
    if {$options(.COLONSPACE)} {
        set colonspace " "
    } else {
        set colonspace ""
    }
    array set attrs $elem($elemX)
    set title [find_element title $attrs(.CHILDREN)]
    array set tv [list abbrev ""]
    array set tv $elem($title)
    set title [list $tv(.CTEXT)]
    set date [find_element date $attrs(.CHILDREN)]
    array set dv $elem($date)
    array set rv $elem(1)
    catch { set ofile $rv(docName) }
    if {$options(.PRIVATE)} {
        lappend left $options(private)
        set status ""
    } else {
        set first ""
        if {(![string compare $rv(number) ""]) \
                && ([string compare \
                             [set workgroup [lindex [find_element workgroup \
                                 $attrs(.CHILDREN)] 0]] ""])} {
            array set wv $elem($workgroup)
            set first [string trim $wv(.CTEXT)]
        }
        if {![string compare $first ""]} {
            set first "Network Working Group"
        }
        lappend left $first
        if {[catch { set day $dv(day) }]} {
            set day 1
        }
        set secs $attrs(.PARSEDDATE)
        if {[info exists rv(category)]} {
            set cindex [lsearch0 $categories $rv(category)]
        } else {
            set cindex -1
        }
        if {[string compare $rv(number) ""]} {
            if {$cindex == -1} {
                unexpected error "category attribute is mandatory for RFC"
            }
            lappend left "Request for Comments:$colonspace $rv(number)"
            if {[string compare $rv(seriesNo) ""]} {
                lappend left \
                        "[lindex [lindex $categories $cindex] 2]:$colonspace $rv(seriesNo)"
            }
            if {[string compare $rv(obsoletes) ""]} {
                lappend left "Obsoletes:$colonspace $rv(obsoletes)"
            }
            if {[string compare $rv(updates) ""]} {
                lappend left "Updates:$colonspace $rv(updates)"
            }
            set category [lindex [lindex $categories $cindex] 1]
            lappend left "Category:$colonspace $category"
            set status [list [lindex [lindex $categories $cindex] 3]]
        } else {
            if {$options(.STRICT)} {
                if {$cindex == -1} {
                    unexpected error "category attribute is mandatory when submitting for publication as RFC"
                }
                foreach t [list Abstract "Security Considerations"] {
                    if {![info exists counter([string tolower $t])]} {
                        unexpected error "missing $t"
                    }
                }
                if {([info exists depth(references)]) \
                        && ($depth(references))} {
                    set hitP 0
                    foreach t [list normative informative] {
                        if {[info exists counter([string tolower $t])]} {
                            set hitP 1
                        }
                    }
                    if {!$hitP} {
                        unexpected error \
                                   "missing Normative/Informative References"
                    }
                }
            }
            lappend left "Internet-Draft"
            if {[string compare $rv(obsoletes) ""]} {
                lappend left "Obsoletes:$colonspace $rv(obsoletes) (if approved)"
            }
            if {[string compare $rv(updates) ""]} {
                lappend left "Updates:$colonspace $rv(updates) (if approved)"
            }
            if {$cindex != -1} {
                switch -- $rv(category) {
                    bcp {
                        set tindex 2
                    }
                    default {
                        set tindex 1
                    }
                }
                lappend left "Intended status:$colonspace [lindex [lindex $categories $cindex] $tindex]"
            }
            if {$secs == 0} {
                unexpected error "Can't parse date to generate expires"
            }
            incr secs [expr (185*86400)]
            set day [string trimleft \
                            [clock format $secs -format "%d" -gmt true] 0]
            set expires [clock format $secs -format "%B $day, %Y" -gmt true]
            lappend left "Expires:$colonspace $expires"
            set category "Expires $expires"
            set ipreal $rv(ipr)
            set ymd [clock format $attrs(.PARSEDDATE) -format "%Y%m%d" \
                           -gmt true]
            if {($ymd >= "20091101") \
                    && ![string compare $ipreal pre5378Trust200902]} {
                set ipreal trust200902
            }
            # Use the shorter alternative for the ID info for new IDs
            # starting April 1, 2010.
            if {$ymd >= 20100401} {
                    set status $idinfo2
            } else {
                    set status $idinfo
            }
            regsub -all -- "&" [lindex [lindex $iprstatus \
                                              [lsearch0 $iprstatus \
                                                        $ipreal]] 1] \
                        "\\\\\\&" ipr
            
            if {($ymd < "20100401")} {
              # insert "to IETF" for documents before Feb 01 2010
              regsub -all -- %TOIETF% $ipr "to IETF" ipr
            } else {
              regsub -all -- %TOIETF% $ipr "" ipr
            }
            regsub -all -- %IPR% $status $ipr status
            if {![string compare $mode html]} {
                regsub -all -- %IDABURL% $status "<a href='$idaburl'>$idaburl</a>" status
                regsub -all -- %IDSHURL% $status "<a href='$idshurl'>$idshurl</a>" status
            } else {
                regsub -all -- %IDABURL% $status $idaburl status
                regsub -all -- %IDSHURL% $status $idshurl status
            }
            if {[string compare [set anchor $rv(iprExtract)] ""]} {
                set extract ", other than to extract "
                append extract [xref_$mode "" $xref($anchor) $anchor "" 1]
                regsub -all -- { } $extract {%NBSP%} extract
                append extract " as-is for separate use"
                if {[string first "%IPREXTRACT%" $status] < 0} {
                    unexpected error "iprExtract attribute not compatible with ipr $rv(ipr)"
                }
            } else {
                set extract ""
            }
            regsub -all -- %IPREXTRACT% $status $extract status
            regsub -all -- %NBSP% $status {\ } status
            regsub -all -- %EXPIRES% $status $expires status
        }
    }
    set authors ""
    set names ""
    foreach child [find_element author $attrs(.CHILDREN)] {
        array set av [list initials "" surname "" fullname "" role ""]
        array set av $elem($child)
        switch -- $av(role) {
            editor - "" {}
            default {
                unexpected error "invalid role attribute: $av(role)"
            }
        }
        set organization [find_element organization $av(.CHILDREN)]
        array set ov [list abbrev ""]
        if {[llength $organization] == 1} {
          if {[string compare $organization ""]} {
              array set ov $elem($organization)
          }
          if {![string compare $ov(abbrev) ""]} {
              set ov(abbrev) $ov(.CTEXT)
          }
        }
        if {[string compare $av(initials) ""]} {
            set av(initials) [lindex [split $av(initials) .] 0].
        }
        set av(abbrev) "$av(initials) $av(surname)"
        if {[string length $av(abbrev)] == 1} {
            set av(abbrev) ""
            lappend names $ov(abbrev)
        } else {
            lappend names $av(surname)
            if {![string compare $av(role) editor]} {
                append av(abbrev) ", Ed."
            }
        }
        set authors [linsert $authors 0 [list $av(abbrev) $ov(abbrev)]]
    }
    set lastO ""
    set right ""
    foreach author $authors {
        if {[string compare [set value [lindex $author 1]] $lastO]} {
            set right [linsert $right 0 [set lastO $value]]
        }
        if {[string compare [set value [lindex $author 0]] ""]} {
            set right [linsert $right 0 $value]
        }
    }
    set day ""
    if {(![string compare $rv(number) ""]) \
            && (![catch { set day $dv(day) }])} {
        set day "$day, "
    }
    lappend right "$dv(month) $day$dv(year)"
    if {$options(.HEADER)} {
        lappend top $options(header)
    } elseif {[string compare $rv(number) ""]} {
        lappend top "RFC $rv(number)"
    } else {
        lappend top "Internet-Draft"
        lappend title $ofile
    }
    set l [string length [lindex $top end]]
    lappend top "$dv(month) $dv(year)"
    set l2 [string length [lindex $top end]]
    if {$l < $l2} {
        set l $l2
    }
    set l [expr $page_width - 2 * ($l + $center_fill_width) + ($l2 < $l)]
    if {[set l2 [string length $tv(abbrev)]] <= 0} {
        if {[string length $tv(.CTEXT)] > $l} {
            unexpected error "<title> element needs an abbrev attribute of at most $l characters"
        } else {
            set tv(abbrev) $tv(.CTEXT)
        }
    } elseif {$l2 > $l} {
        unexpected error "abbrev attribute of <title> element is still too long ($l2 > $l)"
    }
    set top [linsert $top 1 $tv(abbrev)]
    switch -- [llength $names] {
        1       { lappend bottom [lindex $names 0] }
        2       { lappend bottom "[lindex $names 0] & [lindex $names 1]" }
        default { lappend bottom "[lindex $names 0], et al." }
    }
    if {$options(.FOOTER)} {
        lappend bottom $options(footer)
    } else {
        lappend bottom $category
    }
    regsub -all -- %YEAR% $copyshort $dv(year) copying
    set keywords {}
    foreach child [find_element keyword $attrs(.CHILDREN)] {
        array set kv $elem($child)
        lappend keywords $kv(.CTEXT)
    }
    front_${mode}_begin $left $right $top $bottom $title $keywords $rv(xml:lang)
    if {[string compare $rv(number) ""]} {
      set cutoff 20090701
    } else {
      set cutoff 20091101
    }
    if {([catch { clock format $attrs(.PARSEDDATE) -format %Y%m%d \
                               -gmt true } ymd]) \
            || ($ymd < "$cutoff")} {
        set options(.ABSTRACT1ST) 0
        write_status_${mode} $status $copying 0
    } else {
        set options(.ABSTRACT1ST) 1
        set attrs(.STATUS) $status
        set attrs(.COPYING) $copying
        set elem($elemX) [array get attrs]
    }
}
proc pass2end_front {elemX} {
    global elem
    global elemZ
    global options copyrightP
    global mode
    global crefs
    array set attrs $elem($elemX)
    if {[info exists attrs(.STATUS)]} {
        write_status_${mode} $attrs(.STATUS) $attrs(.COPYING) 1
    }
    set toc ""
    if {$options(.TOC)} {
        set refs 0
        set irefP 0
        set backP 0
        set author ""
        set back ""
        set ipr ""
        for {set elemY 1} {$elemY <= $elemZ} {incr elemY} {
            catch { array unset cv }
            array set cv $elem($elemY)
            switch -- $cv(.NAME) {
                rfc {
                    if {!$options(.PRIVATE) && ($copyrightP > 0) && !$options(.RFCEDSTYLE)} {
                        set title "Intellectual Property and Copyright Statements"
                        set anchor ""
                        if {![string compare $mode html]} {
                            set anchor rfc.copyright
                            set label "§"
                        } else {
                            catch { set anchor $cv(.ANCHOR) }
                            set label ""
                        }
                        set ipr [list 0 $label $title $anchor]
                    }
                }
                front {
                    if {$elemY > 2 || $options(.RFCEDSTYLE)} {
                        # <reference>s have a <front> too!
                        continue
                    }
                    set n [llength [find_element author $cv(.CHILDREN)]]
                    if {$n == 0} {
                        continue
                    } elseif {$n == 1} {
                        set title "Author's Address"
                    } else {
                        set title "Authors' Addresses"
                    }
                    set anchor ""
                    if {![string compare $mode html]} {
                        set anchor rfc.authors
                        set label "§"
                    } else {
                        global authorspg
                        set anchor $authorspg
                        set label ""
                    }
                    if {$options(.AUTHORSHIP)} {
                        set author [list 0 $label $title $anchor]
                    }
                }
                section - appendix {
                    if {[string compare $back ""]} {
                        lappend toc $back
                        set back ""
                    }
                    set x [llength [split [set label $cv(.COUNTER)] .]]
                    incr x -1
                    switch -- $cv(toc) {
                        include {}
                        exclude { continue }
                        default {
                            if {$x >= $options(.TOCDEPTH)} {
                                continue
                            }
                        }
                    }
                    if {   (!$x && $backP)
                        || ![string compare $cv(.NAME) "appendix"]} {
                        set x -1
                    }
                    append label .
                    lappend toc [list $x $label $cv(title) $cv(.ANCHOR)]
                }
                back {
                    set backP 1
                    if {(!$options(.INLINE)) && ([array size crefs] > 0)} {
                        set anchor ""
                        if {![string compare $mode html]} {
                            set anchor rfc.comments
                            set label "§"
                        } else {
                            catch { set anchor $cv(.ANCHOR) }
                            set label ""
                        }
                        set back [list 0 $label "Editorial Comments" $anchor]
                    }
                }
                references {
                    set anchor ""
                    if {![string compare $mode html]} {
                        set anchor rfc.references[incr refs]
                    } else {
                        catch { set anchor $cv(.ANCHOR) }
                    }
                    set label $cv(.COUNTER)
                    if {[catch { set title $cv(title) }]} {
                        set title References
                    }
                    set l [split $label .]
                    set x [expr [llength $l] - 1]
                    if {$x == 1 && ![string compare [lindex $l 1] 1]} {
                        lappend toc [list 0 [lindex $l 0]. $options(refparent) \
                                          $anchor]
                    }
                    append label .
                    lappend toc [list $x $label $title $anchor]
                }
                iref {
                    set irefP 1
                }
            }
        }
        if {[string compare $back ""]} {
            lappend toc $back
        }
        if {$irefP} {
            global indexpg
            if {![string compare $mode html]} {
                set label "§"
            } else {
                set label ""
            }
            lappend toc [list 0 $label Index $indexpg]
        }
        if {[string compare $author ""]} {
            lappend toc $author
        }
        if {[string compare $ipr ""]} {
            lappend toc $ipr
        }
    }
    front_${mode}_end $toc
}
# the abstract/note elements
proc pass2begin_abstract {elemX} {
    global mode
    abstract_$mode
}
proc pass2begin_note {elemX} {
    global elem stack
    global mode
    set d 0
    foreach frame $stack {
        if {![string compare [lindex $frame 0] note]} {
            incr d
        }
    }
    array set attrs $elem($elemX)
    note_$mode $attrs(title) $d
}
# the section element
proc pass2begin_section {elemX {appendP 0}} {
    global elem stack
    global mode
    # In case we're in <back> and this hasn't been done yet.
    pass2middle_back
    array set attrs [list anchor ""]
    array set attrs $elem($elemX)
    if {([lsearch0 $stack appendix] < 0) && ([lsearch0 $stack section] < 0)} {
        set top 1
    } else {
        set top 0
    }
    set prefix ""
    set s $attrs(.COUNTER)
    append s .
    if {($appendP) || (([lsearch0 $stack back] >= 0) && ($top))} {
        set prefix "Appendix "
    }
    set title $attrs(title)
    set lines 1
    if {[llength $attrs(.CHILDREN)] > 0} {
        set elemY [lindex $attrs(.CHILDREN) 0]
        array set cv $elem($elemY)
        switch -- $cv(.NAME) {
            figure - texttable {
                incr lines [pass2begin_$cv(.NAME) $elemY 1]
            }
            default { incr lines 2 }
        }
    }
    set attrs(.ANCHOR) \
        [section_$mode $prefix$s $top $title $lines $attrs(anchor)]
    set elem($elemX) [array get attrs]
}
proc pass2begin_appendix {elemX {appendP 0}} {
    global appendixW
    if {[catch { set appendixW }]} {
        set appendixW 1
        unexpected warning \
                   "<appendix/> element is deprecated, use <section/> instead"
    }
    pass2begin_section $elemX 1
}
proc section_title {elemX} {
    global elem
    array set attrs [list anchor "" title ""]
    array set attrs $elem($elemX)
    return $attrs(title)
}
# the t element
proc pass2begin_t {elemX} {
    global counter elem stack
    global mode
    array set attrs [list .COUNTER "" style "" hangText "" \
                          hangIndent "" anchor   ""]
    array set attrs $elem($elemX)
    set elem($elemX) [array get attrs]
    if {[string compare $attrs(.COUNTER) ""]} {
        # Get <list>.
        set frame [lindex $stack end]
        array set av [lrange $frame 1 end]
        set elemY $av(elemN)
        array set av $elem($elemY)
        if {![info exists av(.STYLE)]} {
            unexpected error "<list> element not subordinate to <t> element"
        }
        set attrs(hangIndent) $av(hangIndent)
        if {![string compare [set attrs(style) $av(.STYLE)] format]} {
            set attrs(style) hanging
            if {![string compare $attrs(hangText) ""]} {
                # $format has already been validated.
                set format $av(.FORMAT)
                set attrs(hangText) [apply_list_style_format \
                                     $format $attrs(.FMTCOUNTER)]
            }
        }
        set elem($elemX) [array get attrs]
    }
    t_$mode begin $attrs(.COUNTER) $attrs(style) $attrs(hangText) \
            $attrs(.EDITNO)
}
proc pass2end_t {elemX} {
    global elem
    global mode
    array set attrs $elem($elemX)
    t_$mode end $attrs(.COUNTER) $attrs(style) $attrs(hangText) ""
}
proc validate_list_style_format {fmt {errstr "<list style='format ...'> spec"}} {
    set p 0
    set n 0
    while {[regexp -start $p -indices -- % $fmt x]} {
        set p [lindex $x 0]
        incr p
        switch -- [set c [string index $fmt $p]] {
            % {}
            d - C - c - I - i - o - X - x {
                set fmttoken %$c
                incr n
            }
            "" {
                unexpected error "truncated % token at end of $errstr"
            }
            default {
                unexpected error "invalid %$c token in $errstr"
            }
        }
        incr p
    }
    set tokens "%d/%C/%c/%I/%i/%o/%X/%x"
    if {$n == 0} {
        unexpected error "missing one of $tokens in $errstr"
    } elseif {$n > 1} {
        unexpected error "more than one $tokens in $errstr"
    }
    return $fmttoken
}
proc apply_list_style_format {fmt c} {
    # This assumes that $fmt has already been validated.  No errors are thrown.
    set s ""
    set p 0
    while {[regexp -start $p -indices -- {%.} $fmt x]} {
        append s [string range $fmt $p [expr [lindex $x 0] - 1]]
        set p [lindex $x 1]
        switch -- [string index $fmt $p] {
            d { set v $c }
            C { set v [offset2letters $c 0] }
            c { set v [offset2letters $c 1] }
            I { set v [offset2romans $c 0] }
            i { set v [offset2romans $c 1] }
            o { set v [format %o $c] }
            X { set v [format %X $c] }
            x { set v [format %x $c] }
            % { set v % }
            default { set v "" }
        }
        append s $v
        incr p
    }
    append s [string range $fmt $p end]
    return $s
}
# the list element
proc pass2begin_list {elemX} {
    global elem stack
    global mode
    # Default values (to be inherited and overridden).
    set style empty
    set hangIndent 0
    # Inherit defaults for innermost ancestor <list>, if any.
    if {[set x [llast0 $stack list]] >= 0} {
        array set fv [lrange [lindex $stack $x] 1 end]
        array set av $elem($fv(elemN))
        # Outer lists have been normalized, so no need for a catch {}.
        set style      $av(style)
        set hangIndent $av(hangIndent)
    }
    # Current element is not yet in stack nor normalized.
    array set attrs [list counter ""]
    array set attrs $elem($elemX)
    array set attrs [list  FORMAT ""  FMTTOKEN ""]
    catch { set style      $attrs(style)      }
    catch { set hangIndent $attrs(hangIndent) }
    set fmtcountername $attrs(counter)
    set longestHangText ""
    # Validate and process style attribute.
    set errstr "style=\"$style\" attribute of <list> element"
    if {[regexp -- {^format[ \t]+(.*)$} $style x format]} {
        if {[string compare $format ""]} {
            set attrs(.STYLE) format
            set fmttoken [validate_list_style_format $format $errstr]
            switch -glob -- $fmttoken {
                *I - *i { set x $attrs(.LONGEST_ROMAN) }
                default { set x $attrs(.MAX) }
            }
            set longestHangText [apply_list_style_format $format $x]
            set attrs(.FORMAT) $format
            set attrs(.FMTTOKEN) $fmttoken
        } else {
            set attrs(.STYLE) hanging
        }
    } else {
        switch -- $style {
            empty - letters - numbers - symbols - hanging {}
            letter - number - symbol {
                unexpected error \
  "did you mean style=\"${style}s\" (plural) instead of the invalid $errstr"
            }
            default {
                unexpected error "invalid $errstr"
            }
        }
        set attrs(.STYLE) $style
    }
    # Save systematically-defined and normalized values for this <list>.
    array set attrs [list style $style  hangIndent $hangIndent]
    set elem($elemX) [array get attrs]
    list_$mode begin $attrs(.MIN) $attrs(.MAX) $attrs(.STYLE) \
               $attrs(hangIndent) $longestHangText \
               [expr ([lsearch0 $stack list] >= 0) ? -1 : [lsearch0 $stack t]]
}
proc pass2end_list {elemX} {
    global elem stack
    global mode
    array set attrs $elem($elemX)
    list_$mode end $attrs(.MIN) $attrs(.MAX) $attrs(.STYLE) \
               "" "" \
               [expr ([lsearch0 $stack list] >= 0) ? -1 : [lsearch0 $stack t]]
}
# the figure and artwork elements
proc pass2begin_figure {elemX {internal 0}} {
    global elem
    global mode
    array set attrs [list anchor "" title "" suppress-title false]
    array set attrs $elem($elemX)
    set lines 0
    foreach p {preamble postamble} {
        if {[llength [find_element $p $attrs(.CHILDREN)]] == 1} {
            incr lines 3
        }
    }
    if {$lines > 5} {
        set lines 5
    }
    set artwork [find_element artwork $attrs(.CHILDREN)]
    array set av $elem($artwork)
    # <artwork> may be empty!
    catch { incr lines [llength [split $av(.CTEXT) "\n"]] }
    if {$internal} {
        return $lines
    }
    catch { push_align $attrs(align) }
    figure_$mode begin $lines $attrs(anchor) $attrs(title) [array get attrs]
}
proc pass2end_figure {elemX} {
    global elem
    global mode
    array set attrs [list anchor "" title "" suppress-title false]
    array set attrs $elem($elemX)
    switch -- [string tolower $attrs(suppress-title)] {
        yes - true - 1 {
            set suppressP 1
        }
        default {
            set suppressP 0
        }
    }
    figure_$mode end "" $attrs(anchor) $attrs(title) [array get attrs] \
                 $suppressP
    if {[info exists attrs(align)]} {
        pop_align
    }
}
proc pass2begin_artwork {elemX} {
    global elem
    global options
    global mode
    array set attrs $elem($elemX)
    switch -- $mode {
        nr - txt {
            if {([string compare $options(artworkdelimiter) ""]) \
                    && ([info exists attrs(.SDATA)])} {
                set attrs(.SDATA) "$options(artworkdelimiter)\n$attrs(.SDATA)\n$options(artworkdelimiter)"
                set elem($elemX) [array get attrs]
            }
            if {($options(.ARTWORKLINES) > 0) \
                    && ([info exists attrs(.SDATA)])} {
                set extra ""
                for {set i $options(.ARTWORKLINES)} {$i > 0} {incr i -1} {
                    append extra "\n"
                }
                set attrs(.SDATA) $extra$attrs(.SDATA)$extra
                set elem($elemX) [array get attrs]
            }
        }
    }
    catch { push_align $attrs(align) }
    set align [current_align]
    catch {
        set lines 0
        # <artwork> may be empty!
        set ctext [split $attrs(.CTEXT) "\n"]
        set lines [llength $ctext]
        if {   ![string compare $mode html]
            || ![catch {set x $attrs(.TEXTWIDTH)}]} {
            # break from catch
            error ""
        }
        set textwidth 0
        foreach l $ctext {
            set ll [string length [string trimright [chars_expand $l]]]
            if {$ll > $textwidth} {
                set textwidth $ll
            }
        }
        set attrs(.TEXTWIDTH) $textwidth
        set elem($elemX) [array get attrs]
    }
    artwork_$mode begin $lines [array get attrs]
}
proc pass2end_artwork {elemX} {
    global elem
    global mode
    array set attrs $elem($elemX)
    artwork_$mode end 0 [array get attrs]
    if {[info exists attrs(align)]} {
        pop_align
    }
}
# the preamble/postamble elements
proc pass2begin_preamble {elemX} {
    global elem
    global mode
    array set attrs $elem($elemX)
    preamble_$mode begin $attrs(.EDITNO)
}
proc pass2end_preamble {elemX} {
    global mode
    preamble_$mode end
}
proc pass2begin_postamble {elemX} {
    global elem
    global mode
    array set attrs $elem($elemX)
    postamble_$mode begin $attrs(.EDITNO)
}
proc pass2end_postamble {elemX} {
    global mode
    postamble_$mode end
}
# the texttable element
proc pass2begin_texttable {elemX {internal 0}} {
    global elem
    global mode
    global options
    global cellR
    array set attrs [list anchor "" title "" suppress-title false style full \
                          align center]
    array set attrs $elem($elemX)
    # Assume tables cannot be nested.
    set cellR $attrs(style)
    set lines 0
    foreach p {preamble postamble} {
        if {[llength [find_element $p $attrs(.CHILDREN)]] == 1} {
            incr lines 3
        }
    }
    if {$lines > 5} {
        set lines 5
    }
    set cols {}
    set ttcols [find_element ttcol $attrs(.CHILDREN)]
    foreach ttcol $ttcols {
        catch { array unset cv }
        array set cv [list width ""]
        array set cv $elem($ttcol)
        if {![regexp -- {^0*(|(100|[1-9][0-9]|[0-9])%|[0-9]*\*|[0-9]+em)$} $cv(width)]} {
            unexpected error "invalid width attribute in <ttcol>: $cv(width)"
        }
        lappend cols $cv(width)
    }
    set colmax [llength $cols]
    set children [find_element c $attrs(.CHILDREN)]
    set rowmax [expr [llength $children]/$colmax]
    if {0 && [info exists attrs(.HEIGHT)]} {
        # Would be usable if there was detection
        # of output stability before the last pass.
        incr lines $attrs(.HEIGHT)
    } else {
        incr lines [expr 4 + $rowmax + ($options(.COMPACT) ? 0 : ($rowmax - 1))]
    }
    if {$internal} {
        return $lines
    }
    catch { push_align $attrs(align) }
    set attrs(.COLS) $cols
    set elem($elemX) [array get attrs]
    set colno 0
    set aligns {}
    foreach ttcol $ttcols {
        catch { array unset cv }
        array set cv [list width "" align left .CWIDTH -1]
        array set cv $elem($ttcol)
        set cv(.WIDTH) [lindex $cols $colno]
        if {   [info exists attrs(.CWIDTHS)]
            && [string compare [set cw [lindex $attrs(.CWIDTHS) $colno]] ""]} {
            set cv(.CWIDTH) $cw
        }
        lappend aligns $cv(align)
        set cv(.COLNO) [list [incr colno] $colmax]
        set elem($ttcol) [array get cv]
    }
    set colno 0
    set rowno 1
    foreach c $children {
        catch { array unset cv }
        array set cv $elem($c)
        set cv(.WIDTH) [lindex $cols   $colno]
        set cv(.ALIGN) [lindex $aligns $colno]
        set cv(.ROWNO) [list      $rowno  $rowmax]
        set cv(.COLNO) [list [incr colno] $colmax]
        if {$colno >= $colmax} {
            set colno 0
            incr rowno
        }
        set elem($c) [array get cv]
    }
    texttable_$mode begin $lines $attrs(anchor) $attrs(title)
}
proc pass2end_texttable {elemX} {
    global elem
    global mode
    array set attrs [list anchor "" title "" suppress-title false]
    array set attrs $elem($elemX)
    switch -- [string tolower $attrs(suppress-title)] {
        yes - true - 1 {
            set suppressP 1
        }
        default {
            set suppressP 0
        }
    }
    set rc [texttable_$mode end "" $attrs(anchor) $attrs(title) $suppressP]
    set attrs(.HEIGHT)  [lindex $rc 0]
    set attrs(.CWIDTHS) [lindex $rc 1]
    set elem($elemX) [array get attrs]
    if {[info exists attrs(align)]} {
        pop_align
    }
}
proc pass2begin_ttcol {elemX} {
    global elem
    global mode
    array set attrs [list width "" align left]
    array set attrs $elem($elemX)
    switch -- $attrs(align) {
        left - center - right {}
        default {
            unexpected error \
                "invalid value for align attribute: $attrs(align)"
        }
    }
    ttcol_$mode $attrs(.CTEXT) $attrs(align) $attrs(.COLNO) $attrs(.WIDTH) $attrs(.CWIDTH)
}
proc pass2begin_c {elemX} {
    global elem
    global mode
    array set attrs $elem($elemX)
    c_$mode begin $attrs(.ROWNO) $attrs(.COLNO) $attrs(.ALIGN) $attrs(.WIDTH)
}
proc pass2end_c {elemX} {
    global elem
    global mode
    array set attrs $elem($elemX)
    c_$mode end $attrs(.ROWNO) $attrs(.COLNO) $attrs(.ALIGN) $attrs(.WIDTH)
}
# the xref element
proc pass2begin_xref {elemX} {
    global elem xref
    global mode
    # pageno is ignored for now...
    array set attrs [list pageno false format default]
    array set attrs $elem($elemX)
    set anchor $attrs(target)
    if {![info exists xref($anchor)]} {
        return -code error "Can't resolve xref target $anchor"
    }
    xref_$mode $attrs(.CTEXT) $xref($anchor) $anchor $attrs(format)
}
# the eref element
proc pass2begin_eref {elemX} {
    global counter elem passno
    global mode
    array set attrs $elem($elemX)
    set t $attrs(target)
    if {$passno == 2} {
        if {![info exists counter(reference)]} {
            set counter(reference) 0
        }
        set c -1
        if {([string first "#" $t] < 0) \
                && ([string compare $attrs(.CTEXT) ""]) \
                && ([string compare $attrs(.CTEXT) $t])} {
            switch -- $mode {
                nr - txt {
                    global erefs
                    foreach {n tn} [array get erefs] {
                        if {![string compare $t $tn]} {
                            set c $n
                            break
                        }
                    }
                    if {$c < 0} {
                        set c [incr counter(reference)]
                    }
                }
            }
        }
        set attrs(.COUNTER) $c
        set elem($elemX) [array get attrs]
    }
    eref_$mode $attrs(.CTEXT) $attrs(.COUNTER) $t
}
# the cref element
proc pass2begin_cref {elemX} {
    global elem
    global mode
    global options
    array set attrs [list anchor "" source ""]
    array set attrs $elem($elemX)
    if {!$options(.COMMENTS)} {
        return
    }
    set text ""
    set attrs(.CTEXT) [string trim $attrs(.CTEXT)]
    while {[set x [string first "\n" $attrs(.CTEXT)]] >= 0} {
        if {$x > 0} {
            append text [string range $attrs(.CTEXT) 0 [expr $x-1]]
        }
        set attrs(.CTEXT) [string trimleft \
                                  [string range $attrs(.CTEXT) $x end]]
        if {[string length $attrs(.CTEXT)] > 0} {
            append text " "
        }
    }
    append text $attrs(.CTEXT)
    cref_$mode $text $attrs(.COUNTER) $attrs(source) $attrs(anchor)
}
proc cref_title {elemX} {
    global elem
    array set attrs [list anchor "" source ""]
    array set attrs $elem($elemX)
    return $attrs(.CTEXT)
}
# the iref element
proc pass2begin_iref {elemX} {
    global elem
    global mode
    array set attrs [list subitem "" primary false]
    array set attrs $elem($elemX)
    set flags [list primary $attrs(primary)]
    unset attrs(primary)
    set attrs(flags) $flags
    set attrs(.ANCHOR) [iref_$mode $attrs(item) $attrs(subitem) $flags]
    set elem($elemX) [array get attrs]
}
# the vspace element
proc pass2begin_vspace {elemX} {
    global elem
    global mode
    array set attrs [list blankLines 0]
    array set attrs $elem($elemX)
    set elem($elemX) [array get attrs]
    vspace_$mode $attrs(blankLines)
}
# the spanx element
proc pass2begin_spanx {elemX} {
    global elem
    global mode
    array set attrs [list style emph]
    array set attrs $elem($elemX)
    set elem($elemX) [array get attrs]
    spanx_$mode $attrs(.CTEXT) $attrs(style)
}
# the references/reference elements
# we intercept the back element so we can put the Author's addresses
# after the References section (if any) and before any Appendices
proc pass2begin_back {elemX} {
    global elem
    global mode
    global crefs erefs
    global options
    global erefP backP
    array set attrs $elem($elemX)
    set backP 1
    set children [find_element references $attrs(.CHILDREN)]
    set erefP [expr [llength $children] == 1]
    # Compute width over all references, not just per-section.
    set width 0
    foreach child $children {
        array set references $elem($child)
        set refchildren [find_element reference $references(.CHILDREN)]
        foreach refchild $refchildren {
            array set x $elem($refchild)
            if {[set y [string length $x(.COUNTER)]] > $width} {
                set width $y
            }
            unset x
        }
    }
    foreach child $children {
        array set references $elem($child)
        set refchildren [find_element reference $references(.CHILDREN)]
        foreach refchild $refchildren {
            array set x $elem($refchild)
            set x(.WIDTH) $width
            set elem($refchild) [array get x]
            unset x
        }
    }
}
proc pass2middle_back {} {
    global mode
    global crefs erefs
    global options
    global erefP backP
    if {!$backP} {
        return
    }
    if {!$erefP && [array size erefs] > 0} {
        erefs_$mode URIs
    }
    if {!$options(.INLINE) && [array size crefs] > 0} {
        crefs_$mode "Editorial Comments"
    }
    back_$mode
    set backP 0
}
proc pass2end_back {elemX} {
    pass2middle_back
}
proc pass2end_references {elemX} {
    global elem
    global mode
    global options
    global erefP
    array set attrs [list title References]
    array set attrs $elem($elemX)
    set prefix $attrs(.COUNTER)
    append prefix .
    set attrs(.ANCHOR) [references_$mode begin $prefix $attrs(title)]
    set elem($elemX) [array get attrs]
    set children [find_element reference $attrs(.CHILDREN)]
    if {$options(.SORTREFS)} {
        set children [lsort -command sort_references $children]
    }
    foreach child $children {
        pass2end_reference $child
    }
    references_$mode end $erefP
}
proc sort_references {elemX elemY} {
    global elem
    global options
    array set attrX $elem($elemX)
    array set attrY $elem($elemY)
    if {$options(.SYMREFS)} {
        return [string compare $attrX(anchor) $attrY(anchor)]
    } else {
        return [expr $attrX(.COUNTER) - $attrY(.COUNTER)]
    }
}
proc pass2begin_reference {elemX} {
    global elem
    global mode
    array set attrs [list anchor "" target "" target2 ""]
    array set attrs $elem($elemX)
    set attrs(.ANNOTATIONS) {}
    set elem($elemX) [array get attrs]
}
proc pass2end_reference {elemX} {
    global elem
    global mode
    array set attrs $elem($elemX)
    set front [find_element front $attrs(.CHILDREN)]
    array set fv $elem($front)
    set names [ref_names $elemX]
    set title [ref_title $elemX]
    set series ""
    foreach child [find_element seriesInfo $attrs(.CHILDREN)] {
        # backwards-compatibility... (the attributes are actually mandatory)
        catch { array unset sv }
        array set sv $elem($child)
        if {([info exists sv(name)]) && ([info exists sv(value)])} {
            lappend series "$sv(name) $sv(value)"
        } else {
            lappend series $sv(.CTEXT)
        }
    }
    set formats {}
    foreach child [find_element format $attrs(.CHILDREN)] {
        lappend formats $elem($child)
    }
    set date [ref_date $elemX]
    reference_$mode $attrs(.COUNTER) $names $title $series $formats $date \
                    $attrs(anchor) $attrs(target) $attrs(target2) $attrs(.WIDTH) \
                    $attrs(.ANNOTATIONS)
}
proc ref_names {elemX} {
    global elem
    array set attrs [list anchor "" target "" target2 ""]
    array set attrs $elem($elemX)
    set front [find_element front $attrs(.CHILDREN)]
    array set fv $elem($front)
    set childN [llength [set children [find_element author $fv(.CHILDREN)]]]
    set childA 0
    set names {}
    foreach child [find_element author $fv(.CHILDREN)] {
        incr childA
        array set av [list initials "" surname "" fullname "" role ""]
        array set av $elem($child)
        set organization [find_element organization $av(.CHILDREN)]
        array set ov [list .CTEXT "" abbrev ""]
        if {[string compare $organization ""]} {
            array set ov $elem($organization)
            if {![string compare $ov(abbrev) ""]} {
                set ov(abbrev) $ov(.CTEXT)
            }
        }
        set mref ""
        set uref ""
        set address [find_element address $av(.CHILDREN)]
        if {[llength $address] == 1} {
            array set bv $elem($address)
            foreach {k v p} {email mref mailto: uri uref ""} {
                set u [find_element $k $bv(.CHILDREN)]
                if {[llength $u] == 1} {
                    catch { array unset uv }
                    array set uv $elem($u)
                    set $v $p$uv(.CTEXT)
                }
            }
        }
        if {![string compare $mref ""]} {
            set mref $uref
        } elseif {![string compare $uref ""]} {
            set uref $mref
        }
        if {[string compare $av(initials) ""]} {
            set av(initials) [lindex [split $av(initials) .] 0].
        }
        if {($childA > 1) && ($childA == $childN)} {
            set av(abbrev) [string trimleft "$av(initials) $av(surname)"]
        } elseif {[string compare $av(initials) ""]} {
            set av(abbrev) "$av(surname), $av(initials)"
        } else {
            set av(abbrev) $av(surname)
        }
        if {[string length $av(abbrev)] == 0} {
            lappend names [list $ov(.CTEXT) $uref]
        } else {
            if {![string compare $av(role) editor]} {
                append av(abbrev) ", Ed."
            }
            lappend names [list $av(abbrev) $mref]
        }
    }
    set hack $names
    set names {}
    foreach name $hack {
        if {[string compare [lindex $name 0] ""]} {
            lappend names $name
        }
    }
    return $names
}
proc ref_title {elemX} {
    global elem
    array set attrs [list anchor "" target "" target2 ""]
    array set attrs $elem($elemX)
    set front [find_element front $attrs(.CHILDREN)]
    array set fv $elem($front)
    set title [find_element title $fv(.CHILDREN)]
    array set tv [list abbrev ""]
    array set tv $elem($title)
    return $tv(.CTEXT)
}
proc ref_date {elemX} {
    global elem
    array set attrs [list anchor "" target "" target2 ""]
    array set attrs $elem($elemX)
    set front [find_element front $attrs(.CHILDREN)]
    array set fv $elem($front)
    set date [find_element date $fv(.CHILDREN)]
    array set dv [list year "" month ""]
    if {[catch { array set dv $elem($date) }]} {
        return ""
    }
    if {[string compare $dv(month) ""]} {
        set date "$dv(month) $dv(year)"
    } else {
        set date $dv(year)
    }
    return $date
}
proc pass2begin_annotation {elemX} {
    global mode
    annotation_$mode begin
}
proc pass2end_annotation {elemX} {
    global elem stack
    global mode
    set frame [lindex $stack end]
    array set av [lrange $frame 1 end]
    set elemY $av(elemN)
    unset av
    array set av $elem($elemY)
    lappend av(.ANNOTATIONS) [annotation_$mode end]
    set elem($elemY) [array get av]
}
#       }}}2 Remaining pass 2 (and subsequent) stuff
#       {{{2 Utility functions
proc find_element {name children} {
    global elem
    set result ""
    foreach child $children {
        array set attrs $elem($child)
        if {![string compare $attrs(.NAME) $name]} {
            lappend result $child
        }
    }
    return $result
}
# could use "lsearch -glob" followed by a "string compare", but there are
# some amusing corner cases with that...
proc lsearch0 {list exact {y 0}} {
    set x 0
    foreach elem $list {
        if {$x >= $y && ![string compare [lindex $elem 0] $exact]} {
            return $x
        }
        incr x
    }
    return -1
}
proc llast0 {list exact} {
    set x [llength $list]
    while {$x > 0} {
        set elem [lindex $list [incr x -1]]
        if {![string compare [lindex $elem 0] $exact]} {
            return $x
        }
    }
    return -1
}
#       }}}2 Utility functions
#   }}}1 XML linkage
#   {{{1 Rendering engines
#       {{{2 Page model for both the txt and nr rendering engines
#
# Each line has at most 72 columns from the left edge, including any
# left margin, but excluding the line terminator.  Every output character
# is from the ASCII repertoire and the only control character used is
# the line-feed (LF); the character-tabulation (HT) character is never
# used.
#
# Each page has the following lines (0-based lineno variable):
#    0:  header line (blank line on first page)
#    1:  blank line
#    2:  blank line
#    3:  1st line of content
#   ...
#   50:  48th line of content
#   51:  blank line
#   52:  blank line
#   53:  blank line
#   54:  footer line
#   55:  form-feed (FF) character (followed by line terminator)
# Once processed through nroff and the fix.sh script (from
# 2-nroff.template), the nr output differs from this in two ways. It
# has three extra blank lines (that could be numbered -3, -2, and -1,
# for a total of six) at the very beginning of the document (so the first
# page is that much longer). It also has no line terminator following the
# very last form-feed character of the file. These differences originate
# in the design of the fix.sh script.
#
# Header and footer lines each have three parts:  left, center, and right.
#
# Output line numbers, when reported to the user, should be 1-based.
#
global page_width
set page_width 72
# Head/foot height = 1-line header/footer + blank lines (excluding FF line)
global page_head_height page_body_height page_foot_height
set page_head_height  3
set page_body_height 48
set page_foot_height  4
global page_basic_indent
set page_basic_indent 3
global center_fill_width
set center_fill_width 2
global max_ref_width
set max_ref_width 7
#       }}}2 Page model for both the txt and nr rendering engines
#       {{{2 txt rendering engine
proc rfc_txt {irefs authors iprstmt copying newP validity} {
    global options copyrightP iprP
    global funding
    global pageno
    global indexpg
    global page_basic_indent
    if {[llength $irefs] > 0} {
        if {!$options(.COMPACT) || ![have_lines 4]} {
            end_page_txt
        } else {
            write_line_txt ""
        }
        if {!$options(.RFCEDSTYLE)} {
            write_line_txt "" -1
        }
        set indexpg $pageno
        write_line_txt "Index"
        push_indent 9
        foreach iref $irefs {
            foreach {L item subitem flags pages} $iref { break }
            if {[string compare $L ""]} {
                write_line_txt ""
                push_indent -9
                write_text_txt $L
                flush_text
                pop_indent
            }
            set subitem [chars_expand $subitem]
            if {[string compare $item ""]} {
                push_indent -6
                write_text_txt [chars_expand $item]
                if {[string compare $subitem ""]} {
                    flush_text
                    pop_indent
                    push_indent [expr -($page_basic_indent)]
                    write_text_txt $subitem
                }
            } else {
                push_indent [expr -($page_basic_indent)]
                write_text_txt $subitem
            }
            pop_indent
            write_text_txt "  [collapsed_num_list $pages]"
            flush_text
        }
        pop_indent
    }
    authors_txt $authors
    if {(!$options(.PRIVATE)) && $copyrightP > 0} {
        end_page_txt
        if {!$options(.RFCEDSTYLE)} {
            write_line_txt "" -1
        }
        set result $pageno
        # There isn't really an authoritative source for the order of
        # the next few paragraphs or the names of the headings under
        # which they are put.  But what's used here corresponds to what
        # can be found in the in-notes/rfc-editor/boilerplate*.txt files.
        if {0 && $newP} {
            write_line_txt "Copyright Statement"
        } else {
            if {$newP < 3} {
                write_line_txt "Full Copyright Statement"
            }
        }
        foreach para $copying {
            write_line_txt ""
            pcdata_txt $para
        }
        if {$newP && $newP < 3} {
            #if {![have_lines 4]} {
            #    end_page_txt
            #}
            #write_line_txt "Disclaimer of Validity"
            foreach para $validity {
                write_line_txt ""
                pcdata_txt $para
            }
        }
        write_line_txt "" -1
        if {!$options(.RFCEDSTYLE)} {
            write_line_txt "" -1
        }
        if {$iprP} {
            global iprurl ipremail
            if {![have_lines 4]} {
                end_page_txt
            }
            write_line_txt "Intellectual Property"
            regsub -all -- %IPRURL% $iprstmt $iprurl iprstmt
            regsub -all -- %IPREMAIL% $iprstmt $ipremail iprstmt
            foreach para $iprstmt {
                write_line_txt ""
                pcdata_txt $para
            }
            write_line_txt "" -1
            if {!$options(.RFCEDSTYLE)} {
                write_line_txt "" -1
            }
        }
        if {![have_lines 4]} {
            end_page_txt
        }
        if {$options(.RFCEDSTYLE)} {
            set ack "Acknowledgement"
        } else {
            set ack "Acknowledgment"
        }
        set acks 0
        if {[string length $funding]} {
            incr acks 1
        }
        if {$options(.RFCPROCACK)} {
            incr acks 1
        }
        if {$acks > 1} {
            append ack s
        }
        if {$acks} {
            write_line_txt $ack
            write_line_txt ""
        }
        if {[string length $funding]} {
            pcdata_txt $funding
        }
        if {$options(.RFCPROCACK)} {
            global prog_ack prog_url
            regsub -all -- %PROGURL% $prog_ack $prog_url xml2rfc_ack
            if {[string length $funding]} {
                pcdata_txt "  "
            }
            pcdata_txt $xml2rfc_ack
        }
    } else {
        set result ""
    }
    end_page_txt
    return $result
}
proc front_txt_begin {left right top bottom title keywords lang} {
    global options copyrightP
    global header footer lineno pageno blankP
    global eatP
    global passno indexpg authorspg
    global indent
    global page_width page_basic_indent
    set header [three_parts $top]
    set footer [string trimright [three_parts $bottom]]
    write_it ""
    set lineno 1
    set pageno 1
    set blankP 1
    set eatP 0
    if {$passno == 2} {
        set indexpg 0
        set authorspg 0
    }
    for {set i 0} {$i < 2} {incr i} {
        write_line_txt "" -1
    }
    set indent 0
    if {$options(.TOPBLOCK)} {
        set left [munge_long $left]
        set right [munge_long $right]
        foreach l $left r $right {
            set l [chars_expand $l]
            set r [chars_expand $r]
            set len [expr $page_width - [string length $l]]
            write_line_txt [format %s%*.*s $l $len $len $r]
        }
        write_line_txt "" -1
        write_line_txt "" -1
    }
    foreach line $title {
        write_text_txt [chars_expand $line] c
    }
    write_line_txt "" -1
    set indent $page_basic_indent
}
proc write_status_txt {status copying afterP} {
    global options copyrightP iprP
    if {$afterP} {
        write_line_txt "" -1
    }
    if {!$options(.PRIVATE)} {
        if {$options(.RFCEDSTYLE)} {
            write_line_txt "Status of This Memo"
        } else {
            write_line_txt "Status of this Memo"
        }
        foreach para $status {
            write_line_txt ""
            pcdata_txt $para
        }
    }
    if {(!$options(.PRIVATE)) && $copyrightP && [string length $copying]} {
        write_line_txt "" -1
        write_line_txt "Copyright Notice"
        foreach para $copying {
            write_line_txt "" -1
            pcdata_txt $para
        }
    }
}
proc three_parts {stuff} {
    global page_width center_fill_width
    set result [nbsp_expand_txt [chars_expand [lindex $stuff 0]]]
    set len [string length $result]
    set text [nbsp_expand_txt [chars_expand [lindex $stuff 1]]]
    set len [expr ($page_width - [string length $text] + 1) / 2 - $len]
    if {$len < $center_fill_width} {
        set len $center_fill_width
    }
    append result [format %*s%s $len "" $text]
    set len [string length [set text [nbsp_expand_txt [chars_expand [lindex $stuff 2]]]]]
    set len [expr ($page_width - [string length $result]) - $len]
    append result [format %*s%s $len "" $text]
    return $result
}
proc front_txt_end {toc} {
    global options
    global mode
    global unpaginated
    global lineno
    global page_width page_head_height page_body_height page_basic_indent
    if {$options(.TOC)} {
        if {   (![have_lines [expr [llength $toc] + 3]])
            || (!$options(.RFCEDSTYLE) && ($lineno >= $page_head_height + $page_body_height / 3))} {
            end_page_$mode
        } else {
            write_line_$mode ""
        }
        if {!$options(.RFCEDSTYLE)} {
            write_line_$mode "" -1
        }
        if {![string compare $mode nr]} {
            global indents
            condwrite_in_nr 0 1
            set indents {}
        }
        write_line_$mode "Table of Contents"
        write_line_$mode "" -1
        if {![string compare $mode nr]} {
            condwrite_nf_nr
        }
        set len1 0
        set len2 0
        foreach c $toc {
            set label [lindex $c 1]
            if {[string compare $label ""]} {
                set x [string length $label]
                set y [lindex $c 0]
                if {$y == -1} {
                    if {$options(.TOCAPPENDIX)} {
                        incr x 9
                    }
                    if {!$options(.TOCINDENT)} {
                        set y 0
                    }
                }
                if {[info exists a($y)]} {
                    if {$x >= $a($y)} {
                        set a($y) [expr $x + 1]
                    }
                } else {
                    set a($y) [expr $x + 2]
                }
                if {$a($y) > $len1} {
                    set len1 $a($y)
                }
            }
            if {!$unpaginated && [set x [string length [lindex $c 3]]] > $len2} {
                set len2 $x
            }
        }
        set len3 [expr 5 - $len2]
        if {$len3 < 0} {
            set len3 0
        }
        set len2 5
        set mid [expr ($page_width - 4) - ($len1 + $len2)]
        set lenX $len1
        set midX $mid
        set z 0
        set s0 [format "%*s" $page_basic_indent ""]
        foreach c $toc {
            set label [lindex $c 1]
            if {   !$options(.TOCOMPACT)
                && [lindex $c 0] <= 0} {
                set z1 [expr [string compare $label ""] ? 1 : 2]
                if {$z && ($z == 1 || $z1 == 1)} {
                    write_line_$mode ""
                }
                set z $z1
            }
            if {   !$options(.TOCOMPACT)
                && [lindex $c 0] == 0
                && [string compare $label ""]} {
            }
            set y [lindex $c 0]
            if {$y == -1 && $options(.TOCAPPENDIX)} {
                set label "Appendix $label"
            }
            if {$options(.TOCINDENT)} {
                if {[string compare $label ""]} {
                    set len1 $a($y)
                    set x 0
                    while {[incr y -1] >= 0} {
                        incr x [expr $options(.TOCNARROW) ? 2 : $a($y)]
                    }
                    set label [format "%*s" $x ""]$label
                    incr len1 $x
                } else {
                    set len1 0
                }
                set mid [expr $midX + $lenX - $len1]
            }
            set s1 [format "%-*.*s" $len1 $len1 $label]
            set s2 [format " %*.*s" $len2 $len2 [lindex $c 3]]
            set title [chars_expand [string trim [lindex $c 2]]]
            while {[string length $title] > $mid} {
                set phrase [string range $title 0 [expr $mid - 1]]
                if {[set x [string last " " $phrase]] < 0} {
                    if {[set x [string first " " $title]] < 0} {
                        break
                    }
                }
                write_toc_$mode $s0$s1 [string range $title 0 [expr $x - 1]] \
                        [format " %*s" $len2 ""] $mid 0
                set s1 [format "%*s" $len1 ""]
                set title [string trimleft [string range $title $x end]]
            }
            if {$len3 > 0} {
                set s2 [string range $s2 $len3 end]
            }
            write_toc_$mode $s0$s1 $title $s2 [expr $mid + $len3] 1
        }
    }
    if {$options(.TOC) || !$options(.COMPACT)} {
        end_page_$mode
    }
}
proc write_toc_txt {s1 title s2 len dot} {
    global mode unpaginated
    set x [string length $title]
    if {$unpaginated} {
        set len $x
        set s2 ""
    } elseif {$dot && ($x < $len)} {
        if {($len - $x) & 1} {
            append title " "
            incr x
        }
        while {$x < $len} {
            append title " ."
            incr x 2
        }
    }
    write_line_$mode [format "%s%-*.*s%s" $s1 $len $len $title $s2]
}
proc abstract_txt {} {
    global options
    if {(!$options(.COMPACT) && !$options(.ABSTRACT1ST)) || ![have_lines 4]} {
        end_page_txt
    } else {
        write_line_txt ""
    }
    write_line_txt "Abstract"
    write_line_txt "" -1
}
proc note_txt {title depth} {
    global options
    if {!$options(.COMPACT) || ![have_lines 4]} {
        end_page_txt
    } else {
        write_line_txt ""
    }
    write_line_txt [chars_expand $title]
    write_line_txt "" -1
}
proc section_txt {prefix top title lines anchor} {
    global options
    global pageno
    global page_basic_indent
    if {($top && !$options(.COMPACT)) || (![have_lines [expr $lines + 2]])} {
        end_page_txt
    } else {
        write_line_txt ""
    }
    if {$top && !$options(.RFCEDSTYLE)} {
        write_line_txt "" -1
    }
    push_indent [expr -($page_basic_indent)]
    write_text_txt "$prefix  "
    push_indent [expr [string length $prefix] + 2]
    write_text_txt [chars_expand $title]
    flush_text
    pop_indent
    pop_indent
    return $pageno
}
proc t_txt {tag counter style hangText editNo} {
    global options
    global eatP
    global mode
    if {$eatP < 0} {
        set eatP 1
    }
    if {![string compare $tag end]} {
        return
    }
    if {[string compare $counter ""]} {
        set pos [pop_indent]
        set l [split $counter .]
        set left -1
        set lines 3
        switch -- $style {
            letters {
                set counter [offset2letters [lindex $l end] [llength $l]]
                append counter "."
            }
            numbers {
                set counter "[lindex $l end]."
            }
            symbols {
                set counter "[lindex { - o * + } [expr [llength $l] & 3]] "
            }
            hanging {
                global page_basic_indent
                set counter [chars_expand $hangText]
                set x [string length $counter]
                if {[set x [string length $counter]]} {
                    if {$x >= $pos} {
                        # Prevent two_spaces from kicking in.
                        append counter "\xA0"
                    }
                    append counter " "
                }
                if {$pos <= $page_basic_indent} {
                    set left ""
                } else {
                    set left -1
                }
                set lines 5
            }
            default {
                set counter "  "
                set left -2
            }
        }
        if {![have_lines $lines]} {
            end_page_$mode
        }
        if {$options(.EDITING)} {
            write_editno_$mode $editNo
        } elseif {!$options(.SUBCOMPACT)} {
            write_line_$mode ""
        }
        set c [format "%-[expr $pos-0]s" $counter]
        switch -- $mode {
            txt {
                write_text_txt $c
            }
            nr {
                indent_text_nr $c $left
                pop_indent
            }
        }
        push_indent $pos
    } else {
        if {$options(.EDITING)} {
            write_editno_$mode $editNo
        } else {
            write_line_$mode ""
        }
    }
    set eatP 1
}
proc offset2letters {offset {depth 0}} {
    set alpha "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    set letters ""
    for {} {$offset > 0} {set offset [expr $offset / 26]} {
        incr offset -1
        set letters [string index $alpha [expr $offset % 26]]$letters
    }
    if {$depth & 1} {
        set letters [string tolower $letters]
    }
    return $letters
}
proc offset2romans {offset {depth 0}} {
    if {$offset <= -5000 || $offset == 0 || $offset >= 5000} {
        # You've been silently upgraded.
        return [expr $offset]
    } elseif {$offset < 0} {
        set offset [expr -($offset)]
        set sign -
    } else {
        set sign ""
    }
    set r {{"" I II III IV V VI VII VIII IX}
           {"" X XX XXX XL L LX LXX LXXX XC}
           {"" C CC CCC CD D DC DCC DCCC CM}}
    set romans ""
    for {set d 0} {$d < 3 && $offset} {incr d; set offset [expr $offset / 10]} {
        set romans [lindex [lindex $r $d] [expr $offset % 10]]$romans
    }
    if {$offset} {
        # This could be a really long string, were it not for the limit above.
        set romans [string repeat M $offset]$romans
    }
    if {$depth & 1} {
        set romans [string tolower $romans]
    }
    return $sign$romans
}
proc list_txt {tag min max style hangIndent longestHangText suprT} {
    global options
    global eatP
    global mode
    switch -- $tag {
        begin {
            switch -- $style {
                letters {
                    set i [expr [string length [offset2letters $max]] + 1]
                }
                numbers {
                    set i [expr [string length $max] + 1]
                }
                format {
                    set i [string length [chars_expand $longestHangText]]
                }
                default { set i 1 }
            }
            if {[incr i 2] > $hangIndent} {
                push_indent $i
            } else {
                push_indent [expr $hangIndent]
            }
        }
        end {
            flush_text
            if {!$options(.SUBCOMPACT)} {
                write_line_$mode ""
            }
            pop_indent
            set eatP 1
            switch -- $mode {
                nr {
                    global indent
                    condwrite_in_nr $indent
                }
            }
        }
    }
}
proc figure_txt {tag lines anchor title av {suppressP 0}} {
    global xref
    global page_width page_basic_indent
    global eatP
    global mode
    switch -- $tag {
        begin {
            if {[string compare $anchor ""]} {
                array set av2 $xref($anchor)
                set x [string length $av2(value)]
                incr x 7
                if {[string compare $title ""]} {
                    incr x [string length [chars_expand $title]]
                    incr x 2
                }
                # Approximation based on a line length of 69 with a
                # weighted average of half-word lengths of 3.7 (4).
                set y [expr $page_width - $page_basic_indent - 4]
                incr lines [expr 1 + ($x + $y - 1) / $y]
            }
            if {![have_lines $lines]} {
                end_page_$mode
            }
            flush_text
        }
        end {
            set eatP 1
            if {[string compare $anchor ""]} {
                array set av2 $xref($anchor)
                set prefix "Figure\xA0$av2(value)"
                if {[string compare $title ""]} {
                    set title "$prefix: [chars_expand $title]"
                } elseif {!$suppressP} {
                    set title $prefix
                }
            }
            if {[string compare $title ""]} {
                write_line_$mode ""
                write_text_$mode $title c
                write_line_$mode ""
            }
        }
    }
}
proc artwork_txt {tag lines {av {}} } {
    global mode
    switch -- $tag {
        begin {
            # This was done for the whole figure, but let's
            # try it for the artwork alone, just in case.
            if {![have_lines $lines]} {
                end_page_$mode
            }
        }
    }
}
proc preamble_txt {tag {editNo ""}} {
    global options
    global eatP
    global mode
    switch -- $tag {
        begin {
            set eatP 1
            if {$options(.EDITING)} {
                write_editno_$mode $editNo
            } else {
                write_line_$mode ""
            }
        }
    }
}
proc postamble_txt {tag {editNo ""}} {
    global options
    global eatP
    global mode
    switch -- $tag {
        begin {
            cellE
            set eatP 1
            if {$options(.EDITING)} {
                write_editno_$mode $editNo
            }
        }
    }
}
proc texttable_txt {tag lines anchor title {suppressP 0}} {
    global xref
    global page_width page_basic_indent
    global eatP
    global mode
    global cellH cellK
    switch -- $tag {
        begin {
            if {[string compare $anchor ""]} {
                array set av $xref($anchor)
                set x [string length $av(value)]
                incr x 6
                if {[string compare $title ""]} {
                    incr x [string length [chars_expand $title]]
                    incr x 2
                }
                # Approximation based on a line length of 69 with a
                # weighted average of half-word lengths of 3.7 (4).
                set y [expr $page_width - $page_basic_indent - 4]
                incr lines [expr 1 + ($x + $y - 1) / $y]
            }
            if {![have_lines $lines]} {
                end_page_$mode
            }
            flush_text
            cellB
        }
        end {
            cellE
            set eatP 1
            if {[string compare $anchor ""]} {
                array set av $xref($anchor)
                set prefix "Table\xA0$av(value)"
                if {[string compare $title ""]} {
                    set title "$prefix: [chars_expand $title]"
                } elseif {!$suppressP} {
                    set title $prefix
                }
            }
            if {[string compare $title ""]} {
                write_line_$mode ""
                write_text_$mode $title c
                write_line_$mode ""
            }
        }
    }
    return [list $cellH $cellK]
}
proc ttcol_txt {text align col width cwidth} {
    cellP $text 0 [lindex $col 0] $width $cwidth $align
}
proc c_txt {tag row col align width} {
    switch -- $tag {
        begin { cellP "" [lindex $row 0] [lindex $col 0] }
    }
}
proc cellB {} {
    global cellH cellK
    set cellH 0
    set cellK {}
}
proc cellE {} {
    global options
    global mode
    global cells cellR cellH cellK
    global page_width page_basic_indent
    if {[llength [array names cells]] == 0} {
        return
    }
    if {![string compare $cellR all]} {
        set rowsepP 1
        set cellR full
    } else {
        set rowsepP 0
    }
    # Assess space taken by table frame.
    set num_rows $cells(maxrow)
    set num_cols $cells(maxcol)
    switch -- $cellR {
        none - headers { set overhead [expr     $num_cols - 1] }
        full           { set overhead [expr 3 * $num_cols + 1] }
    }
    incr overhead $page_basic_indent
    set avail [expr $page_width - $overhead]
    set left_margin [current_align_bias]
    switch -- [current_align] {
        left {
            if {$left_margin < 0} {
                if {$left_margin < -($page_basic_indent)} {
                    set left_margin [expr -($page_basic_indent)]
                }
                incr avail [expr -($left_margin)]
            }
        }
    }
    if {$avail < 0} {
        unexpected error "too many <ttcol>s to even build <texttable> frame"
    }
    # Compute basic statistics on the data.
    set min {}
    set max {}
    set specs $cells(width)
    foreach col $specs {
        lappend min 0
        lappend max 0
    }
    for {set i 0} {$i <= $num_rows} {incr i} {
        for {set j 1} {$j <= $num_cols} {incr j} {
            if {![info exists cells($i,$j)]} {
                set data ""
            } else {
                set data [two_spaces $cells($i,$j) 1]
            }
            set cells($i,$j) $data
            set x [string length $data]
            set y [expr $j - 1]
            if {$x > [lindex $max $y]} {
                set max [lreplace $max $y $y $x]
            }
            set z 0
            foreach word [split $data] {
                set x [string length $word]
                if {$x > $z} {
                    set z $x
                }
            }
            if {$z > [lindex $min $y]} {
                set min [lreplace $min $y $y $z]
            }
        }
    }
    set max_width [sum_list $max]
    set min_width [sum_list $min]
    set inf {}
    set inf_width 0
    foreach col $min {
        set col [expr $col != 0]
        lappend inf $col
        incr inf_width $col
    }
    if {$avail < $inf_width} {
        unexpected error "too many non-empty columns in <texttable> to fit in page width"
    }
    # Translate width specs given available space.
    set cols {}
    set rel_total 0
    set unspec {}
    foreach col $specs {
        # What to do with the unspecified ones is touchy.
        set u 0
        switch -- $col {
            {}      { set x [lindex $min [llength $cols]]; set u 1 }
            *       { incr rel_total [set x -1] }
            default {
                regexp -- {^0*([0-9]+)(|em|[%*])$} $col x num units
                switch -- $units {
                    em      { set x $num }
                    %       { set x [expr ($num * $avail + 99) / 100]}
                    *       { incr rel_total [set x [expr -($num)]] }
                    default { set x 0 }
                }
            }
        }
        lappend cols $x
        lappend unspec $u
    }
    set specs $cols
    # Compute final cell widths (and their total).
    set width $avail
    if {$avail == $min_width} {
        set cols $min
    } elseif {$avail == $inf_width} {
        set cols $inf
    } elseif {$avail < $min_width} {
        unexpected warning "so many <ttcol>s in <texttable> that some words need to be split"
        set excess [expr $min_width - $avail]
        # First, try the mins that are greater than their specs.
        set tol {}
        set tol_width 0
        set fnum [expr ($rel_total > 0) ? 1000 : 0]
        set fden 1
        foreach s $specs n $min {
            set t 0
            if {$s >= 0} {
                incr s [expr $s == 0]
                set y [expr $n - $s]
                if {$y > 0} {
                    set t $y
                }
            } elseif {$fnum > 0} {
                # Prepare in case we need to try the relative widths.
                incr n -1
                set s [expr -($s)]
                # We keep the smallest acceptable factor to all as a mixed number.
                if {$n <= 0} {
                    set fnum 0
                } elseif {$n * $fden < $s * $fnum} {
                    set fnum $n
                    set fden $s
                }
            }
            lappend tol $t
            incr tol_width $t
        }
        foreach {excess cols} [shave_cols_excess $min $excess $tol $tol_width] {break}
        # Second, try the unspecified widths.
        if {$excess > 0} {
            set tol {}
            set tol_width 0
            foreach w $cols u $unspec {
                set t [expr ($u && $w > 0) ? ($w - 1) : 0]
                lappend tol $t
                incr tol_width $t
            }
            foreach {excess cols} [shave_cols_excess $cols $excess $tol $tol_width] {break}
        }
        # Third, try the relative widths (to shrink, not expand).
        if {$excess > 0 && $fnum > 0} {
            if {$excess * $fden < $rel_total * $fnum} {
                set fnum $excess
                set fden $rel_total
            }
            set tol {}
            set tol_width 0
            foreach s $specs {
                set t [expr ($s < 0) ? (($fnum * -($s)) / $fden) : 0]
                lappend tol $t
                incr tol_width $t
            }
            foreach {excess cols} [shave_cols_excess $cols $excess $tol $tol_width] {break}
        }
        # Finally, try anything that's left, leaving as little as one column.
        # Start with largest.
        set p 1
        foreach w $cols {
            if {$w > $p} {
                set p $w
            }
        }
        while {$excess > 0} {
            if {$p == 1} {
                unexpected error "bug in reducing <texttable> column widths"
            }
            # Find second largest.
            set q 1
            foreach w $cols {
                if {$w > $q && $w < $p} {
                    set q $w
                }
            }
            set tol {}
            set tol_width 0
            foreach w $cols {
                set t [expr ($w > $q) ? ($w - $q) : 0]
                lappend tol $t
                incr tol_width $t
            }
            foreach {excess cols} [shave_cols_excess $cols $excess $tol $tol_width] {break}
            set p $q
        }
    } else {
        # There is room beyond minimum space.
        # First, try to give everyone what they want or need.
        #   min + specs + max(all)
        set cols {}
        set cols_width 0
        # min + specs
        set mnsa {}
        set mnsa_width 0
        # min + specs + max(rel)
        set mnsb {}
        set mnsb_width 0
        # min + specs + max(rel + unspec)
        set mnsc {}
        set mnsc_width 0
        foreach m $max n $min s $specs u $unspec {
            set t $n
            if {$t < $s} {
                set t $s
            }
            lappend mnsa $t
            incr mnsa_width $t
            if {$s < 0} {
                set t $m
            }
            lappend mnsb $t
            incr mnsb_width $t
            if {$u} {
                set t $m
            }
            lappend mnsc $t
            incr mnsc_width $t
            if {$t < $m} {
                set t $m
            }
            lappend cols $t
            incr cols_width $t
        }
        # In decreasing order by width...
        if {$avail >= $cols_width} {
            set width $cols_width
        } elseif {$avail > $mnsc_width} {
            # Partially expand columns with greater maximal width from mnsc.
            set target [expr $avail - $mnsc_width]
            foreach {target cols} [expand_cols_by_height $mnsc $target $cols] {break}
        } elseif {$avail == $mnsc_width} {
            set cols $mnsc
        } elseif {$avail > $mnsb_width} {
            # Partially expand columns with unspecified width from mnsb.
            set target [expr $avail - $mnsb_width]
            foreach {target cols} [expand_cols_by_height $mnsb $target $mnsc] {break}
        } elseif {$avail == $mnsb_width} {
            set cols $mnsb
        } elseif {$avail > $mnsa_width} {
            # Partially expand columns with relative width from mnsa.
            set cols $mnsa
            set target [expr $avail - $mnsa_width]
            while {$target > 0} {
                set rel {}
                set num_rel 0
                set rel_total 0
                set fnum 1000
                set fden 1
                foreach m $max s $specs w $cols {
                    set x 0
                    if {$s < 0} {
                        set d [expr $m - $w]
                        if {$d > 0} {
                            set x [expr -($s)]
                            if {$d * $fden < $x * $fnum} {
                                set fnum $d
                                set fden $x
                            }
                            incr num_rel
                            incr rel_total $x
                        }
                    }
                    lappend rel $x
                }
                if {$target * $fden < $rel_total * $fnum} {
                    set fnum $target
                    set fden $rel_total
                }
                set plus_width 0
                if {$num_rel > 0 && $fnum > 0} {
                    set kols {}
                    foreach r $rel w $cols {
                        set p [expr ($r * $fnum) / $fden]
                        lappend kols [expr $w + $p]
                        incr plus_width $p
                    }
                }
                if {$plus_width > 0} {
                    set cols $kols
                    incr target [expr -($plus_width)]
                } elseif {$num_rel > 0} {
                    set dd $target
                    set kols {}
                    foreach r $rel w $cols {
                        if {$r > 0} {
                            # Prefer expanding the rightmost ones.
                            if {$dd >= $num_rel} {
                                incr w
                                incr target -1
                            }
                            incr dd
                        }
                        lappend kols $w
                    }
                    set cols $kols
                } else {
                    unexpected error "bug in expanding <texttable> columns with relative widths"
                }
            }
        } elseif {$avail == $mnsa_width} {
            set cols $mnsa
        } else {
            # Partially expand columns with greater specified width from min.
            set target [expr $avail - $min_width]
            set plus [subtract_lists $mnsa $min]
            foreach {target cols} [expand_cols $min $target $plus] {break}
        }
    }
    # Adjust $left_margin from $width and current align (for whole table).
    set x [expr $avail - $width]
    switch -- [current_align] {
        left {
            if {$left_margin < 0} {
                set x -1
            }
        }
        center {
            incr left_margin [expr $x / 2]
        }
        right {
            incr left_margin $x
        }
    }
    if {$x >= 0} {
        if {$left_margin > $x} {
            set left_margin $x
        }
        if {$left_margin < 0} {
            set left_margin 0
        }
    }
    incr left_margin $page_basic_indent
    # At this point, we have the $cols list, $num_cols, and $left_margin.
    set prefix [format "%*s" $left_margin ""]
    if {![string compare $mode nr]} {
        condwrite_nf_nr
    }
    # Building blocks.
    switch -- $cellR {
        none    { set vars "0 0 {} { } {} {}  {} { } { }" }
        headers { set vars "0 1 {} { } {} {}  {} { } -  " }
        full    { set vars "1 0 |  |   -  { } +  +   -  " }
    }
    foreach {allP halfP sideC colC sepC padC rowC crxC dashC} $vars {break}
    # Format each cell given final $cols list values.
    set cellK $cols
    foreach cell [array names cells *,*] {
        set column [expr [lindex [split $cell ,] 1] - 1]
        set cells($cell) [cellF $cells($cell) \
                                [lindex $cells(align) $column] \
                                [lindex $cols $column]]
    }
    # Precompute number of lines in each row.
    set row_lines {}
    for {set row 0} {$row <= $num_rows} {incr row} {
        set lines 0
        foreach cell [array name cells $row,*] {
            if {[set x [llength [split $cells($cell) "\n"]]] > $lines} {
                set lines $x
            }
        }
        lappend row_lines $lines
    }
    write_line_$mode ""
    # Attempt to fit header (row 0) and row 1 in same page.
    if {$num_rows >= 1} {
        set lines [lindex $row_lines 0]
        incr lines [expr $allP && $lines > 0]
        incr lines [expr   (   !$options(.COMPACT) \
                            ||  [string compare $cellR none]) \
                         + (   ($num_rows == 1) \
                            && ![string compare $cellR full])]
        incr lines [lindex $row_lines 1]
        if {![have_lines $lines]} {
            end_page_$mode
        }
    }
    # Precompute separator line.
    set hit_image $prefix
    set c $rowC
    foreach col $cols {
        append hit_image "$c$sepC[::textutil::strRepeat $dashC $col]$sepC"
        set c $crxC
    }
    append hit_image $rowC
    if {$rowsepP} {
        # No blank lines - use separator line.
        set blank_image $hit_image
    } else {
        # Precompute blank line.
        set blank_image $prefix
        set c $sideC
        foreach col $cols {
            append blank_image [format "$c$padC%*s$padC" $col ""]
            set c $colC
        }
        append blank_image $sideC
    }
    # Write top line.
    if {$allP && [lindex $row_lines 0] > 0} {
        write_line_$mode $hit_image
        incr cellH
    }
    # Generate each row of cells.
    for {set row 0} {$row <= $num_rows} {incr row} {
        set lines [lindex $row_lines $row]
        set hitP 0
        switch -- $cellR {
            none    { if {$row == 0 && !$options(.COMPACT)} { set hitP 1 } }
            headers { if {$row == 0}                        { set hitP 1 } }
            full    { if {$row == 0 || $row == $num_rows}      { set hitP 1 } }
        }
        if {![is_at_page_start]} {
            set blkP [expr ($row > 1) && (!$options(.COMPACT) || $rowsepP)]
            if {![have_lines [expr $blkP + $lines + $hitP]]} {
                if {$blkP && [have_lines 1]} {
                    # Totally optional.  Only if a line is available.
                    write_line_$mode $blank_image
                }
                end_page_$mode
                if {$rowsepP} {
                    write_line_$mode $blank_image
                }
            } elseif {$blkP} {
                write_line_$mode $blank_image
            }
            incr cellH $blkP
        }
        for {set line 0} {$line < $lines} {incr line} {
            set image $prefix
            set c $sideC
            for {set column 1} {$column <= $num_cols} {incr column} {
                set width [lindex $cols [expr $column - 1]]
                set data [format "%-*.*s" $width $width \
                                 [lindex [split $cells($row,$column) "\n"] \
                                         $line]]
                append image "$c$padC$data$padC"
                set c $colC
            }
            append image $sideC
            write_line_$mode $image
            incr cellH
        }
        if {$hitP} {
            write_line_$mode $hit_image
            incr cellH
        }
    }
    write_line_$mode ""
    unset cells
}
proc shave_cols_excess {cols excess give {give_width -1}} {
    if {$give_width < 0} {
        set give_width [sum_list $give]
    }
    if {$excess <= 0 || $give_width <= 0} {
        # Nothing to do.
    } elseif {$excess >= $give_width} {
        # Take everything; it may still not be enough.
        set cols [subtract_lists $cols $give]
        incr excess [expr -($give_width)]
    } else {
        # Take only what we need, in relative proportion.
        set dd 0
        set kols {}
        foreach c $cols g $give {
            if {$g > 0} {
                set d [expr ($g * $excess) / $give_width]
                incr c [expr -($d)]
                incr dd $d
            }
            lappend kols $c
        }
        incr excess [expr -($dd)]
        # Do the ones we missed because of integer division.
        if {$excess > 0} {
            set cols {}
            foreach k $kols g $give {
                # Prefer shaving the leftmost ones.
                if {$excess > 0 && $g > 0} {
                    incr k -1
                    incr excess -1
                }
                lappend cols $k
            }
        } else {
            set cols $kols
        }
    }
    return [list $excess $cols]
}
proc expand_cols {cols target plus {plus_width -1}} {
    if {$plus_width < 0} {
        set plus_width [sum_list $plus]
    }
    if {$target <= 0 || $plus_width <= 0} {
        # Nothing to do.
    } elseif {$target >= $plus_width} {
        # Take everything; it may still not be enough.
        set cols [add_lists $cols $plus]
        incr target [expr -($plus_width)]
    } else {
        # Take only what we need, in relative proportion.
        set dd 0
        set dr 0
        set kols {}
        foreach c $cols p $plus {
            if {$p > 0} {
                set d [expr ($p * $target) / $plus_width]
                incr c $d
                incr dd $d
                incr dr
            }
            lappend kols $c
        }
        incr target [expr -($dd)]
        # Do the ones we missed because of integer division.
        if {$target > 0} {
            set dd $target
            set cols {}
            foreach k $kols p $plus {
                if {$p > 0} {
                    # Prefer expanding the rightmost ones.
                    if {$dd >= $dr} {
                        incr k
                        incr target -1
                    }
                    incr dd
                }
                lappend cols $k
            }
        } else {
            set cols $kols
        }
    }
    return [list $target $cols]
}
proc expand_cols_by_height {cols target bound} {
    while {$target > 0} {
        set m_width 0
        set w_width 0
        foreach m $bound w $cols {
            if {$m > $w} {
                # Only cover those columns below the bound.
                incr m_width $m
                incr w_width $w
            }
        }
        # This mixed number is the average height we could achieve.
        set fnum $m_width
        set fden [expr $w_width + $target]
        set plus_num 0
        set plus {}
        set plus_width 0
        set kols {}
        foreach m $bound w $cols {
            set p 0
            set k $w
            if {$m > $w} {
                set x [expr $m * $fden]
                set y [expr $w * $fnum]
                # Seek columns of above average height.
                if {$x >= $y} {
                    # Nearly reduce height to average by augmenting width.
                    set p 1
                    # Round height up at this point to avoid overshoot.
                    set k [expr $x / ($fnum + $fden - 1)]
                    if {$k < $w} {
                        # But do no smaller than before.
                        set k $w
                    }
                    if {$k > [expr $w + $target]} {
                        # overshot anyway
                        set k [expr $w + $target]
                    }
                    set q [expr $k - $w]
                    incr plus_num
                    incr plus_width $q
                }
            }
            lappend plus $p
            lappend kols $k
        }
        if {$plus_width > 0} {
            set cols $kols
            incr target [expr -($plus_width)]
        } elseif {$plus_num > 0} {
            # No progress due to integer division.  Make some.
            set dd $target
            set cols {}
            foreach p $plus w $kols {
                if {$p > 0} {
                    # Prefer expanding the rightmost ones.
                    if {$dd >= $plus_num} {
                        incr w
                        incr target -1
                    }
                    incr dd
                }
                lappend cols $w
            }
        } else {
            # Should not happen, but just in case we were given a bad target.
            set cols $kols
            break
        }
    }
    return [list $target $cols]
}
proc cellF {text align width} {
    set text [::textutil::adjust::adjust $text \
                           -justify      $align \
                           -length       $width \
                           -full         true \
                           -strictlength true]
    # ...adjust really needs some work
    set pad [format %*s $width ""]
    while {[string first "$pad\n" $text] == 0} {
        set text [string range $text [expr $width + 1] end]
    }
    # this will work only for left-justified errors...
    if {[set nlines [llength [set lines [split $text "\n"]]]] \
            > 1} {
        set pre ""
        set post ""
        for {set lineno 0} {$lineno < $nlines} {incr lineno} {
            set line $post[lindex $lines $lineno]
            set post ""
            if {[string length $line] > $width} {
                append pre [string range $line 0 [expr $width - 1]]
                set post [string range $line $width end]
            } else {
                append pre $line
            }
            append pre "\n"
        }
        if {[string compare $post ""]} {
            append pre "$post\n"
        }
        set text [string trimright $pre]
    }
    return $text
}
proc cellP {data {row -1} {col -1} {width -1} {cwidth -1} {align ""}} {
    global cell_row cell_col cells
    global mode
    global annoP
    if {[info exists annoP]} {
        # <annotation>s within <reference>s.
        switch -- $mode {
            html {}
            default { set data [chars_expand $data 0] }
        }
        append cells(0,0) $data
        return 1
    }
    if {$row == -1} {
        if {[llength [array names cells]] == 0} {
            # No current cell_row,cell_col to append to.
            return 0
        }
    } else {
        # We were called for a <ttcol> or a <c>.
        set cells(maxrow) $row
        set cell_row $row
        set cell_col $col
        if {![string compare $width ""] || $width >= 0} {
            # We were called for a <ttcol>.
            lappend cells(width) $width
            lappend cells(align) $align
            set cells(maxcol) $col
        }
        if {![string compare $cwidth ""] || $cwidth >= 0} {
            # We were called for a <ttcol> and cwidths are known.
            lappend cells(cwidth) $cwidth
        }
    }
    append cells($cell_row,$cell_col) [chars_expand $data 0]
    return 1
}
proc xref_txt {text av target format {hackP 0}} {
    global elem
    global eatP
    global mode
    array set attrs $av
    set elemY $attrs(elemN)
    array set tv [list title "" suppress-title false]
    array set tv $elem($elemY)
    switch -- [string tolower $tv(suppress-title)] {
        yes - true - 1 {
            set suppressP 1
        }
        default {
            set suppressP 0
        }
    }
    # Turn any hyphens in value into non-breaking hyphens.
    regsub -all -- "-" $attrs(value) "\u2011" attrs(value)
    switch -- $attrs(type) {
        section   { set line   "Section\xA0$attrs(value)"   }
        appendix  { set line  "Appendix\xA0$attrs(value)"   }
        figure    { set line    "Figure\xA0$attrs(value)"   }
        texttable { set line     "Table\xA0$attrs(value)"   }
        cref      { set line   "Comment\xA0$attrs(value)"   }
        t         { set line "Paragraph\xA0$attrs(value)"   }
        default   { set line            "\[$attrs(value)\]" }
    }
    if {$hackP} {
        return $line
    }
    if {![string compare $format none]} {
        if {![string compare [set line [chars_expand $text]] ""]} {
            set eatP -1
            return
        }
    } elseif {[string compare $text ""]} {
        switch -- $attrs(type) {
            section - appendix - figure - texttable {
                if {$suppressP} {
                    set line [chars_expand $text]
                } else {
                    set line "[chars_expand $text] ($line)"
                }
            }
            default {
                set line "[chars_expand $text] $line"
            }
        }
    } else {
        switch -- $format {
            counter { set line $attrs(value) }
            title   { set line [chars_expand $tv(title)] }
            default {}
        }
    }
    if {![cellP $line]} {
        set eatP 0
        write_text_$mode $line
    }
    set eatP -1
}
proc eref_txt {text counter target} {
    global eatP
    global erefs
    global mode
    if {![string compare $text ""]} {
        set line "<$target>"
    } elseif {([string first "#" $target] < 0) \
                  && ([string compare $text $target])} {
        set erefs($counter) $target
        set line "$text\xA0\[$counter\]"
    } else {
        set line $text
    }
    if {![cellP $line]} {
        set eatP 0
        write_text_$mode [chars_expand $line]
    }
    set eatP -1
}
proc cref_txt {text counter source anchor} {
    global options
    global eatP
    global crefs
    global mode
    set comments ""
    if {[string compare $source ""]} {
        set comments "${source}: "
    }
    append comments $text
    set crefs($counter) [list $anchor $source $text $comments]
    if {$options(.INLINE)} {
        set line "\[\[$counter: $text"
        if {[string compare $source ""]} {
            append line " --$source"
        }
        append line "\]\]"
    } else {
        set line "\[$counter\]"
    }
    if {![cellP $line]} {
        set eatP 0
        pcdata_$mode $line
    }
    set eatP -1
}
proc iref_txt {item subitem flags} {
    global pageno
    return $pageno
}
proc vspace_txt {lines} {
    global lineno
    global eatP
    global mode
    global unpaginated
    global page_head_height page_body_height
    set eatP 1
    if {[is_at_page_start]} {
        return
    }
    if {   !$unpaginated
        && ($lineno + $lines >= $page_head_height + $page_body_height)} {
        # l+l == h+b would fit, but leave nothing.
        end_page_$mode
    } else {
        switch -- $mode {
            txt {
                while {[incr lines -1] >= 0} {
                    write_it ""
                    incr lineno
                }
            }
            nr {
                if {$lines > 0} {
                    write_it ".sp $lines"
                    incr lineno $lines
                } else {
                    write_it ".br"
                }
            }
        }
    }
}
# Can be reset in rc file to override or add styles; e.g.,
#   global spanx_txt_styles
#   set spanx_txt_styles [linsert $spanx_txt_styles 0 {verb "<" ">"}]
global spanx_txt_styles
set spanx_txt_styles {
    {emph "_"}      # as in makeinfo(1)
    {vemph "_"}
    {strong "*"}    # as in makeinfo(1)
    {vstrong "*"}
    {verb "\""}
    {vbare ""}
    {vdeluxe "*_" "_*"}
    {nobreak ""}
}
proc spanx_txt {text style} {
    global spanx_txt_styles
    global mode
    global eatP
    set i [lsearch0 $spanx_txt_styles $style]
    if {$i < 0} {
        set c1 ""
        set c2 ""
    } else {
        set sts [lindex $spanx_txt_styles $i]
        set c1 [lindex $sts 1]
        if {[llength $sts] >= 3} {
            set c2 [lindex $sts 2]
        } else {
            set c2 $c1
        }
    }
    set text [chars_expand $text]
    switch -- $style {
        vemph - vstrong - verb - vbare - vdeluxe - nobreak {
            set text [break_protect $text]
        }
    }
    set line $c1$text$c2
    if {![cellP $line]} {
        set eatP 0
        write_pcdata_$mode $line
    }
    set eatP -1
}
proc references_txt {tag args} {
    global mode
    global counter depth
    global pageno
    global page_basic_indent
    switch -- $tag {
        begin {
            set prefix [lindex $args 0]
            set title  [lindex $args 1]
            if {   $depth(references) > 1
                && ![info exists counter(references)]} {
                set counter(references) 0
                section_$mode [lindex [split $prefix .] 0]. 1 References 0 ""
            }
            return [section_$mode $prefix [expr $depth(references) <= 1] $title 3 ""]
        }
        end {
            set erefP [lindex $args 0]
            if {$erefP} {
                erefs_$mode
            } else {
                flush_text
            }
        }
    }
}
proc erefs_txt {{title ""}} {
    global erefs
    global options
    if {[string compare $title ""]} {
        if {$options(.COMPACT)} {
            write_line_txt ""
        } else {
            end_page_txt
        }
        write_line_txt $title
    }
    set names  [lsort -integer [array names erefs]]
    set width [expr [string length [lindex $names end]]+2]
    foreach eref $names {
        write_line_txt ""
        set i [expr [string length \
                            [set prefix \
                                 [format %-*.*s $width $width \
                                         "\[$eref\]"]]+2]]
        write_text_txt $prefix
        push_indent $i
        write_text_txt "  "
        write_url $erefs($eref)
        pop_indent
    }
    flush_text
}
proc crefs_txt {title} {
    global crefs
    global options
    if {[string compare $title ""]} {
        if {$options(.COMPACT)} {
            write_line_txt ""
        } else {
            end_page_txt
        }
        write_line_txt $title
    }
    set names  [lsort -dictionary [array names crefs]]
    set width 0
    foreach cref $names {
        set x [string length $cref]
        if {$x > $width} {
            set width $x
        }
    }
    incr width 2
    foreach cref $names {
        write_line_txt ""
        set i [expr [string length \
                            [set prefix \
                                 [format %-*.*s $width $width \
                                         "\[$cref\]"]]+2]]
        write_text_txt $prefix
        push_indent $i
        write_text_txt "  "
        write_text_txt [chars_expand [lindex $crefs($cref) 3]]
        pop_indent
    }
    flush_text
}
proc reference_txt {prefix names title series formats date anchor target
                    target2 width annotations} {
    global options
    global max_ref_width
    write_line_txt ""
    if {($width > $max_ref_width) && !$options(.RFCEDSTYLE)} {
        set width $max_ref_width
    }
    set i [string length $prefix]
    set prefix [format %-*s [expr $width + 2] "\[$prefix\]"]
    write_text_txt $prefix
    if {$i > $width} {
        set s ""
        flush_text
    } else {
        set s "  "
    }
    push_indent [expr $width + 4]
    set nameA 1
    set nameN [llength $names]
    foreach name $names {
        incr nameA
        write_text_txt $s[chars_expand [lindex $name 0]]
        set s [list_sep_str $nameA $nameN]
    }
    write_text_txt "$s\"[chars_expand $title]\""
    foreach serial $series {
        if {$options(.NOTEDRAFTINPROGRESS)} {
          if {[regexp -nocase -- "internet-draft (draft-.*)" $serial x n] == 1} {
              set serial "$n (work in progress)"
          }
        }
        write_text_txt ", [chars_expand $serial]"
    }
    if {[string compare $date ""]} {
        write_text_txt ", [chars_expand $date]"
    }
    if {[string compare $target ""]} {
        write_text_txt ", "
        write_url $target
    }
    write_text_txt .
    while {[llength $annotations] > 0} {
        write_line_txt ""
        pcdata_txt [lindex $annotations 0]
        set annotations [lrange $annotations 1 end]
    }
    pop_indent
}
proc annotation_txt {tag} {
    global mode
    global annoP
    global cells
    switch -- $tag {
        begin {
            set annoP 1
        }
        end {
            unset annoP
            set text [string trim $cells(0,0)]
            unset cells
            switch -- $mode {
                html {}
                default { set text [two_spaces $text 1] }
            }
            return $text
        }
    }
}
proc authors_txt {authors} {
    global options
    global lineno pageno
    global contacts
    global authorspg
    global page_basic_indent
    if {!$options(.AUTHORSHIP)} {
        return
    }
    switch -- [llength $authors] {
        0       { return }
        1       { set s1 "'s"; set s2 ""   }
        default { set s1 "s'"; set s2 "es" }
    }
    set s "Author$s1 Address$s2"
    if {!$options(.COMPACT) || ![have_lines 4]} {
        end_page_txt
    } else {
        write_line_txt ""
    }
    if {!$options(.RFCEDSTYLE)} {
        write_line_txt "" -1
    }
    set authorspg $pageno
    set bi [format "%*s" $page_basic_indent ""]
    set firstP 1
    foreach author $authors {
        set block1 [lindex $author 0]
        set block2 [lindex $author 1]
        set lines 4
        incr lines [llength $block1]
        incr lines [llength $block2]
        if {![have_lines $lines]} {
            end_page_txt
        }
        if {[string compare $s ""]} {
            write_line_txt $s
            set s ""
        } else {
            write_line_txt "" -1
        }
        write_line_txt "" -1
        foreach line $block1 {
            write_line_txt $bi[chars_expand $line]
        }
        if {[llength $block2] > 0} {
            write_line_txt ""
            foreach contact $block2 {
                set key [lindex $contact 0]
                set value [lindex [lindex $contacts \
                                          [lsearch0 $contacts $key]] 1]
                if {$options(.RFCEDSTYLE) && ![string compare $key email]} {
                    regsub -- m $value M value
                }
                set value [format %-6s $value:]
                if {$options(.COLONSPACE)} {
                    append value " "
                }
                write_line_txt "$bi$value [chars_expand [lindex $contact 1]]"
            }
        }
    }
}
proc back_txt {} {
}
global pcdata_line_offset
set pcdata_line_offset 0
proc pcdata_txt {text {pre 0} {nowrite 0} {spans {}} {divs {}} } {
    global eatP
    global options
    global pcdata_line_offset
    if {[llength $spans] > 0 || [llength $divs] > 0} {
        set text [html_quote $text]
    }
    if {(!$pre) && ($eatP > 0)} {
        set text [string trimleft $text]
    }
    if {[string length $text] <= 0} {
        # Was only white space, but got trimmed.
        return
    }
    set eatP 0
    if {!$pre} {
        regsub -all -- "\n\[ \t\n\]*" $text "\n" text
        regsub -all -- "\[ \t\]*\n\[ \t\]*" $text "\n" text
        set prefix ""
        if {$options(.EMOTICONIC)} {
            set text [emoticonic_txt $text]
        }
    }
    if {[cellP $text]} {
        return
    }
    set pcdata_line_offset 0
    foreach line [split $text "\n"] {
        set line [chars_expand $line]
        if {$pre} {
            set x 0
            while {[set x [lsearch0 $divs $pcdata_line_offset $x]] >= 0} {
                if {![have_lines [lindex [lindex $divs $x] 1]]} {
                    end_page_txt
                    break
                }
                incr x
            }
            write_line_txt [string trimright $line] $pre
        } else {
            write_pcdata_txt $prefix$line
            set prefix " "
        }
        incr pcdata_line_offset
    }
    set pcdata_line_offset 0
    if {[regexp -- {[ \t\n]$} $text]} {
        set eatP 1
    }
}
proc emoticonic_txt {text} {
    foreach {ei begin end} [list  *   *   * \
                                  '   '   ' \
                                 {"} {"} {"}] {
        set body ""
        while {[set x [string first "|$ei" $text]] >= 0} {
            if {$x > 0} {
                append body [string range $text 0 [expr $x-1]]
            }
            append body "$begin"
            set text [string range $text [expr $x+2] end]
            if {[set x [string first "|" $text]] < 0} {
                error "missing close for |$ei"
            }
            if {$x > 0} {
                set inline [string range $text 0 [expr $x-1]]
                if {[string first $begin $inline] == 0} {
                    set inline [string range $inline [string length $begin] \
                                       end]
                }
                set tail [expr [string length $inline]-[string length $end]]
                if {[string last $end $inline] == $tail} {
                    set inline [string range $inline 0 [expr $tail-1]]
                }
                append body $inline
            }
            append body "$end"
            set text [string range $text [expr $x+1] end]
        }
        append body $text
        set text $body
    }
    return $text
}
proc start_page_txt {} {
    global header lineno blankP
    global page_head_height
    write_it $header
    write_it ""
    write_it ""
    set lineno $page_head_height
    set blankP 1
}
proc end_page_txt {} {
    global footer lineno pageno unpaginated
    global page_width page_head_height page_body_height page_foot_height
    flush_text
    if {$lineno <= $page_head_height} {
        return
    }
    if {$unpaginated} {
        write_line_txt ""
        return
    }
    set lim [expr $page_head_height + $page_body_height + $page_foot_height - 1]
    while {$lineno < $lim} {
        write_it ""
        incr lineno
    }
    set text [format "\[Page %d\]" $pageno]
    incr pageno
    set len [string length $text]
    set len [expr ($page_width - [string length $footer]) - $len]
    if {$len < 4} {
        set len 4
    }
    write_it [format %s%*s%s $footer $len "" $text]
    write_it "\f"
    set lineno 0
}
proc write_pcdata_txt {text} {
    global buffer buffer_align
    global indent
    global mode
    if {![string compare $buffer ""]} {
        set buffer [format %*s $indent ""]
        set buffer_align [current_align]
    }
    append buffer $text
    set buffer [two_spaces $buffer]
    write_text_$mode ""
}
proc write_editno_txt {editNo} {
    global buffer
    flush_text
    set buffer <$editNo>
    flush_text
}
global break_chars
set break_chars {/ @ & | - + # % :}
proc break_protect {s} {
    global break_chars
    foreach c $break_chars {
        # Unicode reserves U+E000..U+F8FF for private use.
        set cx [format %c [expr 0xF000 + [scan $c %c]]]
        regsub -all -- "\[$c\]" $s $cx s
    }
    return $s
}
proc break_preprocess {s} {
    # As long as we only try breaking lines *after* recognized characters.
    # U+2060 WORD JOINER
    while {[regexp -- "(\[!-~\])\[\u2060\]" $s x cx]} {
        # Unicode reserves U+E000..U+F8FF for private use.
        set c [format %c [expr 0xF000 + [scan $cx %c]]]
        regsub -all -- "\[$cx\]\[\u2060\]" $s $c s
    }
    regsub -all -- "\[\u2060\]" $s "" s
    return $s
}
proc break_unprotect {s} {
    global break_chars
    # Unicode reserves U+E000..U+F8FF for private use.
    while {[regexp -- "\[\uF000-\uF0FF\]" $s cx]} {
        set c [format %c [expr [scan $cx %c] - 0xF000]]
        if {![string compare $c &]} {
            set c "\\&"
        }
        regsub -all -- "\[$cx\]" $s $c s
    }
    # U+2011 NON-BREAKING HYPHEN
    regsub -all -- "\[\u2011\]" $s "-" s
    # U+2060 WORD JOINER
    regsub -all -- "\[\u2060\]" $s "" s
    return $s
}
global buffer_rest buffer_align
set buffer_rest ""
set buffer_align ""
proc fold_text_txt {} {
    global buffer buffer_rest
    global break_chars
    global indent
    global page_width
    set buflen [string length $buffer]
    if {$buflen > $page_width} {
        set x [string last " " [string range $buffer 0 $page_width]]
        if {   $x != $page_width
            && [regexp -indices -start [expr $x + 1] \
                       -- { *([^ ]+)} $buffer y wi]
            && [set w0 [lindex $wi 0]] < $page_width} {
            # Get word across edge.
            set w1 [lindex $wi 1]
            set word [string range $buffer $w0 $w1]
            set wlen [expr $w1 - $w0 + 1]
            set ww [string range $word 0 [expr $page_width - 1 - $w0]]
            set must_break [expr (   ($w0 <= $indent) \
                                  || ($indent + $wlen > $page_width))]
            # Don't bother with short words that cannot possibly
            # produce a good break.
            # Don't break a URI (or other things that are nice to
            # copy&paste in their entirety) if it would entirely
            # fit in its own line (the next line).
            # Don't bother wasting our time on frequent purely
            # alphanumerical non-opportunities.
            if {   $must_break
                || (   ($w0 < ($page_width - 2))
                    && ($wlen >= 6)
                    && ![regexp -- {^[A-Za-z0-9_\xA0]+$} $ww]
                    && ![regexp -expanded -- { ://
                                              |\m(mailto|urn|news|tel):
                                              |\mdraft-[a-z0-9]+-
                                              |\m[A-Za-z0-9._-]+@[a-z0-9.-]+\M
                                             } $word]
                   )} {
                set best_left -1
                set best_middle -1
                set best_right $wlen
                # Bad:       a-zzzzzzz
                # Ok:       aa-zzzzzzz
                # Bad:  aaaaaa-zz
                # Ok:   aaaaaa-zzz
                foreach d $break_chars {
                    set y [string last $d $ww]
                    while {   $y >= 0
                           && [regexp -start $y -- "\\A.\[\])>\}'\"/@+:&|#%-\]" $word]} {
                        # Not a good break based on first character after it.
                        set y [string last $d [string range $ww 0 [expr $y - 1]]]
                    }
                    if {$y < 0 || $w0 + $y < $indent} {
                        # Not usable.
                    } elseif {   $y < 2
                              || [regexp -all -- {[A-Za-z0-9_]} \
                                         [string range $word \
                                                 0 [expr $y - 1]]] < 2} {
                        # Keep best of the indesirable left cuts.
                        if {$y > $best_left} {
                            set best_left $y
                        }
                    } elseif {   $y > $wlen - 4
                              || [regexp -all -- {[A-Za-z0-9_]} \
                                         [string range $word \
                                                 [expr $y + 1] end]] < 3} {
                        # Keep best of the indesirable right cuts.
                        if {$y < $best_right} {
                            set best_right $y
                        }
                    } else {
                        # The first good middle position gets it,
                        # because it's a better character.
                        if {$best_middle < 0} {
                            set best_middle $y
                            # Bonus early break.
                            break
                        }
                        ## The best middle position gets it,
                        ## even if it's a worst character.
                        #if {$y > $best_middle} {
                        #    set best_middle $y
                        #}
                    }
                }
                if {$best_middle >= 0} {
                    set x [expr $w0 + $best_middle + 1]
                } elseif {$must_break} {
                    # All undesirable, so start at right.
                    if {$best_right < $wlen} {
                        set x [expr $w0 + $best_right + 1]
                    } elseif {$best_left >= 0} {
                        set x [expr $w0 + $best_left + 1]
                    } else {
                        set x $page_width
                    }
                    global lineno pageno
                    regsub -all -- \" [string range $buffer $w0 [expr $x - 1]] {\"} wa
                    regsub -all -- \" [string range $buffer $x  $w1]           {\"} wz
                    unexpected warning \
 "output line $lineno (on page $pageno) breaks badly between \"$wa\" and \"$wz\""
                }
                # Else, we keep the first x we found
                # so we don't break the word.
            }
        }
        set text [string range $buffer 0 [expr $x-1]]
        set rest [string trimleft [string range $buffer $x end]]
    } else {
        set text $buffer
        set rest ""
    }
    # This would be done anyway by flush_text,
    # which is now (and must be) a no-op.
    set buffer ""
    # It is up to the caller to restore buffer with $buffer_rest,
    # after having printed text with write_line_$mode.
    if {[string compare $rest ""]} {
        set buffer_rest [format %*s%s $indent "" $rest]
    } else {
        set buffer_rest ""
    }
    return [string trimright $text]
}
proc justify_text_txt {text direction} {
    global indent
    global page_width
    set t [string trim $text]
    switch -- $direction {
        c - center {
            # Attempt to match (g)nroff formula.
            set len [expr ($page_width + $indent - [string length $t]) / 2]
        }
        r - right {
            set len [expr $page_width - [string length $t]]
        }
        default { return $text }
    }
    return [format %*s%s $len "" $t]
}
proc write_text_txt {text {direction l}} {
    global buffer buffer_rest buffer_align
    global indent
    global page_width
    global eatP
    if {($eatP < 0) && ![regexp -- {^[.,?!]} $text]} {
        set text " $text"
    }
    if {![string compare $buffer ""]} {
        set buffer [format %*s $indent ""]
        set buffer_align [current_align]
    }
# print_stack_trace
    append buffer $text
    set flush [string compare $direction l]
    while {([string length $buffer] > $page_width) || ($flush)} {
        set text [fold_text_txt]
        switch -- $direction {
            c - r { set buffer_align $direction }
        }
        set text [justify_text_txt $text $buffer_align]
        write_line_txt $text
        if {![string compare [set buffer $buffer_rest] ""]} {
            set buffer_align ""
            break
        }
    }
}
# grab the current function name. Useful in debugging like this:
# puts stderr "[get_current_function_name] your message goes here"
proc get_current_function_name {} {
    return [info level -1];
}
# print the current stack trace
proc print_stack_trace {} {
    set stack ""
    set level -1
    for { set x [expr {[info level] + $level}] } { $x > 0 } { incr x -1 } {
	append stack "    called from [info level $x]\n"
    }
    puts stderr $stack
}
proc write_line_txt {line {pre 0}} {
    global lineno blankP
    global unpaginated
    global page_width
    global page_head_height page_body_height page_basic_indent
    flush_text
    if {$lineno == 0} {
        start_page_txt
    }
    if {![set x [string compare $line ""]]} {
        set blankO $blankP
        set blankP 1
        if {($blankO) && (!$pre || $lineno == $page_head_height)} {
            return
        }
    } else {
        set blankP 0
    }
    if {($pre) && ($x)} {
        if {$pre < 0} {
            set prefix [format "%*s" $page_basic_indent ""]
        } else {
            # pre = 1 + total indent
            set prefix [format %*s [expr $pre - 1] ""]
            set line [tabs_expand_pre $line]
        }
    } else {
        set prefix ""
    }
    set line [nbsp_expand_txt [break_unprotect $line]]
    write_it [set line [string trimright $prefix$line]]
    incr lineno
    if {[set len [string length $line]] > $page_width} {
        global pageno
        regsub -all -- \" [string range $line $page_width end] {\"} excess
        unexpected [unex_condtype] \
            "output line $lineno (on page $pageno) has $len > $page_width characters (excess string is \"$excess\")"
    }
    if {!$unpaginated && ($lineno >= $page_head_height + $page_body_height)} {
        end_page_txt
    }
}
proc nbsp_expand_txt {s} {
    regsub -all -- "\xA0" [string trimright $s] " " s
    return $s
}
proc two_spaces {glop {flatten 0}} {
    global options
    global indent
    # Work around a bug in tcl-8.4.9 and possibly others.
    # Don't ask, it's a mystery anyway.
    set foo "x$glop"
    if {$flatten} {
        set post ""
        set glop [string trim $glop]
        regsub -all -- {[\t\n ]+} $glop { } glop
    } else {
        set post [string range $glop 0 [expr $indent -1]]
        set glop [string range $glop $indent end]
        regsub -all -- {([^ ])[\t ]+} $glop {\1 } glop
    }
    if {$options(.COLONSPACE)} {
        set re {([.?!][])'"]*|:) }
    } else {
        set re {[.?!][])'"]* }
    }
    while {[string length $glop] > 0} {
        # The double quotes will also match the end of a spanx-verb, which
        # may not be the end of a sentence.  Impossible to tell apart.  :-(
        if {![regexp -indices -- $re $glop x]} {
            append post $glop
            break
        }
        set pre [string range $glop 0 [lindex $x 1]]
        set glop [string trimleft [string range $glop [expr [lindex $x 1] + 1] end]]
        append post $pre
        # Get rid of the colon case quickly.
        if {   $options(.COLONSPACE)
            && [regexp -- {: $} $pre]} {
            append post " "
            continue
        }
        # A special case.  Author wouldn't normally put a period after that.
        if {[regexp -- {[Aa](nne|ppendi)x[ \xA0][A-Z][])'"]*[.?!][])'"]* $} $pre]} {
            append post " "
            continue
        }
        # Check for likely abbreviation.  Do not insert two spaces in
        # this case.
        # "e.g." and "i.e." are never directly followed by spaces.
        # "etc. " and "et al. " will often be the end of the sentence anyway.
        if {[regexp -expanded -- {(^|[^A-Za-z\xA0-])
                                  (  [A-Z]\.[])'"]*
                                   | (  [A-Z][a-z][a-z]
                                      | Fig | Tbl | Eq
                                      | [Cc]f | vs | resp
                                      | [JS]r | M[rs] | Messrs | Mrs | Mmes
                                      | Drs? | Profs?
                                      | Rep | Sen | Gov
                                      | St | Rev
                                      | Gen | Col | Maj | Cap | Lt)
                                     \.)
                                  \ $} $pre]} {
            continue
        }
        # Check if what follows doesn't look like the beginning of a sentence.
        if {[regexp -- {^["'([]*[^A-Z"'([]} $glop]} {
            continue
        }
        # Otherwise, we assume that we are in between two sentences.
        append post " "
    }
    return $post
}
proc pi_txt {key value} {
    global mode
    global passno
    switch -- $key {
        needLines {
            global buffer
            set x [string compare $buffer ""]
            if {![have_lines $value]} {
                end_page_$mode
            } elseif {$x && ![string compare $mode nr]} {
                # We might have flushed early, so now make it stick.
                write_it ".br"
            }
        }
        typeout {
            if {$passno == 2} {
                puts stdout $value
            }
        }
        default { error "" }
    }
}
#       }}}2 txt rendering engine
#       {{{2 html rendering engine
#           {{{3 Main html mode
# don't need to return anything even though rfc_txt does...
proc rfc_html {irefs authors iprstmt copying newP validity} {
    global options copyrightP iprP
    global funding
    global indexpg
    if {$options(.SLIDES) && [end_rfc_slides]} {
        return
    }
    if {[llength $irefs] > 0} {
        set indexpg rfc.index
        toc_html rfc.index
        write_html "<$options(.TOPTAG)>Index</$options(.TOPTAG)>"
        write_html "<table>"
        foreach iref $irefs {
            foreach {L item subitem flags pages} $iref { break }
            if {[string compare $L ""]} {
                write_html "<tr><td><strong>$L</strong></td><td> </td></tr>"
            }
            if {[string compare $subitem ""]} {
                if {[string compare $item ""]} {
                    write_html "<tr><td> </td><td>$item</td></tr>"
                }
                set key $subitem
                set t "  "
            } else {
                set key $item
                set t ""
            }
            array set iflags $flags
            if {![string compare $iflags(primary) true]} {
                set key "<b>$key</b>"
            }
            if {[llength $pages] == 1} {
                set key "<a href=\"#[lindex $pages 0]\">$key</a>"
            } else {
                set i 0
                set s "  "
                foreach page $pages {
                    append key "$s<a href=\"#$page\">[incr i]</a>"
                    set s ", "
                }
            }
            write_html "<tr><td> </td><td>$t$key</td></tr>"
        }
        write_html "</table>"
    }
    authors_html $authors
#!# puts "html copyrightP $copyrightP"
    if {(!$options(.PRIVATE)) && $copyrightP > 0} {
        toc_html rfc.copyright
        # See comment in "proc rfc_txt" about this content.
        if {0 && $newP} {
            write_html "<$options(.TOPTAG)>Copyright Statement</$options(.TOPTAG)>"
        } else {
            write_html "<$options(.TOPTAG)>Full Copyright Statement</$options(.TOPTAG)>"
        }
        foreach para $copying {
            write_html "<p class='copyright'>"
            pcdata_html $para
            write_html "</p>"
        }
        if {$newP} {
            #write_html "<$options(.TOPTAG)>Disclaimer of Validity</$options(.TOPTAG)>"
            foreach para $validity {
                write_html "<p class='copyright'>"
                pcdata_html $para
                write_html "</p>"
            }
        }
        if {$iprP} {
            global iprurl ipremail
            write_html "<$options(.TOPTAG)>Intellectual Property</$options(.TOPTAG)>"
            regsub -all -- %IPRURL% $iprstmt "<a href='$iprurl'>$iprurl</a>" iprstmt
            if {$options(.LINKMAILTO)} {
                regsub -all -- %IPREMAIL% $iprstmt "<a href='mailto:$ipremail'>$ipremail</a>" iprstmt
            } else {
                regsub -all -- %IPREMAIL% $iprstmt $ipremail iprstmt
            }
            foreach para $iprstmt {
                write_html "<p class='copyright'>"
                pcdata_html $para
                write_html "</p>"
            }
        }
        if {$options(.RFCEDSTYLE)} {
            set ack "Acknowledgement"
        } else {
            set ack "Acknowledgment"
        }
        set acks 0
        if {[string length $funding]} {
            incr acks 1
        }
        if {$options(.RFCPROCACK)} {
            incr acks 1
        }
        if {$acks > 1} {
            append ack s
        }
        if {$acks} {
            write_html "<$options(.TOPTAG)>$ack</$options(.TOPTAG)>"
            write_html "<p class='copyright'>"
        }
        if {[string length $funding]} {
            pcdata_html $funding
        }
        if {$options(.RFCPROCACK)} {
            global prog_ack prog_url
            regsub -all -- %PROGURL% $prog_ack \
                   "<a href='$prog_url'>$prog_url</a>" xml2rfc_ack
            if {[string length $funding]} {
                pcdata_html "  "
            }
            pcdata_html $xml2rfc_ack
        }
        if {$acks} {
            write_html "</p>"
        }
    }
    write_html "</body></html>"
    return ""
}
#               {{{4 CSS style-sheet
global htmlstyle
set htmlstyle \
"<style type='text/css'><!--
        body {
                font-family: verdana, charcoal, helvetica, arial, sans-serif;
                font-size: small; color: #000; background-color: #FFF;
                margin: 2em;
        }
        h1, h2, h3, h4, h5, h6 {
                font-family: helvetica, monaco, \"MS Sans Serif\", arial, sans-serif;
                font-weight: bold; font-style: normal;
        }
        h1 { color: #900; background-color: transparent; text-align: right; }
        h3 { color: #333; background-color: transparent; }
        td.RFCbug {
                font-size: x-small; text-decoration: none;
                width: 30px; height: 30px; padding-top: 2px;
                text-align: justify; vertical-align: middle;
                background-color: #000;
        }
        td.RFCbug span.RFC {
                font-family: monaco, charcoal, geneva, \"MS Sans Serif\", helvetica, verdana, sans-serif;
                font-weight: bold; color: #666;
        }
        td.RFCbug span.hotText {
                font-family: charcoal, monaco, geneva, \"MS Sans Serif\", helvetica, verdana, sans-serif;
                font-weight: normal; text-align: center; color: #FFF;
        }
        table.TOCbug { width: 30px; height: 15px; }
        td.TOCbug {
                text-align: center; width: 30px; height: 15px;
                color: #FFF; background-color: #900;
        }
        td.TOCbug a {
                font-family: monaco, charcoal, geneva, \"MS Sans Serif\", helvetica, sans-serif;
                font-weight: bold; font-size: x-small; text-decoration: none;
                color: #FFF; background-color: transparent;
        }
        td.header {
                font-family: arial, helvetica, sans-serif; font-size: x-small;
                vertical-align: top; width: 33%;
                color: #FFF; background-color: #666;
        }
        td.author { font-weight: bold; font-size: x-small; margin-left: 4em; }
        td.author-text { font-size: x-small; }
        /* info code from SantaKlauss at http://www.madaboutstyle.com/tooltip2.html */
        a.info {
                /* This is the key. */
                position: relative;
                z-index: 24;
                text-decoration: none;
        }
        a.info:hover {
                z-index: 25;
                color: #FFF; background-color: #900;
        }
        a.info span { display: none; }
        a.info:hover span.info {
                /* The span will display just on :hover state. */
                display: block;
                position: absolute;
                font-size: smaller;
                top: 2em; left: -5em; width: 15em;
                padding: 2px; border: 1px solid #333;
                color: #900; background-color: #EEE;
                text-align: left;
        }
        a { font-weight: bold; }
        a:link    { color: #900; background-color: transparent; }
        a:visited { color: #633; background-color: transparent; }
        a:active  { color: #633; background-color: transparent; }
        p { margin-left: 2em; margin-right: 2em; }
        p.copyright { font-size: x-small; }
        p.toc { font-size: small; font-weight: bold; margin-left: 3em; }
        table.toc { margin: 0 0 0 3em; padding: 0; border: 0; vertical-align: text-top; }
        td.toc { font-size: small; font-weight: bold; vertical-align: text-top; }
        ol.text { margin-left: 2em; margin-right: 2em; }
        ul.text { margin-left: 2em; margin-right: 2em; }
        li      { margin-left: 3em; }
        /* RFC-2629 <spanx>s and <artwork>s. */
        em     { font-style: italic; }
        strong { font-weight: bold; }
        dfn    { font-weight: bold; font-style: normal; }
        cite   { font-weight: normal; font-style: normal; }
        tt     { color: #036; }
        tt, pre, pre dfn, pre em, pre cite, pre span {
                font-family: \"Courier New\", Courier, monospace; font-size: small;
        }
        pre {
                text-align: left; padding: 4px;
                color: #000; background-color: #CCC;
        }
        pre dfn  { color: #900; }
        pre em   { color: #66F; background-color: #FFC; font-weight: normal; }
        pre .key { color: #33C; font-weight: bold; }
        pre .id  { color: #900; }
        pre .str { color: #000; background-color: #CFF; }
        pre .val { color: #066; }
        pre .rep { color: #909; }
        pre .oth { color: #000; background-color: #FCF; }
        pre .err { background-color: #FCC; }
        /* RFC-2629 <texttable>s. */
        table.all, table.full, table.headers, table.none {
                font-size: small; text-align: center; border-width: 2px;
                vertical-align: top; border-collapse: collapse;
        }
        table.all, table.full { border-style: solid; border-color: black; }
        table.headers, table.none { border-style: none; }
        th {
                font-weight: bold; border-color: black;
                border-width: 2px 2px 3px 2px;
        }
        table.all th, table.full th { border-style: solid; }
        table.headers th { border-style: none none solid none; }
        table.none th { border-style: none; }
        table.all td {
                border-style: solid; border-color: #333;
                border-width: 1px 2px;
        }
        table.full td, table.headers td, table.none td { border-style: none; }
        hr { height: 1px; }
        hr.insert {
                width: 80%; border-style: none; border-width: 0;
                color: #CCC; background-color: #CCC;
        }
--></style>"
#               }}}4 CSS style-sheet
proc front_html_begin {left right top bottom title keywords lang} {
    global prog prog_version prog_url
    global options copyrightP
    global htmlstyle
    global doingP hangP needP
    global imgP
    global indexpg authorspg
    set doingP 0
    set hangP 0
    set needP 0
    set imgP 0
    if {$options(.SLIDES) \
            && [front_slides_begin $left $right $top $bottom $title]} {
        return
    }
    set indexpg rfc.index
    set authorspg rfc.authors
    write_html "<\!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"
    write_html -nonewline "<html lang=\"$lang\"><head><title>"
    if {($options(.PRIVATE)) \
            && ([string compare [string trim $options(private)] ""])} {
        pcdata_html "$options(private): "
    }
    pcdata_html [lindex $title 0]
    write_html "</title>"
    # Begin new meta tags.
    write_html "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
    write_html -nonewline "<meta name=\"description\" content=\""
    regsub -all -- \" [lindex $title 0] {\"} t0
    pcdata_html $t0
    write_html "\">"
    # Write out meta tag with keywords if they exist.
    if {[llength $keywords] > 0} {
        write_html -nonewline "<meta name=\"keywords\" content=\""
        set s ""
        foreach kw $keywords {
            pcdata_html $s$kw
            set s ", "
        }
        write_html "\">"
    }
     write_html -nonewline "<meta name=\"generator\" content=\"$prog $prog_version "
     write_html "($prog_url)\">"
    # End new meta tags.
    write_html "$htmlstyle\n</head>"
    write_html -nonewline "<body"
    if {[string compare $options(background) ""]} {
        write_html -nonewline " background=\"$options(background)\""
    }
    write_html ">"
    xxxx_html
    if {$options(.TOPBLOCK)} {
        write_html "<table summary=\"layout\" width=\"66%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><td><table summary=\"layout\" width=\"100%\" border=\"0\" cellpadding=\"2\" cellspacing=\"1\">"
        set left [munge_long $left]
        set right [munge_long $right]
        set lc ""
        set rc ""
        foreach l $left r $right {
            if {[string compare $l ""]} {
                set l $l
            } else {
                set l " "
            }
            if {[string compare $r ""]} {
                set r $r
            } else {
                set r " "
            }
            write_html "<tr><td class=\"header\">$l</td><td class=\"header\">$r</td></tr>"
        }
        write_html "</table></td></tr></table>"
    }
    write_html -nonewline "<h1>"
    foreach line $title {
        write_html -nonewline "<br />"
        pcdata_html $line
    }
    write_html "</h1>"
}
proc write_status_html {status copying afterP} {
    global options copyrightP iprP
    if {!$options(.PRIVATE)} {
        write_html ""
        if {$options(.RFCEDSTYLE)} {
            write_html "<$options(.TOPTAG)>Status of This Memo</$options(.TOPTAG)>"
        } else {
            write_html "<$options(.TOPTAG)>Status of this Memo</$options(.TOPTAG)>"
        }
        foreach para $status {
            write_html "<p>"
            pcdata_html $para
            write_html "</p>"
        }
    }
    if {(!$options(.PRIVATE)) && $copyrightP && [string length $copying]} {
        write_html ""
        write_html "<$options(.TOPTAG)>Copyright Notice</$options(.TOPTAG)>"
        foreach para $copying {
            write_html "<p>"
            pcdata_html $para
            write_html "</p>"
        }
    }
}
proc front_html_end {toc} {
    global options
    if {!$options(.TOC)} {
        return
    }
    xxxx_html toc
    write_html "<$options(.TOPTAG)>Table of Contents</$options(.TOPTAG)>"
    if {$options(.TOCNARROW)} {
        write_html "<p class=\"toc\">"
    } else {
        write_html "<table class=\"toc\">"
    }
    set z 0
    foreach c $toc {
        set label [lindex $c 1]
        if {   !$options(.TOCOMPACT)
            && [lindex $c 0] <= 0} {
            set z1 [expr [string compare $label "§"] ? 1 : 2]
            if {$z && ($z == 1 || $z1 == 1)} {
                if {$options(.TOCNARROW)} {
                    write_html "<br />"
                } else {
                    write_html "<tr><td class=\"toc\"> </td></tr>"
                }
            }
            set z $z1
        }
        if {!$options(.TOCNARROW)} {
            write_html -nonewline "<tr><td class=\"toc\">"
        }
        set x [lindex $c 0]
        if {$options(.TOCINDENT)} {
            while {$x > 0} {
                if {$options(.TOCNARROW)} {
                    write_html -nonewline "    "
                } else {
                    write_html -nonewline "</td><td class=\"toc\">"
                }
                incr x -1
            }
        }
        if {$x < 0 && $options(.TOCAPPENDIX)} {
            set label "Appendix $label"
        }
        write_html -nonewline "<a href=\"#[lindex $c 3]\">"
        pcdata_html $label
        write_html "</a> "
        if {!$options(.TOCNARROW)} {
            write_html -nonewline "</td><td class=\"toc\" colspan=\"[expr $options(.TOCDEPTH) - [lindex $c 0]]\">"
        }
        pcdata_html [lindex $c 2]
        if {$options(.TOCNARROW)} {
            write_html "<br />"
        } else {
            write_html "</td></tr>"
        }
    }
    if {$options(.TOCNARROW)} {
        write_html "</p>"
    } else {
        write_html "</table>"
    }
    write_html "<br clear=\"all\" />"
}
proc abstract_html {} {
    global options
    if {$options(.SLIDES) && [end_page_slides]} {
        start_page_slides Abstract
    } else {
        write_html ""
        write_html "<$options(.TOPTAG)>Abstract</$options(.TOPTAG)>"
    }
}
proc note_html {title depth} {
    global options
    if {$options(.SLIDES) && [end_page_slides]} {
        start_page_slides $title
    } else {
        incr depth 3
        write_html ""
        write_html -nonewline "<h$depth>"
        pcdata_html $title
        write_html "</h$depth>"
    }
}
proc section_html {prefix top title {lines 0} anchor} {
    global options
    if {$options(.SLIDES) && [end_page_slides]} {
        start_page_slides $title
        return $anchor
    }
    set anchor2 [string trimright $prefix .]
    if {[string first "Appendix " $anchor2] == 0} {
        set anchor2 [string range $anchor2 9 end]
    }
    set anchor2 rfc.section.$anchor2
    if {$options(.DOCMAPPING)} {
        if {[set x [expr [llength [split $prefix .]]-1]] \
                > $options(.TOCDEPTH)} {
            set x $options(.TOCDEPTH)
        }
        set htag "h$x"
    } elseif {[string match *. $prefix]} {
        set htag "h3"
    } else {
        set htag "h4"
    }
    write_html ""
    if {[string match *. $prefix]} {
        toc_html $anchor
        write_html -nonewline "<a name=\"$anchor2\"></a>"
        write_html "<$htag>$prefix "
        pcdata_html $title
        write_html "</$htag>"
    } else {
        write_html -nonewline "<a name=\"$anchor2\"></a>"
        write_html "<$htag><a name=\"$anchor\">$prefix</a> "
        pcdata_html $title
        write_html "</$htag>"
    }
    return $anchor
}
proc t_html {tag counter style hangText editNo} {
    global options
    global doingP hangP needP
    if {[string compare $tag begin]} {
        set s /
        set needP 0
    } else {
        set s ""
    }
    write_html ""
    if {![string compare $style "hanging"]} {
        if {![string compare $tag begin]} {
            write_html "<dt>$hangText</dt>"
        }
        write_html -nonewline "<${s}dd>"
        set hangP 1
    } elseif {![string compare $style "letters"]} {
        if {![string compare $tag begin]} {
            set l [split $counter .]
            write_html "<dt>[offset2letters [lindex $l end] [llength $l]].</dt>"
        }
        write_html -nonewline "<${s}dd>"
        set hangP 1
    } elseif {([string compare $counter ""]) \
                    && ([string compare $style empty])} {
        write_html -nonewline "<${s}li>"
        set hangP 0
    } else {
        set sta ""
        if {[string compare $tag end]} {
            set doingP 1
            switch -- [set a [current_align]] {
                left - center - right {
                   set sta " style='text-align: $a'"
                }
            }
        }
        if {$doingP} {
            set doingP [string compare $tag end]
            write_html -nonewline "<${s}p${sta}>"
        }
        set hangP 0
    }
    if {$options(.EDITING) \
            && (![string compare $tag begin]) \
            && ([string compare $editNo ""])} {
        write_html -nonewline "<sup><small>$editNo</small></sup>"
    }
}
proc list_html {tag min max style hangIndent longestHangText suprT} {
    global doingP hangP needP
    if {[string compare $tag begin]} {
        set s /
        set c ""
    } else {
        set s ""
        set c " class=\"text\""
        if {$doingP} {
            write_html -nonewline "</p>"
            set doingP 0
        }
    }
    write_html ""
    switch -- $style {
        letters - hanging - format {
            if {[string compare $tag begin]} {
                write_html -nonewline "</dl></blockquote>"
            } else {
                write_html -nonewline "<blockquote$c><dl>"
            }
        }
        numbers { write_html -nonewline "<${s}ol$c>" }
        symbols { write_html -nonewline "<${s}ul$c>" }
        default { write_html -nonewline "<${s}blockquote$c>" }
    }
    if {($suprT >= 0) && ([string compare $tag begin])} {
        set needP 1
    }
    set hangP 0
}
proc figure_html {tag lines anchor title av {suppressP 0}} {
    global xref
    set hr {<hr class="insert" />}
    switch -- $tag {
        begin {
            if {[string compare $title ""] || [string compare $anchor ""]} {
                write_html "<br />$hr"
            }
            if {[string compare $anchor ""]} {
                write_html "<a name=\"$anchor\"></a>"
            }
            img_html begin 1 $av
        }
        end {
            img_html end 1 $av
            if {[string compare $anchor ""]} {
                array set av2 $xref($anchor)
                set prefix "Figure $av2(value)"
                if {[string compare $title ""]} {
                    set title "$prefix: $title"
                } elseif {!$suppressP} {
                    set title $prefix
                }
            }
            if {[string compare $title ""]} {
                #switch -- [set a [current_align]] {
                #    left - center - right { set al " align=\"$a\"" }
                #    default { set al "" }
                #}
                set al " align=\"center\""
                write_html "<table border=\"0\" cellpadding=\"0\" cellspacing=\"2\"$al><tr><td align=\"center\"><font face=\"monaco, MS Sans Serif\" size=\"1\"><b> $title </b></font><br /></td></tr></table>$hr"
            }
        }
    }
}
proc artwork_html {tag lines {av {}} } {
    img_html $tag 2 $av
}
proc img_html {tag bit {av {}} } {
    global imgP
    global options
    if {[set x [lsearch -exact $av src]] < 0 || $x & 1} {
        return
    }
    switch -- $tag {
        begin {
            if {$imgP} {
                return
            }
            set line "<div"
            set attrs ""
            set seen_alt 0
            foreach {k v} $av {
                # "name": file name to use for storing the content.
                # "type": not a MIME type; e.g., "abnf".
                regsub -all -- \" $v {\"} v
                switch -- $k {
                    width - height {
                        append attrs " $k=\"$v\""
                    }
                    src {
                        if {$options(.USEOBJECT)} {
                            append attrs " data=\"$v\""
                        } else {
                            append attrs " src=\"$v\""
                        }
                    }
                    alt {
                        if {!$options(.USEOBJECT)} {
                            append attrs " alt=\"$v\""
                            set seen_alt 1
                        }
                    }
                    align {
                        regsub -- {[-+][0-9]+em$} $v "" vv
                        switch -- $vv {
                            left - center - right {
                                append line " style='text-align: $vv'"
                            }
                            default {
                                unexpected error \
                                    "align=\"$v\" attribute is invalid"
                            }
                        }
                    }
                }
            }
            if {$options(.USEOBJECT)} {
                append line "><object"
            } else {
                append line "><img"
            }
            append line $attrs
            if {$options(.USEOBJECT)} {
                append line ">"
            } else {
                if {!$seen_alt} {
                    if {$options(.STRICT)} {
                        unexpected error \
                            "use of the \"src\" attribute in img graphics also requires \"alt\" attribute"
                    } else {
                        unexpected warning \
                            "also showing text content for img graphics with \"src\" but not \"alt\" attribute"
                        append line { alt="[graphic image equivalent to the textual content below]"}
                    }
                } else {
                    set imgP [expr $imgP | $bit]
                }
                append line " /></div>"
            }
            write_html $line
        }
        end {
            if {[set imgP [expr $imgP & ~$bit]]} {
                return
            }
            set line ""
            if {$options(.USEOBJECT)} {
                append line "</object>"
            }
            append line "</div>"
            write_html $line
        }
    }
}
proc preamble_html {tag {editNo ""}} {
    t_html $tag "" "" "" $editNo
}
proc postamble_html {tag {editNo ""}} {
    t_html $tag "" "" "" $editNo
}
proc texttable_html {tag lines anchor title {suppressP 0}} {
    global xref
    set hr {<hr class="insert" />}
    switch -- $tag {
        begin {
            if {[string compare $title ""] || [string compare $anchor ""]} {
                write_html "<br />$hr"
            }
            if {[string compare $anchor ""]} {
                write_html "<a name=\"$anchor\"></a>"
            }
        }
        end {
            if {[string compare $anchor ""]} {
                array set av $xref($anchor)
                set prefix "Table $av(value)"
                if {[string compare $title ""]} {
                    set title "$prefix: $title"
                } elseif {!$suppressP} {
                    set title $prefix
                }
            }
            if {[string compare $title ""]} {
                #switch -- [set a [current_align]] {
                #    left - center - right { set al " align=\"$a\"" }
                #    default { set al "" }
                #}
                set al " align=\"center\""
                write_html "<table border=\"0\" cellpadding=\"0\" cellspacing=\"2\"$al><tr><td align=\"center\"><font face=\"monaco, MS Sans Serif\" size=\"1\"><b> $title </b></font><br /></td></tr></table>$hr"
            }
        }
    }
    return [list 0 {}]
}
proc ttcol_html {text align col width cwidth} {
    global cellR
    global ttcol_html_cols ttcol_html_colsP ttcol_html_head ttcol_html_headP
    if {[set x [lindex $col 0]] == 1} {
        switch -- [set a [current_align]] {
            left - center - right { set al " align=\"$a\"" }
            default { set al "" }
        }
        write_html "<table class=\"$cellR\"$al border=\"0\" cellpadding=\"2\" cellspacing=\"2\">"
        # This assumes that <texttable>s cannot nest.
        set ttcol_html_cols ""
        set ttcol_html_colsP 0
        set ttcol_html_head ""
        set ttcol_html_headP 0
    }
    if {$x == 1} {
        append ttcol_html_head "<tr>"
    }
    set text [pcdata_html $text 0 1]
    if {[string compare [string trim $text] ""]} {
        set ttcol_html_headP 1
    }
    set attrs ""
    if {[string compare $align ""]} {
        append attrs " align=\"$align\""
    }
    # We shouldn't have to add an align attribute to <th> since it's
    # already in <col>, but Mozilla isn't standards-compliant.
    append ttcol_html_head "<th$attrs>$text</th>"
    if {[string compare $width ""]} {
        # We interpret our em to be a width (one character large).
        # CSS1, however, supports both em and ex but interprets
        # them both as _heights_ relative to the current font size
        # (full height and height of the letter x, respectively).
        # CSS2 is more normal.
        # There is no such thing as a CSS en.
        # Using a CSS em is usually too large, but using a CSS ex
        # is usually too narrow; what else to do?
        switch -regexp -- $width {
            {^0+$}       { set attr " width=\"0\"" }
            {^[0-9]+%$}  { set attr " width=\"$width\"" }
            {^[0-9]*\*$} { set attr " width=\"$width\"" }
            {^[0-9]+em$} { set attr " style=\"width: $width\"" }
            default      { set attr "" }
        }
        append attrs $attr
    }
    append ttcol_html_cols "<col$attrs>"
    if {[string compare $attrs ""]} {
        set ttcol_html_colsP 1
    }
    if {$x == [lindex $col 1]} {
        if {$ttcol_html_colsP} {
            write_html $ttcol_html_cols
        }
        append ttcol_html_head "</tr>"
        if {$ttcol_html_headP} {
            write_html $ttcol_html_head
        }
    }
}
proc c_html {tag row col align width} {
    global emptyP
    switch -- $tag {
        begin {
            if {[lindex $col 0] == 1} {
                write_html "<tr>"
            }
            set attrs ""
            if {[string compare $align ""]} {
                append attrs " align=\"$align\""
            }
            # We shouldn't have to add an align attribute to <td> since it's
            # already in <col>, but Mozilla isn't standards-compliant.
            write_html -nonewline "<td$attrs>"
            set emptyP 1
        }
        end {
            if {$emptyP} {
                write_html -nonewline " "
            }
            write_html "</td>"
            if {[lindex $col 0] == [lindex $col 1]} {
                write_html "</tr>"
                if {[lindex $row 0] == [lindex $row 1]} {
                    write_html "</table>"
                    write_html "<br clear=\"all\" />"
                }
            }
        }
    }
}
proc xref_html {text av target format {hackP 0}} {
    global elem
    global options
    array set attrs $av
    set elemY $attrs(elemN)
    array set tv [list title ""]
    array set tv $elem($elemY)
    # Turn any hyphens in value into non-breaking hyphens.
    regsub -all -- "-" $attrs(value) {\‑} attrs(value)
    set title ""
    switch -- $attrs(type) {
        section {
            set line "Section $attrs(value)"
            set title [section_title $elemY]
        }
        appendix {
            set line "Appendix $attrs(value)"
            set title [section_title $elemY]
        }
        figure {
            set line "Figure $attrs(value)"
            set title [section_title $elemY]
        }
        texttable {
            set line "Table $attrs(value)"
            set title [section_title $elemY]
        }
        cref {
            set line "Comment $attrs(value)"
            set title [cref_title $elemY]
        }
        t {
            set line "Paragraph $attrs(value)"
            set title ""
        }
        reference {
            set line "\[$attrs(value)\]"
            set s ""
            set nameA 1
            set nameN [llength [set names [ref_names $elemY]]]
            foreach name $names {
                incr nameA
                set name [lindex $name 0]
                append title $s$name
                set s [list_sep_str $nameA $nameN]
            }
            append title ", “[ref_title $elemY],” [ref_date $elemY]."
        }
        default {
            set line "\[$attrs(value)\]"
        }
    }
    regsub -all -- \"   $title {\"} title
    regsub -all -- "\r" $title { }       title
    regsub -all -- "\n" $title { }       title
    #set title " title=\"$title\""
    if {![string compare $format none]} {
        if {![string compare $text ""]} {
            return
        }
    } elseif {![string compare $text ""]} {
        switch -- $format {
            counter { set text $attrs(value) }
            title   { set text $tv(title)    }
            default { }
        }
    } elseif {$options(.EMOTICONIC)} {
        set text [emoticonic_html $text]
    }
    set post ""
    if {[string compare $text ""]} {
        switch -- $attrs(type) {
            section - appendix - figure - texttable {}
            default {
                if {![string compare $format default]} {
                    set post " $line"
                }
            }
        }
    } else {
        set text $line
    }
    #set line "<a href=\"#$target\"$title>$text</a>$post"
    set line "<a class='info' href='#$target'>$text"
    if {[string compare $title ""]} {
        append line "<span> (</span><span class='info'>$title</span><span>)</span>"
    }
    append line "</a>$post"
    if {$hackP} {
        return $line
    }
    if {![cellP $line]} {
        global emptyP
        write_html -nonewline $line
        set emptyP 0
    }
}
proc eref_html {text counter target} {
    global options
    if {![string compare $text ""]} {
        set text $target
    } elseif {$options(.EMOTICONIC)} {
        set text [emoticonic_html $text]
    }
    set line "<a href='$target'>$text</a>"
    if {![cellP $line]} {
        global emptyP
        write_html -nonewline $line
        set emptyP 0
    }
}
proc cref_html {text counter source anchor} {
    global crefs
    set comments ""
    if {[string compare $source ""]} {
        set comments "${source}: "
    }
    append comments $text
    set crefs($counter) [list $anchor $source $text $comments]
    regsub -all -- \"   $comments {\"} comments
    regsub -all -- "\r" $comments { }       comments
    regsub -all -- "\n" $comments { }       comments
    #set line "<a href='#comment.$counter' title='$comments'>\[$counter\]</a>"
    set line "<a class='info' href='#comment.$counter'>\[$counter\]<span> (</span><span class='info'>$comments</span><span>)</span></a>"
    append line "<a name='$anchor'></a>"
    if {![cellP $line]} {
        global emptyP
        write_html -nonewline $line
        set emptyP 0
    }
}
proc iref_html {item subitem flags} {
    global anchorN
    set anchor anchor[incr anchorN]
    write_html -nonewline "<a name='$anchor'></a>"
    return $anchor
}
proc vspace_html {lines} {
    global options
    global hangP
    if {$lines > 5} {
        if {$options(.SLIDES) && [end_page_slides]} {
            start_page_slides
        }
        return
    }
    incr lines [expr -($hangP)]
    while {$lines >= 0} {
        incr lines -1
        write_html "<br />"
    }
    set hangP 0
}
proc spanx_html {text style} {
    set p 1
    switch -- $style {
        verb
        - vbare { set e tt              }
        vemph   { set e {tt em}         }
        vstrong { set e {tt strong}     }
        vdeluxe { set e {tt strong em}  }
        emph    { set e em;     set p 0 }
        strong  { set e strong; set p 0 }
        default { set e {};     set p 0 }
    }
    #if {$p} {
    #    regsub -all -- { } $text {\ } text
    #}
    set s ""
    set t ""
    foreach x $e {
        append s "<$x>"
        set    t "</$x>$t"
    }
    write_html -nonewline "$s$text$t"
}
# Don't need to return anything even though txt/nr versions do...
proc references_html {tag args} {
    global counter depth
    global options
    if {$options(.SLIDES) \
            && (![string compare $tag begin]) \
            && [end_page_slides]} {
        start_page_slides $options(refparent)
        return
    }
    switch -- $tag {
        begin {
            set prefix [lindex $args 0]
            set title  [lindex $args 1]
            if {($depth(references) > 1) \
                    && (![info exists counter(references)])} {
                set counter(references) 0
                section_html [lindex [split $prefix .] 0]. 1 \
                             $options(refparent) 0 rfc.references
            }
            write_html ""
            if {![info exists counter(references)]} {
                set suffix 1
            } else {
                set suffix [incr counter(references)]
            }
            toc_html rfc.references$suffix
            write_html -nonewline "<$options(.TOPTAG)>$prefix "
            pcdata_html $title
            write_html "</$options(.TOPTAG)>"
            write_html "<table width=\"99%\" border=\"0\">"
        }
        end {
            write_html "</table>"
        }
    }
}
proc reference_html {prefix names title series formats date anchor target
                     target2 width annotations} {
    global options
    global rfcTxtHome rfcHtmlHome idTxtHome
    if {[string compare $target2 ""]} {
        set prefix "<a href=\"$target2\">$prefix</a>"
    }
    if {[string compare $anchor ""]} {
        set prefix "<a name=\"$anchor\">\[$prefix\]</a>"
    }
    write_html "<tr><td class=\"author-text\" valign=\"top\">$prefix</td>"
    set text ""
    set s ""
    set nameA 1
    set nameN [llength $names]
    foreach name $names {
        incr nameA
        if {[string compare [set eref [lindex $name 1]] ""]} {
            set name "<a href=\"$eref\">[lindex $name 0]</a>"
        } else {
            set name [lindex $name 0]
        }
        append text $s$name
        set s [list_sep_str $nameA $nameN]
    }
    if {![string compare $target ""]} {
        foreach serial $series {
            if {[regexp -nocase -- "rfc (\[0-9\]*)" $serial x n] == 1} {
#               set target $rfcTxtHome/rfc$n.txt
                set target $rfcHtmlHome/rfc$n
                break
            }
            if {[regexp -nocase -- "internet-draft (draft-.*)" $serial x n] \
                    == 1} {
                set target $idTxtHome/$n.txt
                break
            }
        }
    }
    if {(![string compare $target ""]) && ([llength $formats] == 1)} {
        array set fv [lindex $formats 0]
        if {[info exists fv(target)]} {
            set target $fv(target)
            set formats {}
        }
    }
    if {[string compare $target ""]} {
        set title "<a href=\"$target\">$title</a>"
    }
    append text "$s“$title"
    set r "”"
    foreach serial $series {
        if {$options(.NOTEDRAFTINPROGRESS)} {
          if {[regexp -nocase -- "internet-draft (draft-.*)" $serial x n] == 1} {
              set serial "$n (work in progress)"
          }
        }
        append text ",$r $serial"
        set r ""
    }
    if {[string compare $date ""]} {
        append text ",$r $date"
        set r ""
    }
    set s "$r ("
    set t ".$r"
    foreach format $formats {
        catch { array unset fv }
        array set fv $format
        if {[info exists fv(target)]} {
            append text "$s<a href=\"$fv(target)\">$fv(type)</a>"
            set s ", "
            set t ")."
        }
    }
    append text $t
    write_html -nonewline "<td class=\"author-text\">"
    pcdata_html $text
    while {[llength $annotations] > 0} {
        write_html "<p>"
        write_html [lindex $annotations 0]
        write_html "</p>"
        set annotations [lrange $annotations 1 end]
    }
    write_html "</td></tr>"
}
proc crefs_html {title} {
    global crefs
    global options
    write_html ""
    toc_html rfc.comments
    write_html -nonewline "<$options(.TOPTAG)>"
    pcdata_html $title
    write_html "</$options(.TOPTAG)>"
    write_html "<table border=\"0\">"
    set names [lsort -dictionary [array names crefs]]
    foreach cref $names {
        write_html "<tr><td class=\"author-text\" valign=\"top\">"
        #write_html "<a href=\"#[lindex $crefs($cref) 0]\" title=\"$cref\">"
        #pcdata_html [lindex $crefs($cref) 1]
        #write_html "</a><a name=\"comment.$cref\"></a>:"
        #write_html "</td><td class=\"author-text\">"
        write_html "<a class=\"info\" href=\"#[lindex $crefs($cref) 0]\">"
        write_html "$cref</a><a name=\"comment.$cref\"></a>:"
        write_html "</td><td class=\"author-text\">"
        if {[string compare [set source [lindex $crefs($cref) 1]] ""]} {
            write_html -nonewline "${source}: "
        }
        pcdata_html [lindex $crefs($cref) 2]
        write_html "</td></tr>"
    }
    write_html "</table>"
}
proc annotation_html {tag} {
    annotation_txt $tag
}
proc authors_html {authors} {
    global contacts
    global options
    global authorspg
    set authorspg rfc.authors
    if {!$options(.AUTHORSHIP)} {
        return
    }
    switch -- [llength $authors] {
        0       { return }
        1       { set s1 "'s"; set s2 ""   }
        default { set s1 "s'"; set s2 "es" }
    }
    write_html ""
    toc_html rfc.authors
    write_html "<$options(.TOPTAG)>Author$s1 Address$s2</$options(.TOPTAG)>"
    write_html \
         "<table width=\"99%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"
    set s ""
    foreach author $authors {
        set block1 [lindex $author 0]
        set block2 [lindex $author 1]
        if {[string compare $s ""]} {
            write_html $s
        }
        foreach line $block1 {
            write_html "<tr><td class=\"author-text\"> </td>"
            write_html "<td class=\"author-text\">$line</td></tr>"
        }
        foreach contact $block2 {
            set key [lindex $contact 0]
            set value [lindex [lindex $contacts \
                                      [lsearch0 $contacts $key]] 1]
            if {$options(.RFCEDSTYLE) && ![string compare $key email]} {
                regsub -- m $value M value
            }
            write_html "<tr><td class=\"author\" align=\"right\">$value: </td>"
            set value [lindex $contact 1]
            switch -- $key {
                email {
                    if {$options(.LINKMAILTO)} {
                        set value "<a href=\"mailto:$value\">$value</a>"
                    }
                }
                uri {
                    set value "<a href=\"$value\">$value</a>"
                }
            }
            write_html "<td class=\"author-text\">$value</td></tr>"
        }
        set s "<tr cellpadding=\"3\"><td> </td><td> </td></tr>"
    }
    write_html "</table>"
}
proc back_html {} {
}
proc xxxx_html {{anchor {}} } {
    global elem
    global options
    if {$options(.PRIVATE)} {
        toc_html $anchor
        return
    } else {
        array set rv $elem(1)
        if {![string compare [set number $rv(number)] ""]} {
            toc_html $anchor
            return
        }
    }
    if {[string compare $anchor ""]} {
        write_html "<a name=\"$anchor\"></a><hr />"
    }
    write_html "
<table border=\"0\" cellpadding=\"0\" cellspacing=\"2\" width=\"30\" align=\"right\">
    <tr>
        <td class=\"RFCbug\">
                <span class=\"RFC\"> RFC </span><br /><span class=\"hotText\"> $number </span>
        </td>
    </tr>"
    if {$options(.TOC)} {
        write_html "    <tr><td class=\"TOCbug\"><a href=\"#toc\"> TOC </a><br /></td></tr>"
    }
    write_html "</table>"
}
proc toc_html {anchor} {
    global options
    if {[string compare $anchor ""]} {
        write_html "<a name=\"$anchor\"></a><br /><hr />"
    }
    if {!$options(.TOC)} {
        return
    }
    if {[string compare $anchor toc]} {
        write_html "<table summary=\"layout\" cellpadding=\"0\" cellspacing=\"2\" class=\"TOCbug\" align=\"right\"><tr><td class=\"TOCbug\"><a href=\"#toc\"> TOC </a></td></tr></table>"
    }
}
proc pcdata_html {text {pre 0} {nowrite 0} {spans {}} {divs {}} } {
    global options
    global doingP needP
    global imgP
    if {$imgP} {
        return
    }
    # Do colorization first because spans are indexed from the original text.
    if {[llength $spans] > 0} {
        set data $text
        set text ""
        set pos 0
        foreach span $spans {
            foreach {t p l} $span {break}
            if {$pos < $p} {
                append text [html_quote [string range $data $pos [expr $p - 1]]]
            } elseif {$pos >= $p + $l} {
                continue
            } elseif {$pos > $p} {
                incr l [expr $p - $pos]
                set p $pos
            }
            set pos [expr $p + $l]
            if {$l > 0} {
                switch -- $t {
                    def      { set e dfn }
                    com      { set e em }
                    key - id { set e cite; set c $t }
                    default  { set e span; set c $t }
                }
                set spn "<$e"
                if {[info exists c]} {
                    append spn " class='$c'"
                    unset c
                }
                append spn ">"
                append spn [html_quote [string range $data $p [expr $pos - 1]]]
                append spn "</$e>"
                append text $spn
            }
        }
        append text [html_quote [string range $data $pos end]]
    } elseif {[llength $divs] > 0} {
        set text [html_quote $text]
    }
    set lines ""
    regsub -all -nocase -- {'} $text {\'} text
    set text [html_expand $text]
    if {$pre} {
        set needP 0
        regsub -line -all -- {[ \t]*$} $text "" text
        if {![slide_pre $text]} {
            if {$doingP} {
                append lines "</p>\n"
            }
            append lines [pre_tag_html begin]
            append lines $text
            append lines [pre_tag_html end]
            if {$doingP} {
                append lines "<p>\n"
            }
        }
    } else {
        if {$options(.EMOTICONIC)} {
            set text [emoticonic_html $text]
        }
        append lines $text
    }
    if {$nowrite} {
        return $lines
    }
    if {![cellP $lines]} {
        global emptyP
        if {$needP} {
            set doingP 1
            set needP 0
            write_html -nonewline "<p>"
        }
        write_html -nonewline $lines
        set emptyP 0
    }
}
proc emoticonic_html {text} {
    foreach {ei begin end} [list *  <strong> </strong> \
                                 '  <b>      </b>      \
                                {"} <b>      </b>] {
        set body ""
        while {[set x [string first "|$ei" $text]] >= 0} {
            if {$x > 0} {
                append body [string range $text 0 [expr $x-1]]
            }
            append body "$begin"
            set text [string range $text [expr $x+2] end]
            if {[set x [string first "|" $text]] < 0} {
                error "missing close for |$ei"
            }
            if {$x > 0} {
                append body [string range $text 0 [expr $x-1]]
            }
            append body "$end"
            set text [string range $text [expr $x+1] end]
        }
        append body $text
        set text $body
    }
    return $text
}
#           }}}3 Main html mode
#           {{{3 Slides sub-mode
catch {
    package require Trf
}
set leftGif \
"R0lGODlhFAAWAKEAAP///8z//wAAAAAAACH+TlRoaXMgYXJ0IGlzIGluIHRoZSBwdWJsaWMgZG9t
YWluLiBLZXZpbiBIdWdoZXMsIGtldmluaEBlaXQuY29tLCBTZXB0ZW1iZXIgMTk5NQAh+QQBAAAB
ACwAAAAAFAAWAAACK4yPqcvN4h6MSViK7MVBb+p9TihKZERqaDqNKfbCIdd5dF2CuX4fbQ9kFAAA
Ow=="
set rightGif \
"R0lGODlhFAAWAKEAAP///8z//wAAAAAAACH+TlRoaXMgYXJ0IGlzIGluIHRoZSBwdWJsaWMgZG9t
YWluLiBLZXZpbiBIdWdoZXMsIGtldmluaEBlaXQuY29tLCBTZXB0ZW1iZXIgMTk5NQAh+QQBAAAB
ACwAAAAAFAAWAAACK4yPqcsd4pqAUU1az8V58+h9UtiFomWeSKpqZvXCXvZsdD3duF7zjw/UFQAA
Ow=="
set upGif \
"R0lGODlhFAAWAKEAAP///8z//wAAAAAAACH+TlRoaXMgYXJ0IGlzIGluIHRoZSBwdWJsaWMgZG9t
YWluLiBLZXZpbiBIdWdoZXMsIGtldmluaEBlaXQuY29tLCBTZXB0ZW1iZXIgMTk5NQAh+QQBAAAB
ACwAAAAAFAAWAAACI4yPqcvtD6OcTQgarJ1ax949IFiNpGKaSZoeLIvF8kzXdlAAADs="
proc end_rfc_slides {} {
    global ifile
    global passno
    global slideno slidewd slidemx
    if {$passno != 2} {
        end_page_slides
        return 1
    }
    set slidemx $slideno
    set slidewd [expr int(log10($slideno))+1]
    foreach file [glob -nocomplain [file rootname $ifile]-*.html] {
        catch { file delete -force $file }
    }
    if {![string compare [info commands base64] base64]} {
        set inputD [file dirname $ifile]
        foreach gif {left right up} {
            global ${gif}Gif
            if {![file exists [set file [file join $inputD ${gif}.gif]]]} {
                set fd [open $file {WRONLY CREAT TRUNC}]
                fconfigure $fd -translation binary
                puts -nonewline $fd [base64 -mode decode -- [set ${gif}Gif]]
                catch { close $fd }
            }
        }
    }
    return 0
}
proc front_slides_begin {left right top bottom title} {
    global passno
    global out_fd
    global slideno slideft
    set slideno 0
    start_page_slides [set slideft [lindex $title 0]]
    if {$passno == 2} {
        return 0
    }
    set size 4
    puts $out_fd "<br /><br /><br /><br /><p align=\"right\">"
    puts $out_fd "<table width=\"75%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"
    puts $out_fd "<tr><td>"
    puts $out_fd "<table width=\"100%\" border=\"0\" cellpadding=\"2\" cellspacing=\"1\">"
    set left [munge_long $left]
    set right [munge_long $right]
    set lc ""
    set rc ""
    foreach l $left r $right {
        if {[string compare $l ""]} {
            set l $l
        } else {
            set l " "
        }
        if {[string compare $r ""]} {
            set r $r
        } else {
            set r " "
        }
        puts $out_fd "<tr valign=\"top\">"
        puts $out_fd "<td width=\"33%\"><font color=\"#006600\" size=\"+$size\">$l</font></td>"
        puts $out_fd "<td width=\"33%\"><font color=\"#006600\" size=\"+$size\">$r</font></td>"
        puts $out_fd "</tr>"
        set size 3
    }
    puts $out_fd "</table>"
    puts $out_fd "</td></tr>"
    puts $out_fd "</table>"
    puts $out_fd "</p>"
    return 1
}
proc start_page_slides {{title ""}} {
    global passno
    global ifile
    global out_fd
    global slideno slidenm
    if {$passno < 3} {
        return
    }
    if {$slideno == 0} {
        catch { close $out_fd }
        set out_fd ""
        catch { file delete -force [file rootname].html }
    }
    set out_fd [open [file rootname $ifile]-[set p [slide_foo $slideno]].html \
                     { WRONLY CREAT TRUNC }]
    catch { fconfigure $out_fd -encoding utf-8 }
    if {[string compare $title ""]} {
        set slidenm $title
    } else {
        set title "$slidenm (continued)"
    }
    if {$slideno != 0} {
        append p ": "
    } else {
        set p ""
    }
    write_html "<\!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"
    puts $out_fd "<html><head><title>"
    pcdata_html $p$title
    puts $out_fd "</title></head>"
    puts $out_fd "<body text=\"#000000\" vlink=\"#006600\" alink=\"#ccddcc\" link=\"#006600\"\n      bgcolor=\"#ffffff\">"
    puts $out_fd "<font face=\"arial, helvetica, sans-serif\">"
    puts $out_fd "<table height=\"100%\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\" border=\"0\">"
    puts $out_fd "<tbody><tr><td valign=\"top\">"
    puts $out_fd "<table height=\"100%\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\" border=\"0\">"
    puts $out_fd "<tbody><tr><td valign=\"top\">"
    puts $out_fd "<p><font color=\"#006600\" size=\"+5\">$title</font></p>"
    puts $out_fd "<br /><br />"
    puts $out_fd "<font size=\"+3\">"
}
proc end_page_slides {} {
    global passno
    global ifile
    global out_fd
    global slideno slidemx slideft
    if {$passno < 3} {
        incr slideno
        return 0
    }
    set up [file rootname [file tail $ifile]]-[slide_foo 0].html
    if {[set left [expr $slideno-1]] < 0} {
        set left $slidemx
    }
    set left [file rootname [file tail $ifile]]-[slide_foo $left].html
    if {[set right [expr $slideno+1]] > $slidemx} {
        set right 0
    }
    set right [file rootname [file tail $ifile]]-[slide_foo $right].html
    puts $out_fd "</font>"
    puts $out_fd "</td></tr></tbody>"
    puts $out_fd "</table>"
    puts $out_fd "</td><td valign=\"bottom\" align=\"right\">"
    puts -nonewline \
         $out_fd "<p align=\"right\"><nobr>"
    puts -nonewline \
         $out_fd "<a href=\"$left\"><img src=\"left.gif\" border=\"0\" width=\"20\" height=\"22\" /></a>"
    puts -nonewline \
         $out_fd "<a href=\"$up\"><img src=\"up.gif\" border=\"0\" width=\"20\" height=\"22\" /></a>"
    puts -nonewline \
         $out_fd "<a href=\"$right\"><img src=\"right.gif\" border=\"0\" /></a>"
    puts $out_fd "</nobr></p>"
    puts $out_fd "</td></tr>"
    puts $out_fd "<tr><td align=\"right\" colspan=\"2\">"
    puts $out_fd "<font color=\"#006600\" size=\"-3\">"
    pcdata_html $slideft
    pcdata_html "</font>"
    puts $out_fd "</td></tr></tbody>"
    puts $out_fd "</table>"
    puts $out_fd "</font></body></html>"
    catch { close $out_fd }
    set out_fd ""
    incr slideno
    return 1
}
proc slide_pre {text} {
    global passno
    global out_fd
    global doingP needP
    if {$passno < 3} {
        return 0
    }
    set needP 0
    set t ""
    if {$doingP} {
        append t "</p>\n"
    }
    append t [pre_tag_html begin]
    append t $text
    append t [pre_tag_html end]
    if {$doingP} {
        append t "<p>\n"
    }
    puts -nonewline $out_fd $t
    return 1
}
proc slide_foo {n} {
    global slidewd
    return [format %*.*d $slidewd $slidewd $n]
}
#           }}}3 Slides sub-mode
#           {{{3 Other html mode stuff
proc pre_tag_html {tag} {
    set str ""
    switch -- $tag {
        begin {
            set ml auto
            set mr auto
            append str "<div style='display: table; width: 0; "
            set b [current_align_bias]
            switch -- [current_align] {
                center  {}
                right   {
                    if {$b < 0} {
                        set mr [expr -($b)]em
                    } else {
                        set mr 0
                    }
                }
                default {
                    incr b 3
                    if {$b > 0} {
                        set ml [expr $b]em
                    } else {
                        set ml 0
                    }
                }
            }
            append str "margin-left: $ml; margin-right: $mr'>"
            append str "<pre>"
        }
        end {
            append str "</pre></div>"
        }
    }
    return $str
}
proc pi_html {key value} {
    switch -- $key {
        needLines {}
        typeout {
            global passno
            if {$passno == 2} {
                puts stdout $value
            }
        }
        default { error "" }
    }
}
proc write_html {a1 {a2 ""}} {
    global options
    global passno
    global out_fd
    if {$options(.SLIDES) || $passno >= 2} {
        set command [list puts]
        if {![string compare $a1 -nonewline]} {
            lappend command -nonewline
            set a1 $a2
        }
        eval $command [list $out_fd $a1]
    }
}
#           }}}3 Other html mode stuff
#       }}}2 html rendering engine
#       {{{2 nr(off) rendering engine
proc rfc_nr {irefs authors iprstmt copying newP validity} {
    global options copyrightP iprP
    global funding
    global pageno
    global indexpg
    global page_basic_indent
    if {[llength $irefs] > 0} {
        if {!$options(.COMPACT) || ![have_lines 4]} {
            end_page_nr
        } else {
            write_line_nr ""
        }
        if {!$options(.RFCEDSTYLE)} {
            write_line_nr "" -1
        }
        set indexpg $pageno
        condwrite_in_nr 0 1
        write_line_nr "Index"
        condwrite_in_nr 12 1
        foreach iref $irefs {
            foreach {L item subitem flags pages} $iref { break }
            if {[string compare $L ""]} {
                write_it ".br"
                write_line_nr ""
                write_it ".ti $page_basic_indent"
                write_line_nr $L
            }
            set subitem [chars_expand $subitem]
            if {[string compare $item ""]} {
                write_it ".br"
                do_indent_text_nr [chars_expand $item] 6
                if {[string compare $subitem ""]} {
                    flush_text
                    write_it ".br"
                    do_indent_text_nr $subitem 9
                }
            } else {
                write_it ".br"
                do_indent_text_nr $subitem 9
            }
            write_text_nr "  [collapsed_num_list $pages]"
            flush_text
        }
        #condwrite_in_nr 0 1
    }
    authors_nr $authors
    if {(!$options(.PRIVATE)) && $copyrightP > 0} {
        end_page_nr
        if {!$options(.RFCEDSTYLE)} {
            write_line_nr "" -1
        }
        set result $pageno
        condwrite_in_nr $page_basic_indent 1
        # See comment in "proc rfc_txt" about this content.
        write_it ".ti 0"
        if {0 && $newP} {
            write_line_nr "Copyright Statement"
        } else {
            write_line_nr "Full Copyright Statement"
        }
        foreach para $copying {
            write_line_nr ""
            pcdata_nr $para
        }
        if {$newP} {
            #if {![have_lines 4]} {
            #    end_page_nr
            #}
            #write_it ".ti 0"
            #write_line_nr "Disclaimer of Validity"
            foreach para $validity {
                write_line_nr ""
                pcdata_nr $para
            }
        }
        write_line_nr "" -1
        if {!$options(.RFCEDSTYLE)} {
            write_line_nr "" -1
        }
        if {$iprP} {
            global iprurl ipremail
            if {![have_lines 4]} {
                end_page_nr
            }
            write_it ".ti 0"
            write_line_nr "Intellectual Property"
            regsub -all -- %IPRURL% $iprstmt $iprurl iprstmt
            regsub -all -- %IPREMAIL% $iprstmt $ipremail iprstmt
            foreach para $iprstmt {
                write_line_nr ""
                pcdata_nr $para
            }
            write_line_nr "" -1
            if {!$options(.RFCEDSTYLE)} {
                write_line_nr "" -1
            }
        }
        if {![have_lines 4]} {
            end_page_nr
        }
        write_it ".ti 0"
        if {$options(.RFCEDSTYLE)} {
            set ack "Acknowledgement"
        } else {
            set ack "Acknowledgment"
        }
        set acks 0
        if {[string length $funding]} {
            incr acks 1
        }
        if {$options(.RFCPROCACK)} {
            incr acks 1
        }
        if {$acks > 1} {
            append ack s
        }
        if {$acks} {
            write_line_nr $ack
            write_line_nr ""
        }
        if {[string length $funding]} {
            pcdata_nr $funding
        }
        if {$options(.RFCPROCACK)} {
            global prog_ack prog_url
            regsub -all -- %PROGURL% $prog_ack $prog_url xml2rfc_ack
            if {[string length $funding]} {
                pcdata_nr "  "
            }
            pcdata_nr $xml2rfc_ack
        }
    } else {
        set result ""
    }
    flush_text
    return $result
}
proc front_nr_begin {left right top bottom title keywords lang} {
    global prog prog_version
    global options copyrightP
    global lineno pageno blankP
    global eatP nofillP indent lastin
    global passno indexpg authorspg
    global page_width page_basic_indent
    set lineno 1
    set pageno 1
    set blankP 0
    set eatP 0
    set lastin -1
    write_it [clock format [clock seconds] \
                    -format ".\\\" automatically generated by $prog $prog_version on %Y-%m-%dT%H:%M:%SZ" \
                    -gmt true]
    set wi [expr $page_width / 10.0]i
    write_it ".\\\" "
    write_it ".pl 10.0i"
    write_it ".po 0"
    write_it ".ll $wi"
    write_it ".lt $wi"
    write_it ".nr LL $wi"
    write_it ".nr LT $wi"
    write_it ".ds LF [nbsp_expand_nr [chars_expand [lindex $bottom 0]]]"
    write_it ".ds RF FORMFEED\[Page %]"
    write_it ".ds CF [nbsp_expand_nr [chars_expand [lindex $bottom 1]]]"
    write_it ".ds LH [nbsp_expand_nr [chars_expand [lindex $top 0]]]"
    write_it ".ds RH [nbsp_expand_nr [chars_expand [lindex $top 2]]]"
    write_it ".ds CH [nbsp_expand_nr [chars_expand [lindex $top 1]]]"
    write_it ".hy 0"
    write_it ".nh"
    write_it ".ad l"
    set nofillP -1
    condwrite_nf_nr
    if {$passno == 2} {
        set indexpg 0
        set authorspg 0
    }
    incr lineno 2
    condwrite_in_nr 0 1
    if {$options(.TOPBLOCK)} {
        set left [munge_long $left]
        set right [munge_long $right]
        foreach l $left r $right {
            set l [chars_expand $l]
            set r [chars_expand $r]
            set len [expr $page_width - [string length $l]]
            write_line_nr [format %s%*.*s $l $len $len $r]
        }
        write_line_nr "" -1
        write_line_nr "" -1
    }
    foreach line $title {
        write_text_nr [chars_expand $line] c
    }
    write_line_nr "" -1
    condwrite_in_nr $page_basic_indent 1
}
proc write_status_nr {status copying afterP} {
    global options copyrightP iprP
    global page_basic_indent
    if {$afterP} {
        write_line_nr "" -1
        condwrite_in_nr $page_basic_indent 1
    }
    if {!$options(.PRIVATE)} {
        write_it ".ti 0"
        if {$options(.RFCEDSTYLE)} {
            write_line_nr "Status of This Memo"
        } else {
            write_line_nr "Status of this Memo"
        }
        foreach para $status {
            write_line_nr ""
            pcdata_nr $para
        }
    }
    if {(!$options(.PRIVATE)) && $copyrightP && [string length $copying]} {
        write_line_nr "" -1
        write_it ".ti 0"
        write_line_nr "Copyright Notice"
        foreach para $copying {
            write_line_nr "" -1
            pcdata_nr $para
        }
    }
}
proc front_nr_end {toc} {
    front_txt_end $toc
}
proc write_toc_nr {s1 title s2 len dot} {
    write_toc_txt $s1 $title $s2 $len $dot
}
proc abstract_nr {} {
    global options
    if {(!$options(.COMPACT) && !$options(.ABSTRACT1ST)) || ![have_lines 4]} {
        end_page_nr
    } else {
        write_line_nr ""
    }
    write_it ".ti 0"
    write_line_nr "Abstract"
    write_line_nr "" -1
}
proc note_nr {title depth} {
    global options
    if {!$options(.COMPACT) || ![have_lines 4]} {
        end_page_nr
    } else {
        write_line_nr ""
    }
    write_it ".ti 0"
    write_line_nr [chars_expand $title]
    write_line_nr "" -1
}
proc section_nr {prefix top title lines anchor} {
    global options
    global pageno
    global page_basic_indent
    if {($top && !$options(.COMPACT)) || (![have_lines [expr $lines + 2]])} {
        end_page_nr
    } else {
        write_line_nr ""
    }
    if {$top && !$options(.RFCEDSTYLE)} {
        write_line_nr "" -1
    }
    indent_text_nr "$prefix  " 0
    write_text_nr [chars_expand $title]
    flush_text
    pop_indent
    condwrite_in_nr $page_basic_indent 1
    return $pageno
}
proc t_nr {tag counter style hangText editNo} {
    t_txt $tag $counter $style $hangText $editNo
}
proc list_nr {tag min max style hangIndent longestHangText suprT} {
    list_txt $tag $min $max $style $hangIndent $longestHangText $suprT
}
proc figure_nr {tag lines anchor title av {suppressP 0}} {
    figure_txt $tag $lines $anchor $title $av $suppressP
}
proc artwork_nr {tag lines {av {}} } {
    artwork_txt $tag $lines $av
}
proc preamble_nr {tag {editNo ""}} {
    preamble_txt $tag $editNo
}
global tblindent
set tblindent 0
proc postamble_nr {tag {editNo ""}} {
    global tblindent
    postamble_txt $tag $editNo
    if {![string compare $tag "begin"] && ($tblindent > 0)} {
        condwrite_in_nr $tblindent
    }
    set tblindent 0
}
proc texttable_nr {tag lines anchor title {suppressP 0}} {
    global tblindent
    set rc [texttable_txt $tag $lines $anchor $title $suppressP]
    if {![string compare $tag "end"] && ($tblindent > 0)} {
        condwrite_in_nr $tblindent
    }
    set tblindent 0
    return rc
}
proc ttcol_nr {text align col width cwidth} {
    global tblindent indent
    if {$tblindent == 0} {
        flush_text
        set tblindent $indent
        condwrite_in_nr 0
    }
    ttcol_txt $text $align $col $width $cwidth
}
proc c_nr {tag row col align width} {
    c_txt $tag $row $col $align $width
}
proc xref_nr {text av target format {hackP 0}} {
    condwrite_fi_nr
    xref_txt $text $av $target $format $hackP
}
proc eref_nr {text counter target} {
    condwrite_fi_nr
    eref_txt $text $counter $target
}
proc cref_nr {text counter source anchor} {
    condwrite_fi_nr
    cref_txt $text $counter $source $anchor
}
proc iref_nr {item subitem flags} {
    global pageno
    return $pageno
}
proc vspace_nr {lines} {
    vspace_txt $lines
}
proc spanx_nr {text style} {
    condwrite_fi_nr
    spanx_txt $text $style
}
proc references_nr {tag arg0 {arg1 ""}} {
    references_txt $tag $arg0 $arg1
}
proc erefs_nr {{title ""}} {
    global erefs
    global options
    if {[string compare $title ""]} {
        if {$options(.COMPACT)} {
            write_line_nr ""
        } else {
            end_page_nr
        }
        condwrite_fi_nr
        write_it ".ti 0"
        write_line_nr $title
    }
    set names  [lsort -integer [array names erefs]]
    set width [expr [string length [lindex $names end]]+2]
    foreach eref $names {
        write_line_nr ""
        indent_text_nr "[format %-*.*s $width $width "\[$eref\]"]  " -1
        write_url $erefs($eref)
        flush_text
        pop_indent
    }
    flush_text
}
proc crefs_nr {title} {
    global crefs
    global options
    if {[string compare $title ""]} {
        if {$options(.COMPACT)} {
            write_line_nr ""
        } else {
            end_page_nr
        }
        condwrite_fi_nr
        write_it ".ti 0"
        write_line_nr $title
    }
    set names  [lsort -dictionary [array names crefs]]
    set width 0
    foreach cref $names {
        set x [string length $cref]
        if {$x > $width} {
            set width $x
        }
    }
    incr width 2
    foreach cref $names {
        write_line_nr ""
        indent_text_nr "[format %-*.*s $width $width "\[$cref\]"]  " -1
        write_text_nr [chars_expand [lindex $crefs($cref) 3]]
        flush_text
        pop_indent
    }
    flush_text
}
proc reference_nr {prefix names title series formats date anchor target
                   target2 width annotations} {
    global options
    global max_ref_width
    global page_basic_indent
    write_line_nr ""
    if {($width > $max_ref_width) && !$options(.RFCEDSTYLE)} {
        set width $max_ref_width
    }
    set i [string length $prefix]
    set prefix [format %-*s [expr $width + 2] "\[$prefix\]"]
    if {$i > $width} {
        # The indent_text_nr abstraction isn't robust enough to figure this out...
        global indent
        flush_text
        condwrite_fi_nr
        push_indent [expr $page_basic_indent + $width + 4 - $indent]
        condwrite_in_nr $indent
        write_it ".ti $page_basic_indent"
        write_line_nr $prefix
        write_it ".br"
    } else {
        indent_text_nr "$prefix  " $page_basic_indent
    }
    set s ""
    set nameA 1
    set nameN [llength $names]
    foreach name $names {
        incr nameA
        write_text_nr $s[chars_expand [lindex $name 0]]
        set s [list_sep_str $nameA $nameN]
    }
    write_text_nr "$s\"[chars_expand $title]\""
    foreach serial $series {
        if {$options(.NOTEDRAFTINPROGRESS)} {
          if {[regexp -nocase -- "internet-draft (draft-.*)" $serial x n] == 1} {
              set serial "$n (work in progress)"
          }
        }
        write_text_nr ", [chars_expand $serial]"
    }
    if {[string compare $date ""]} {
        write_text_nr ", [chars_expand $date]"
    }
    if {[string compare $target ""]} {
        write_text_nr ", "
        write_url $target
    }
    write_text_nr .
    while {[llength $annotations] > 0} {
        write_line_nr ""
        pcdata_nr [lindex $annotations 0]
        set annotations [lrange $annotations 1 end]
    }
    pop_indent
}
proc annotation_nr {tag} {
    annotation_txt $tag
}
proc authors_nr {authors} {
    global options
    global lineno pageno
    global contacts
    global authorspg
    global page_basic_indent
    if {!$options(.AUTHORSHIP)} {
        return
    }
    switch -- [llength $authors] {
        0       { return }
        1       { set s1 "'s"; set s2 ""   }
        default { set s1 "s'"; set s2 "es" }
    }
    set s "Author$s1 Address$s2"
    if {!$options(.COMPACT) || ![have_lines 4]} {
        end_page_nr
    } else {
        write_line_nr ""
    }
    if {!$options(.RFCEDSTYLE)} {
        write_line_nr "" -1
    }
    set authorspg $pageno
    condwrite_in_nr $page_basic_indent 1
    condwrite_nf_nr
    set firstP 1
    foreach author $authors {
        set block1 [lindex $author 0]
        set block2 [lindex $author 1]
        set lines 4
        incr lines [llength $block1]
        incr lines [llength $block2]
        if {![have_lines $lines]} {
            end_page_nr
        }
        if {[string compare $s ""]} {
            write_it ".ti 0"
            write_line_nr $s
            set s ""
        } else {
            write_line_nr "" -1
        }
        write_line_nr "" -1
        foreach line $block1 {
            write_line_nr [chars_expand $line]
        }
        if {[llength $block2] > 0} {
            write_line_nr ""
            foreach contact $block2 {
                set key [lindex $contact 0]
                set value [lindex [lindex $contacts \
                                          [lsearch0 $contacts $key]] 1]
                if {$options(.RFCEDSTYLE) && ![string compare $key email]} {
                    regsub -- m $value M value
                }
                set value [format %-6s $value:]
                if {$options(.COLONSPACE)} {
                    append value " "
                }
                write_line_nr "$value [chars_expand [lindex $contact 1]]"
            }
        }
    }
}
proc back_nr {} {
}
proc pcdata_nr {text {pre 0} {nowrite 0} {spans {}} {divs {}} } {
    global eatP
    global options
    global pcdata_line_offset
    global page_basic_indent
    if {[llength $spans] > 0 || [llength $divs] > 0} {
        set text [html_quote $text]
    }
    if {(!$pre) && ($eatP > 0)} {
        set text [string trimleft $text]
    }
    if {[string length $text] <= 0} {
        # Was only white space, but got trimmed.
        return
    }
    set eatP 0
    if {!$pre} {
        regsub -all -- "\n\[ \t\n\]*" $text "\n" text
        regsub -all -- "\[ \t\]*\n\[ \t\]*" $text "\n" text
        set prefix ""
        if {$options(.EMOTICONIC)} {
            set text [emoticonic_txt $text]
        }
    }
    if {$pre} {
        condwrite_nf_nr
    } else {
        condwrite_fi_nr
    }
    if {[cellP $text]} {
        return
    }
    set pcdata_line_offset 0
    foreach line [split $text "\n"] {
        set line [chars_expand $line]
        if {$pre} {
            set x 0
            while {[set x [lsearch0 $divs $pcdata_line_offset $x]] >= 0} {
                if {![have_lines [lindex [lindex $divs $x] 1]]} {
                    end_page_nr
                    break
                }
                incr x
            }
            write_line_nr [string trimright $line] $pre
        } else {
            write_pcdata_nr $prefix$line
            set prefix " "
        }
        incr pcdata_line_offset
    }
    if {$pre} {
        condwrite_in_nr $page_basic_indent
    }
    set pcdata_line_offset 0
    if {[regexp -- {[ \t\n]$} $text]} {
        set eatP 1
    }
}
proc start_page_nr {} {
    global lineno blankP
    global page_head_height
    set lineno $page_head_height
    set blankP 1
}
proc end_page_nr {} {
    global lineno pageno
    global page_head_height
    flush_text
    if {$lineno <= $page_head_height} {
        return
    }
    incr pageno
    set lineno 0
    write_it ".bp"
}
proc indent_text_nr {prefix {left ""}} {
    global indent
    global page_basic_indent
    flush_text
    condwrite_fi_nr
    if {![string compare $left ""]} {
        set left $indent
        while {![string compare [string index $prefix 0] " "]} {
            incr left
            set prefix [string range $prefix 1 end]
        }
        push_indent $page_basic_indent
    } elseif {$left < 0} {
        if {$left == -1} {
            set left $indent
        }
        push_indent [string length $prefix]
        if {$left == -2} {
            set left $indent
            set prefix ""
        }
    } else {
        push_indent [expr $left + [string length $prefix] - $indent]
    }
    condwrite_in_nr $indent
    do_indent_text_nr $prefix $left
}
proc do_indent_text_nr {text left} {
    global buffer
    global indent
    write_it ".ti $left"
    # In case $left==0, we have to put $text in buffer ourselves now,
    # otherwise the next write_text_nr will prepend an indent and screw
    # the line-breaking algorithm (nroff can undo that) but more
    # importantly the value of lineno.  The page could end up shorter
    # as a result of an over-inflated lineno.
    set buffer [format %*s%s $left "" $text]
    if {$indent != 0 && [string length $buffer] == 0} {
        unexpected error "internal bug triggered in do_indent_text_nr; report it!"
    }
    write_text_nr ""
}
proc write_pcdata_nr {text} {
    global buffer
    if {![string compare $buffer ""]} {
        setup_align_nr begin [current_align]
    }
    write_pcdata_txt $text
}
proc write_editno_nr {editNo} {
    global buffer
    if {[string compare $buffer ""]} {
        flush_text
    }
    write_it ".ti 0"
    write_it <$editNo>
    write_it ".br"
}
proc write_text_nr {text {direction l} {magic 0}} {
    global buffer buffer_rest buffer_align
    global indent
    global page_width
    global eatP
    if {($eatP < 0) && ![regexp -- {^[.,?!]} $text]} {
        set text " $text"
    }
    switch -- $direction {
        c - r { flush_text }
    }
    if {![string compare $buffer ""]} {
        condwrite_in_nr $indent
        switch -- $direction {
            c - r {}
            default {
                setup_align_nr begin [set buffer_align [current_align]]
            }
        }
        set buffer [format %*s $indent ""]
    }
    append buffer $text
    set flush [string compare $direction l]
    while {([string length $buffer] > $page_width) || ($flush)} {
        set text [fold_text_txt]
        setup_align_nr oneshot $direction
        write_line_nr [string trimleft $text] 0 $magic
        if {![string compare [set buffer $buffer_rest] ""]} {
            setup_align_nr end $buffer_align
            set buffer_align ""
            break
        }
    }
}
proc write_line_nr {line {pre 0} {magic 0}} {
    global lineno blankP
    global page_width page_head_height page_body_height page_basic_indent
    flush_text
    if {$lineno == 0} {
        start_page_nr
    }
    if {![set x [string length [set orig_line $line]]]} {
        set blankO $blankP
        set blankP 1
        if {($blankO) && (!$pre || $lineno == $page_head_height)} {
            return
        }
    } else {
        set blankP 0
    }
    if {($pre) && ($x)} {
        condwrite_in_nr [expr $pre > 0 ? ($pre - 1) : $page_basic_indent]
        if {$pre > 0} {
            set line [tabs_expand_pre $line]
            set x [string length [set orig_line $line]]
        }
    }
    if {!$magic} {
        regsub -all -- "\\\\" $line "\\\\\\" line
    }
    regsub -all -- "'" $line "\\'" line
    set line [nbsp_expand_nr [break_unprotect $line]]
    if {[string first "." $line] == 0} {
        set line "\\&$line"
    }
    if {!($pre)} {
        regsub -all -- "\[^ \t\n\]*-" $line "\\%\&" line
    }
    write_it $line
    incr lineno
    if {$pre > 0 && [set len [expr ($pre - 1) + $x]] > $page_width} {
        global pageno
        regsub -all -- \" [string range $orig_line [expr $page_width - ($pre - 1)] end] {\"} excess
        unexpected [unex_condtype] \
            "output line $lineno (on page $pageno) has $len > $page_width characters (excess string is \"$excess\")"
    }
    if {$lineno >= $page_head_height + $page_body_height} {
        end_page_nr
    }
}
proc nbsp_expand_nr {s} {
    regsub -all -- "\xA0" [string trimright $s] "\\\\0" s
    return $s
}
proc pi_nr {key value} {
    pi_txt $key $value
}
# Only proc allowed to write a ".fi" or set nofillP to zero.
proc condwrite_fi_nr {} {
    global nofillP
    #global lastin
    if {$nofillP != 0} {
        flush_text
        write_it ".fi"
        set nofillP 0
        # Is the next line necessary on some nroff's???
        #set lastin -1
    }
}
# Only proc allowed to write a ".nf" or set nofillP positive.
proc condwrite_nf_nr {} {
    global nofillP
    if {$nofillP <= 0} {
        flush_text
        write_it ".nf"
        set nofillP 1
    }
}
# Only proc allowed to write a ".in" or update lastin.
proc condwrite_in_nr {in {reset 0}} {
    global lastin
    if {$lastin != $in} {
        flush_text
        write_it ".in [set lastin $in]"
        if {$reset} {
            global indents indent
            set indent $in
            set indents {}
        }
    }
}
# Assumes flush has been done.  Must NOT be done again.
proc setup_align_nr {tag dir} {
    switch -- $dir {
        c - center { set xx ce }
        r - right  { set xx rj }
        default    { return }
    }
    switch -- $tag {
        begin    { set v " 8192" }
        oneshot  { set v ""      }
        end      { set v " 0"    }
    }
    write_it ".$xx$v"
}
#       }}}2 nr(off) rendering engine
#   }}}1 Rendering engines
#   {{{1 Low-level formatting
#       {{{2 Some globals
global contacts
set contacts { {phone Phone} {facsimile Fax} {email Email} {uri URI} }
global buffer indent indents
set buffer ""
set indent $page_basic_indent
set indents {}
global rfcTxtHome rfcHtmlHome idTxtHome
set rfcTxtHome ftp://ftp.isi.edu/in-notes
set rfcHtmlHome http://tools.ietf.org/html
set idTxtHome http://www.ietf.org/internet-drafts
#       }}}2 Some globals
#       {{{2 Characters entities
global xentities oentities entities uentities
# Hex entities (?) are first converted to dec entities (?) elsewhere.
# Only put dec entities or (case-sensitive) named entities here.
# & and & must always be last and specified simultaneously.
#  , &nbhy;, and &wj; are first converted to actual characters here
#   then handled elsewhere by the txt and nr rendering engines.
set uentities [list {&rfc2629\.processor;} "$prog\\ $prog_version"]
# For compatibility with previous versions (really invalid form of mdash).
set xentities [concat $uentities [list "&#(0*151|x0*97);" "\\—"]]
set oentities $xentities
# Entity names unknown to HTML and XHTML.
foreach {e c t} {
    lpar     0x28 (         rpar     0x29 )
    lsqb     0x5B \[        rsqb     0x5D \]
    lcub     0x7B \{        rcub     0x7D \}
    sol      0x2F /         percnt   0x25 %
    num      0x23 #         dollar   0x24 \$
    ast      0x2A *         hyphen   0x2D -
    plus     0x2B +         equals   0x3D =
    comma    0x2C ,         period   0x2E .
    colon    0x3A :         semi     0x3B ;
    excl     0x21 !         quest    0x3F ?
    commat   0x40 @         lowbar   0x5F _
    circ     0x5E ^         grave    0x60 `
    bsol     0x5C \\        verbar   0x7C |
    Zcaron 0x017D Z         zcaron 0x017E z
    dash   0x2010 -         nbhy   0x2011 "\u2011"
    wj     0x2060 "\u2060"
 } {
    set c [expr $c]
    lappend xentities "&$e;"         "\\&#$c;"
    lappend oentities "&($e|#0*$c);" $t
    lappend uentities "&$e;" [format %c $c]
}
# Some entities known to HTML and XHTML.
# Note that ' is (officially) unknown to HTML.
# The second ˆ is a duplicate only useful for its numerical value.
# All arrows are the same width by design.
foreach {e c t} {
    quot     0x22 \"        apos     0x27 '
    lt       0x3C <         gt       0x3E >
    OElig  0x0152 OE        oelig  0x0153 oe
    Scaron 0x0160 S         scaron 0x0161 s
    Yuml   0x0178 Y
    fnof   0x0192 f
    circ   0x02C6 ^
    tilde  0x02DC ~
    ensp   0x2002 { }       emsp   0x2003 { }
    thinsp 0x2009 { }
    ndash  0x2013 -         mdash  0x2014 --
    lsquo  0x2018 '         rsquo  0x2019 '
    sbquo  0x201A '
    ldquo  0x201C \"        rdquo  0x201D \"
    bdquo  0x201E \"
    dagger 0x2020 *!*       Dagger 0x2021 *!!*
    bull   0x2022 o         hellip 0x2026 ...
    permil 0x2030 {[/1000]}
    prime  0x2032 '         Prime  0x2033 \"
    lsaquo 0x2039 <         rsaquo 0x203A >
    frasl  0x2044 /
    euro   0x20AC EUR       trade  0x2122 {[TM]}
    larr   0x2190 <--       lArr   0x21D0 <==
    rarr   0x2192 -->       rArr   0x21D2 ==>
    harr   0x2194 <->       hArr   0x21D4 <=>
    minus  0x2212 -         lowast 0x2217 *
    le     0x2264 <=        ge     0x2265 >=
    lang   0x2329 <         rang   0x232A >
 } {
    set c [expr $c]
    lappend oentities "&($e|#0*$c);" $t
    lappend uentities "&$e;" [format %c $c]
}
# ISO Latin 1 (named and dec) entities (all known to HTML and XHTML).
# ü should be just "u" in French, but it's so rare it can yield to "ue".
set c 160
foreach {e t} {
    nbsp   "\xA0"              iexcl  !          cent   {[cents]}  pound  GBP
    curren {[currency units]}  yen    JPY        brvbar |          sect   S.
    uml    \"                  copy   (C)        ordf   a          laquo  <<
    not    {[not]}             shy    {}         reg    (R)        macr   _
    deg    o                   plusmn +/-        sup2   ^2         sup3   ^3
    acute  '                   micro  {[micro]}  para   P.         middot .
    cedil  ,                   sup1   ^1         ordm   o          raquo  >>
    frac14 1/4                 frac12 1/2        frac34 3/4        iquest ?
    Agrave A                   Aacute A          Acirc  A          Atilde A
    Auml   Ae                  Aring  Ae         AElig  AE         Ccedil C
    Egrave E                   Eacute E          Ecirc  E          Euml   E
    Igrave I                   Iacute I          Icirc  I          Iuml   I
    ETH    {[ETH]}             Ntilde N          Ograve O          Oacute O
    Ocirc  O                   Otilde O          Ouml   Oe         times  x
    Oslash Oe                  Ugrave U          Uacute U          Ucirc  U
    Uuml   Ue                  Yacute Y          THORN  {[THORN]}  szlig  ss
    agrave a                   aacute a          acirc  a          atilde a
    auml   ae                  aring  ae         aelig  ae         ccedil c
    egrave e                   eacute e          ecirc  e          euml   e
    igrave i                   iacute i          icirc  i          iuml   i
    eth    {[eth]}             ntilde n          ograve o          oacute o
    ocirc  o                   otilde o          ouml   oe         divide /
    oslash oe                  ugrave u          uacute u          ucirc  u
    uuml   ue                  yacute y          thorn  {[thorn]}  yuml   y
 } {
    lappend oentities "&($e|#0*$c);" $t
    lappend uentities "&$e;" [format %c $c]
    incr c
}
# ASCII dec entities.
for {set c 32} {$c < 127} {incr c} {
    if {$c == 38} {
        # Must skip ampersand.
        continue
    }
    lappend oentities "�*$c;" [format %c $c]
}
lappend oentities     {&(amp|#0*38);} {\&}
set entities $oentities
#       }}}2 Characters entities
#       {{{2 IANA charset and Tcl encodings
global charsets
# We only list those that start with a 1-octet ASCII subset,
# and prefer those registered with the IANA.
# Format:  tcl-encoding {iana-charset...}
set charsets {
    utf-8       {UTF-8 csUTF8}
    ascii       {US-ASCII ASCII ANSI_X3.4-1968 iso-ir-6 ANSI_X3.4-1986 ISO_646.irv:1991 ISO646-US us IBM367 cp367 csASCII}
    iso8859-1   {ISO-8859-1 ISO_8859-1:1987 iso-ir-100 ISO_8859-1 latin1 l1 IBM819 CP819 csISOLatin1}
    iso8859-2   {ISO-8859-2 ISO_8859-2:1987 iso-ir-101 ISO_8859-2 latin2 l2 csISOLatin2}
    iso8859-3   {ISO-8859-3 ISO_8859-3:1988 iso-ir-109 ISO_8859-3 latin3 l3 csISOLatin3}
    iso8859-4   {ISO-8859-4 ISO_8859-4:1988 iso-ir-110 ISO_8859-4 latin4 l4 csISOLatin4}
    iso8859-5   {ISO-8859-5 ISO_8859-5:1988 iso-ir-144 ISO_8859-5 cyrillic csISOLatinCyrillic}
    iso8859-6   {ISO-8859-6 ISO_8859-6:1987 iso-ir-127 ISO_8859-6 arabic ECMA-114 ASMO-708 csISOLatinArabic}
    iso8859-7   {ISO-8859-7 ISO_8859-7:1987 iso-ir-126 ISO_8859-7 greek greek8 ELOT_928 ECMA-118 csISOLatinGreek}
    iso8859-8   {ISO-8859-8 ISO_8859-8:1988 iso-ir-138 ISO_8859-8 hebrew csISOLatinHebrew}
    iso8859-9   {ISO-8859-9 ISO_8859-9:1989 iso-ir-148 ISO_8859-9 latin5 l5 csISOLatin5}
    iso8859-10  {ISO-8859-10 ISO_8859-10:1992 iso-ir-157 latin6 l6 csISOLatin6}
    iso8859-13  {ISO-8859-13 csISO885913}
    iso8859-14  {ISO-8859-14 ISO_8859-14:1998 iso-ir-199 ISO_8859-14 latin8 l8 iso-celtic csISO885914}
    iso8859-15  {ISO-8859-15 ISO_8859-15 Latin-9 csISO885915}
    iso8859-16  {ISO-8859-16 ISO_8859-16:2001 iso-ir-226 ISO_8859-16 latin10 l10 csISO885916}
    iso2022     {JIS_Encoding csJISEncoding}
    iso2022-jp  {ISO-2022-JP csISO2022JP}
    iso2022-kr  {ISO-2022-KR csISO2022KR}
    euc-cn      {}
    euc-jp      {EUC-JP Extended_UNIX_Code_Packed_Format_for_Japanese csEUCPkdFmtJapanese}
    euc-kr      {EUC-KR csEUCKR}
    big5        {Big5 csBig5}
    gb1988      {GB_1988-80 iso-ir-57 cn ISO646-CN csISO57GB1988}
    gb2312      {GB2312 csGB2312}
    jis0201     {JIS_X0201 X0201 csHalfWidthKatakana}
    koi8-r      {KOI8-R csKOI8R}
    koi8-u      {KOI8-U csKOI8U}
    shiftjis    {Shift_JIS MS_Kanji csShiftJIS}
    tis-620     {TIS-620 csTIS620}
    macRoman    {macintosh mac csMacintosh}
    macCentEuro {}
    macCroatian {}
    macCyrillic {}
    macGreek    {}
    macIceland  {}
    macJapan    {}
    macRomania  {}
    macThai     {}
    macTurkish  {}
    macUkraine  {}
    cp437       {IBM437 cp437 437 csPC8CodePage437}
    cp737       {}
    cp775       {IBM775 cp775 csPC775Baltic}
    cp850       {IBM850 cp850 850 csPC850Multilingual}
    cp852       {IBM852 cp852 852 csPCp852}
    cp855       {IBM855 cp855 855 csIBM855}
    cp857       {IBM857 cp857 857 csIBM857}
    cp860       {IBM860 cp860 860 csIBM860}
    cp861       {IBM861 cp861 861 cp-is csIBM861}
    cp862       {IBM862 cp862 862 csPC862LatinHebrew}
    cp863       {IBM863 cp863 863 csIBM863}
    cp864       {IBM864 cp864 csIBM864}
    cp865       {IBM865 cp865 865 csIBM865}
    cp866       {IBM866 cp866 866 csIBM866}
    cp869       {IBM869 cp869 869 cp-gr csIBM869}
    cp874       {}
    cp932       {}
    cp936       {GBK CP936 MS936 windows-936 csGBK}
    cp949       {}
    cp950       {}
    cp1250      {windows-1250 cswindows1250}
    cp1251      {windows-1251 cswindows1251}
    cp1252      {windows-1252 cswindows1252}
    cp1253      {windows-1253 cswindows1253}
    cp1254      {windows-1254 cswindows1254}
    cp1255      {windows-1255 cswindows1255}
    cp1256      {windows-1256 cswindows1256}
    cp1257      {windows-1257 cswindows1257}
    cp1258      {windows-1258 cswindows1258}
}
proc cs2enc {charset} {
    global charsets
    foreach {enc csl} $charsets {
        foreach cs $csl {
            if {![string compare -nocase $charset $cs]} {
                return $enc
            }
        }
        if {![string compare -nocase $charset $enc]} {
            set encx $enc
        }
    }
    if {[info exists encx]} {
        return $encx
    }
    return ""
}
#       }}}2 IANA charset and Tcl encodings
#       {{{2 Indent utility functions
proc push_indent {pos} {
    global indent indents
    lappend indents $pos
    incr indent $pos
}
proc pop_indent {} {
    global indent indents
    set pos [lindex $indents end]
    set indent [expr $indent - $pos]
    set indents [lreplace $indents end end]
    return $pos
}
#       }}}2 Indent utility functions
#       {{{2 Align utility functions
global aligns
set aligns {}
proc push_align {a} {
    global aligns
    if {[regexp -- {^(left[-+]|center[-+]|right-)[0-9]+em$} $a]} {
        lappend aligns $a
        return
    }
    switch -- $a {
        left - center - right { lappend aligns $a }
        default {
            unexpected error \
                "align=\"$a\" attribute is invalid"
        }
    }
}
proc pop_align {} {
    global aligns
    set a [lindex $aligns end]
    set aligns [lreplace $aligns end end]
    return $a
}
proc current_align {} {
    global aligns
    set a ""
    if {[llength $aligns] > 0} {
        set a [lindex $aligns end]
    }
    regsub -- {[-+][0-9]+em$} $a "" a
    return $a
}
proc current_align_bias {} {
    global aligns
    set a ""
    if {[llength $aligns] > 0} {
        set a [lindex $aligns end]
    }
    if {[regexp -- {([-+][0-9]+)em$} $a x b]} {
        set b [expr $b]
    } else {
        set b 0
    }
    return $b
}
#       }}}2 Align utility functions
#       {{{2 Other
proc flush_text {} {
    global buffer buffer_align
    global mode
    if {[string compare $buffer ""]} {
        set rest $buffer
        set buffer ""
        switch -- $mode {
            txt     { set rest [justify_text_txt $rest $buffer_align] }
            default { set rest [string trim $rest] }
        }
        write_line_$mode $rest
        switch -- $mode {
            nr { setup_align_nr end $buffer_align }
        }
        set buffer_align ""
    }
}
proc munge_long {lines} {
    global page_width
    global mode
    set result ""
    set max [expr $page_width / 2 - 2]
    foreach buffer $lines {
        set linkP 0
        if {(![string compare $mode html]) \
                && (([string match Obsoletes:* $buffer])
                        || ([string match Updates:* $buffer]))} {
            set linkP 1
        }
        while {[set i [string length $buffer]] > $max} {
            set line [string range $buffer 0 $max]
            if {[set x [string last " " $line]] < 0} {
                if {[set x [string first " " $buffer]] < 0} {
                    break
                }
            }
            set line [string range $buffer 0 [expr $x-1]]
            if {$linkP} {
                set line [munge_line $line]
            }
            lappend result $line
            set buffer [string trimleft [string range $buffer $x end]]
        }
        if {$linkP} {
            set buffer [munge_line $buffer]
        }
        lappend result $buffer
    }
    return $result
}
proc munge_line {line} {
    global rfcTxtHome rfcHtmlHome
    if {[set y [string first : $line]] >= 0} {
        set start [string range $line 0 $y]
        set line [string range $line [expr $y+1] end]
    } else {
        set start ""
    }
    if {[set y [string first " (" $line]] >= 0 ||
        [set y [string first "(" $line]] == 0} {
        set tail [string range $line $y end]
        set line [string range $line 0 [expr $y-1]]
    } else {
        set tail ""
    }
    set s " "
    foreach n [split $line ,] {
        set n [string trim $n]
#       append start $s "<a href='$rfcTxtHome/rfc$n.txt'>$n</a>"
        append start $s "<a href='$rfcHtmlHome/rfc$n'>$n</a>"
        set s ", "
    }
    return $start$tail
}
proc write_url {url} {
    global mode
    write_text_$mode <[chars_expand $url]>
}
proc is_at_page_start {} {
    global lineno
    global mode
    global page_head_height
    flush_text
    if {$lineno == 0} {
        start_page_$mode
    }
    return [expr $lineno <= $page_head_height]
}
proc have_lines {cnt} {
    global lineno
    global options
    global unpaginated
    global page_head_height page_body_height
    if {[is_at_page_start] || !$options(.AUTOBREAKS) || $unpaginated} {
        return 1
    }
    if {   $cnt <= $page_body_height
        && $lineno + $cnt > $page_head_height + $page_body_height} {
        return 0
    }
    return 1
}
proc write_it {line} {
    global passno
    global out_fd
    if {$passno >= 2} {
        puts $out_fd $line
    }
}
#       }}}2 Other
#       {{{2 Textual lists utility functions
proc collapsed_num_list {nums} {
    set r ""
    if {[llength $nums] == 0} {
        return $r
    }
    set s ""
    # Assume nums are non-negative and ordered.
    set i -1
    # Add sentinel.
    lappend nums [expr [lindex $nums end] + 2]
    foreach n $nums {
        if {$i < 0} {
            set j [set i $n]
            continue
        }
        if {$n == $j} {
            continue
        }
        if {$n == $j + 1} {
            set j $n
            continue
        }
        if {$i == $j} {
            append r "$s$i"
        } else {
            append r "$s$i-$j"
        }
        set j [set i $n]
        set s ", "
    }
    return $r
}
proc list_sep_str {i n} {
    if {$i == $n} {
        if {$n > 2} {
            return ", and "
        } else {
            return " and "
        }
    } else {
        return ", "
    }
}
#       }}}2 Textual lists utility functions
#       {{{2 Character expansion
# This expands entities and non-ASCII characters
# into ASCII characters and ASCII-art glyphs.
proc chars_expand {text {flatten 1}} {
    global entities
    if {[regsub -all -- {[\0-\010\013\014\016-\037\177]+} $text {*?*} text]} {
        # DELETE and every C0 control char except \t, \n, and \r.
        unexpected error \
            "illegal use of hardcoded ASCII control character(s) in \"$text\""
    }
    if {[regsub -all -- {[\x80-\x9F]+} $text {*?*} text]} {
        # Every C1 control char.
        unexpected error \
            "illegal use of hardcoded C1 control character(s) (U+0080..U+009F) possibly instead of standard entities (e.g., — or ’) in \"$text\""
    }
    # Convert other hardcoded non-ASCII characters (except no-break space,
    # non-breaking hyphen, word joiner, and our protected characters)
    # as dec entities.
    while {[regexp -- {[^\0-\xA0\u2011\u2060\uF000-\uF0FF]} $text x]} {
        regsub -all -- $x $text "\\&#[scan $x %c];" text
    }
    # Process hex here to avoid cluttering $entities, to support
    # leading zeros, and most importantly to have -nocase.
    while {[regexp -nocase -- {&#x([0-9A-Z]+);} $text x y]} {
        # Rewrite hex as dec.
        regsub -all -nocase -- $x $text "\\&#[scan $y %x];" text
    }
    if {[regexp -- {�*1(2[89]|[345][0-9]);} $text]} {
        # Possibly just a warning for backward compatibility.
        unexpected [unex_condtype] \
            "non-standard use of entities between € and Ÿ as printable characters (really C1 control characters) instead of standard entities (e.g., — or ’) in \"$text\""
    }
    if {[regexp -- {�+;} $text]} {
        # All versions of XML prohibit this.
        unexpected error \
            "illegal use of � entity in \"$text\""
    }
    # Remaining entities are case sensitive (or just dec).
    foreach {entity chars} $entities {
        regsub -all -- $entity $text $chars text
    }
    set text [break_preprocess $text]
    if {$flatten} {
        regsub -all -- "\n\[ \t\]*" $text " " text
    }
    return $text
}
# This expands all entities into Unicode characters.
# Unknown entities are silently replaced
# by a REPLACEMENT CHARACTER (U+FFFD).
proc ent_expand {text} {
    global uentities
    # Process hex; support leading zeros and -nocase.
    while {[regexp -nocase -- {&#x([0-9A-Z]+);} $text x y]} {
        set y [expr 0x$y]
        if {$y == 38} {
            # Skip ampersand.
            continue
        }
        regsub -all -nocase -- $x $text [format %c $y] text
    }
    # Process dec; support leading zeros.
    while {[regexp -- {&#([0-9]+);} $text x y]} {
        if {$y == 38} {
            # Skip ampersand.
            continue
        }
        regsub -all -- $x $text [format %c $y] text
    }
    # Known named entities are case sensitive.
    foreach {entity uchar} $uentities {
        regsub -all -- $entity $text $uchar text
    }
    # Replace unknown named entities.
    set p 0
    while {[regexp -start $p -indices -- {&[A-Za-z0-9._:-]*;} $text x]} {
        set p [lindex $x 0]
        set q [lindex $x 1]
        set ent [string range $text $p $q]
        if {![string compare $ent "&"]} {
            # Skip ampersand.
            set p [expr $q + 1]
            continue
        }
        regsub -all -- {\.} $ent {\\.} ent
        regsub -all -start $p -- $ent $text "\uFFFD" text
    }
    # Ampersand.
    regsub -all -- {&(amp|#0*38|#[xX]0*26);} $text {\&} text
    # Replace DELETE and every C0 control char except \t, \n, and \r.
    regsub -all -- {[\0-\010\013\014\016-\037\177]+} $text "\uFFFD" text
    # Replace every C1 control char (including if entities between € and
    # Ÿ were mistakenly thought to be windows-1252 or something similar).
    regsub -all -- {[\x80-\x9F]+} $text "\uFFFD" text
    return $text
}
# This only replaces named entities that we know about, but that (x)html
# wouldn't, by numerical entities.
proc html_expand {text} {
    global xentities
    foreach {entity chars} $xentities {
        regsub -all -- $entity $text $chars text
    }
    return $text
}
proc html_quote {text} {
    foreach {e c} {amp & lt < gt >} {
        regsub -all -- "\[$c\]" $text "\\&$e;" text
    }
    return $text
}
proc tabs_expand_pre {line} {
    global pageno lineno
    set msg "pre-formatted output line [expr $lineno + 1] (on page $pageno)"
    if {[regexp -- {[\t]} $line]} {
        unexpected warning \
            "$msg contained tab characters which were expanded"
        while {[set x [string first "\t" $line]] >= 0} {
            set new [string range $line 0 [expr $x - 1]]
            append new [string repeat " " [expr 8 - ($x % 8)]]
            set line $new[string range $line [expr $x + 1] end]
        }
    }
    if {[regexp -- {[^ -~\xA0\u2011\u2060]} $line]} {
        # No-break spaces will be expanded later and are OK.
        unexpected error \
            "$msg contains illegal characters (control or otherwise)"
    }
    return $line
}
#       }}}2 Character expansion
#   }}}1 Low-level formatting
#   {{{1 xml2ref support
namespace eval ref {
    variable ref
    array set ref { uid 0 }
    variable parser [xml::parser]
    variable context
    #              element       verbatim        beginF  endF
    set context { {dummy/-1}
                  {rfc/0         no              yes     yes}
                  {front/1}
                  {title/2}
                  {author/2}
                  {organization/3}
                  {address/3}
                  {postal/4}
                  {street/5}
                  {city/5}
                  {region/5}
                  {code/5}
                  {country/5}
                  {phone/4}
                  {facsimile/4}
                  {email/4}
                  {uri/4}
                  {date/2}
                  {area/2}
                  {workgroup/2}
                  {keyword/2}
                  {abstract/2    yes}
                  {note/2        yes}
                }
    namespace export init fin transform
}
proc ref::init {} {
    variable ref
    set token [namespace current]::[incr ref(uid)]
    variable $token
    upvar 0 $token state
    catch { array unset state }
    return $token
}
proc ref::fin {token} {
    variable $token
    upvar 0 $token state
    foreach name [array names state] {
        unset state($name)
    }
    unset $token
}
proc ref::transform {token file {formats {}} } {
    global errorCode errorInfo
    global ifile
    global emptyA
    variable $token
    upvar 0 $token state
    catch { array unset emptyA }
    unex_init
    variable parser
    $parser configure \
            -elementstartcommand    "ref::element_start $token" \
            -elementendcommand      "ref::element_end   $token" \
            -characterdatacommand   "ref::cdata         $token" \
            -entityreferencecommand ""                          \
            -errorcommand           ref::oops                   \
            -entityvariable         emptyA                      \
            -final                  1                           \
            -reportempty            1
    set fd ""
    set data ""
    catch {
        set fd [open $file { RDONLY }]
        catch { fconfigure $fd -encoding binary -translation lf }
        set ifile $file
        set data [read $fd]
    }
    if {[catch { close $fd } result]} {
        log::entry $logT system $result
    }
    set data [prexml $data]
    set state(stack)    ""
    set state(body)     ""
    set state(number)   0
    set state(authors)  0
    set state(keywords) 0
    set state(verbatim) 0
    set state(silent)   0
    set state(formats)  $formats
    set state(info)     ""
    set state(mtime)    0
    set state(tprefix)  ""
    set state(tsuffix)  ""
    set state(descr)    ""
    set code [catch { $parser parse $data } result]
    set ecode $errorCode
    set einfo $errorInfo
    switch -- $code {
        0 {
            set result [list body  $state(body) \
                             info  $state(info) \
                             mtime $state(mtime)]
        }
        1 {
            if {[set i [llength $state(stack)]] > 0} {
                set text "File:    $file\nContext:"
                while {$i > 0} {
                    set frame [lindex $state(stack) [incr i -1]]
                    append text "\n    <[lindex $frame 0]"
                    foreach {k v} [lindex $frame 1] {
                        regsub -all -- \" $v {\"} v
                        append text " $k=\"$v\""
                    }
                    append text ">"
                }
                append result "\n\n$text"
            }
        }
    }
    unset state(stack)    \
          state(body)     \
          state(number)   \
          state(authors)  \
          state(keywords) \
          state(verbatim) \
          state(silent)   \
          state(formats)  \
          state(info)     \
          state(mtime)    \
          state(tprefix)  \
          state(tsuffix)  \
          state(descr)
    return -code $code -errorinfo $einfo -errorcode $ecode $result
}
proc ref::element_start {token name {av {}} args} {
    global rfcitems
    variable $token
    upvar 0 $token state
    variable context
    array set options [list -empty 0]
    array set options $args
    set depth [llength $state(stack)]
    if {[set idx [lsearch -glob $context $name/$depth*]] >= 0} {
        set info [lindex $context $idx]
        if {[string compare [lindex $info 0] $name/$depth]} {
            set idx -1
        } elseif {![string compare [lindex $info 1] yes]} {
            set state(verbatim) 1
        }
    }
    set state(silent) 0
    if {($idx < 0) && ($state(verbatim))} {
        set idx 0
        set info ""
        if {[lsearch -exact {xref eref cref iref vspace} $name] >= 0} {
            set state(silent) 1
        }
    }
    # format*
    # is-also: BCP70
    if {$idx >= 0} {
        if {![string compare [lindex $info 2] yes]} {
            ref::start_$name $token $av
        } elseif {!$state(silent)} {
            switch -- $name {
                author {
                    incr state(authors)
                    set k $state(number),author$state(authors)
                    if {[info exists rfcitems($k)]} {
                        array set kv $rfcitems($k)
                        if {[info exists $kv(name)]} {
                            set name $kv(name)
                            # update initials/surname when
                            # rfc-index.xml is more robust...
                        }
                    }
                    array set nv $av
                    if {[info exists nv(fullname)]} {
                        append state(tsuffix) ", " $nv(fullname)
                    }
                }
                date {
                    set k $state(number)
                    array set nv $av
                    foreach n [list day year month] {
                        if {[info exists rfcitems($k,$n)]} {
                            set nv($n) $rfcitems($k,$n)
                        }
                    }
                    set av [array get nv]
                    array set dv [list day 1 year "" month ""]
                    array set dv $av
                    if {[string first "<dc:date>" $state(info)] < 0} {
                        catch {
                            set state(mtime) \
                                [clock scan "$dv(month) $dv(day), $dv(year)"]
                            append state(info) \
                                   "    <dc:date>" \
                                   [clock format $state(mtime) \
                                        -format "%Y-%m-%dT%T-00:00" \
                                        -gmt true] \
                                   "</dc:date>\n"
                        }
                    }
                }
                note {
                    if {[string first "</description>" $state(info)] < 0} {
                        append state(info) "    <description></description>\n"
                    }
                }
            }
            append state(body) "\n<$name"
            foreach {n v} $av {
                regsub -all -- {'} $v {\'} v
                append state(body) " $n='$v'"
            }
            if {$options(-empty)} {
                append state(body) " /"
            }
            append state(body) >
            switch -- $name {
                title {
                    set k $state(number)
                    if {[info exists rfcitems($k,doc-title)]} {
                        append state(body) $rfcitems($k,doc-title)
                        if {[string first "<title>" $state(info)] < 0} {
                            append state(info) "    <title>" \
                                   $state(tprefix) \
                                   $rfcitems($k,doc-title) \
                                   "</title>\n"
                        }
                    }
                }
            }
        }
    }
    lappend state(stack) [list $name $av $idx ""]
}
proc ref::element_end {token name args} {
    variable $token
    upvar 0 $token state
    variable context
    array set options [list -empty 0]
    array set options $args
    set frame [lindex $state(stack) end]
    set state(stack) [lreplace $state(stack) end end]
    if {[set idx [lindex $frame 2]] >= 0} {
        set info [lindex $context $idx]
        if {![string compare [lindex $info 3] yes]} {
            ref::end_$name $token $frame
        } elseif {!$state(silent) && !$options(-empty)} {
            append state(body) </$name>
        }
        if {![string compare [lindex $info 1] yes]} {
            set state(verbatim) 0
        }
    }
    set state(silent) 0
    switch -- $name {
        title {
            if {([string first "<title>" $state(info)] >= 0)
                    && ([string first "</title>" $state(info)] < 0)} {
                append state(info) "</title>\n"
            }
        }
        t {}
        front - abstract {
            if {[string first "</description>" $state(info)] < 0} {
                if {[string first "<description>" $state(info)] >= 0} {
                    append state(info) "</description>\n"
                } else {
                    append state(info) "    <description></description>\n"
                }
            }
        }
    }
}
proc ref::cdata {token text} {
    global rfcitems
    variable $token
    upvar 0 $token state
    if {[string length [string trim $text]] <= 0} {
        return
    }
    set frame [lindex $state(stack) end]
    if {[set idx [lindex $frame 2]] < 0} {
        return
    }
    switch -- [lindex $frame 0] {
        title {
            set k $state(number)
            if {[info exists rfcitems($k,doc-title)]} {
                return
            }
        }
    }
    regsub -all -- "\r" $text "\n" text
    append state(body) $text
    switch -- [lindex $frame 0] {
        title {
            if {![info exists rfcitems($k,doc-title)]} {
                if {[string first "<title>" $state(info)] < 0} {
                    append state(info) "    <title>" $state(tprefix) $text
                } elseif {[string first "</title>" $state(info)] < 0} {
                    append state(info) $text
                }
            }
        }
        t {
            if {[string first "<description>" $state(info)] < 0} {
                append state(info) "    <description>" $text
            } elseif {[string first "</description>" $state(info)] < 0} {
                append state(info) $text
            }
        }
    }
}
proc ref::oops {args} {
    return -code error [join $args " "]
}
proc ref::start_rfc {token av} {
    variable $token
    upvar 0 $token state
    array set rfc [list obsoletes "" updates "" category info seriesNo ""]
    array set rfc $av
    if {[catch { set rfc(number) }]} {
        ref::oops "missing number attribute in rfc element"
    }
    set state(number) $rfc(number)
    set state(body) "<?xml version='1.0' encoding='UTF-8'?>\n\n"
    append state(body) "<reference anchor='RFC[format %04d $rfc(number)]'>\n"
    set state(tprefix) "RFC $rfc(number): "
}
proc ref::end_rfc {token frame} {
    global rfcitems
    variable $token
    upvar 0 $token state
    array set rfc [list obsoletes "" updates "" category info seriesNo ""]
    array set rfc [lindex $frame 1]
    set k $state(number)
    if {[info exists rfcitems($k,is-also)]} {
        array set rfc [list category [string range $rfcitems($k,is-also) 0 2] \
                            seriesNo [string range $rfcitems($k,is-also) 3 end]]
    }
    append state(body) "\n\n"
    if {([string compare [set x $rfc(category)] info]) \
            && ([string compare [set y $rfc(seriesNo)] ""])} {
        append state(body) "<seriesInfo name='[string toupper $x]' "
        append state(body) "value='$y' />\n"
    }
    append state(body) "<seriesInfo name='RFC' value='$rfc(number)' />\n"
    foreach format $state(formats) {
        append state(body) "<format"
        foreach {k v} $format {
            append state(body) " $k='$v'"
        }
        append state(body) " />\n"
    }
    append state(body) "</reference>\n"
    set url ""
    foreach format $state(formats) {
        catch { array unset fv }
        array set fv $format
        set url $fv(target)
        if {![string compare $fv(type) TXT]} {
            break
        }
    }
    if {[string compare $url ""]} {
        regsub -all -- {&} $url {\&} url
        regsub -all -- {'} $url {\'} url
        if {([string compare $state(tsuffix) ""]) \
                && ([set x [string first "</title>" $state(info)]] > 0)} {
            set info [string range $state(info) 0 [expr $x-1]]
            append info $state(tsuffix) [string range $state(info) $x end]
            set state(info) $info
        }
        set state(info) "\n<item rdf:about='$url'>\n    <link>$url</link>\n$state(info)</item>\n"
    } else {
        set state(info) ""
    }
}
#   }}}1 xml2ref support
#   {{{1 Some string manipulations
proc stindex {sindex len} {
    switch -regexp -- $sindex {
        {^[Ee][Nn][Dd]*$} {
            incr len -1
            return [expr $len[string range $sindex 3 end]]
        }
        {^[Ll][Ee][Nn]*$} {
            return [expr $len[string range $sindex 3 end]]
        }
        default {
            return $sindex
        }
    }
}
proc streplace {string first last {newstring ""} {magic 0}} {
    set first [stindex $first [set len [string length $string]]]
    set last [stindex $last $len]
    if {($first > $last) || ($first > $len) || ($last < 0)} {
        return $string
    }
    if {$first > 0} {
        set left [string range $string 0 [expr $first-1]]
    } else {
        set left ""
    }
    if {$magic} {
        set oldstring [string range $string \
                              [expr (($first) >= 0) ? ($first) : 0] \
                              [expr (($last) < $len) ? ($last) : $len-1]]
        if {$magic == 1} {
            regsub -all -- {[^\t\r\n]} $oldstring { } newstring
        } elseif {$magic >= 2} {
            # Remove, but preserve the line count.
            set newstring ""
            # EOL normalization is necessary with XML 1.1.
            set n [num_eols [str_norm_eol $oldstring]]
            if {$n > 0} {
                if {$magic == 2} {
                    append newstring {<!--} [string repeat "\n" $n] {-->}
                } else {
                    # $magic == 3
                    set newstring [string repeat "\n" $n]
                }
            }
        }
    }
    if {$last < $len} {
        set right [string range $string [expr $last+1] end]
    } else {
        set right ""
    }
    return $left$newstring$right
}
proc str_norm_eol {string {xml11 0}} {
    if {$xml11} {
        regsub -all -- "\r\n|\r\x85|\x85|\u2028|\r" $string "\n" string
    } else {
        regsub -all -- "\r\n?" $string "\n" string
    }
    return $string
}
proc str_pad_cmp {s1 s2} {
    set l1 [string length $s1]
    set l2 [string length $s2]
    if {$l1 < $l2} {
        set s1 [string repeat "0" [expr $l2 - $l1]]$s1
    } elseif {$l1 > $l2} {
        set s2 [string repeat "0" [expr $l1 - $l2]]$s2
    }
    set s1 [string toupper $s1]
    set s2 [string toupper $s2]
    return [string compare $s1 $s2]
}
#   }}}1 Some string manipulations
#   {{{1 artwork content processing
#       {{{2 namespace
namespace eval artwork {
    variable grammar
    variable grammar_program
    catch { array unset grammar }
    catch { array unset grammar_program }
    namespace eval tokenize {}
}
#       }}}2 namespace
#       {{{2 procs
proc artwork::validate_highlight {type text} {
    variable grammar
    variable grammar_program
    switch -- $type {
        abnf {
            append text "\n"
        }
        pib {
            # For now.
            set type mib
        }
    }
    if {   !(   [info exists grammar_program($type)]
             || [compile_grammar $type]
             || [info exists grammar($type)])
        || [catch { info body tokenize::$type }]} {
        return {-1 {} [generic_divs]}
    }
    # Through upvar, this read $text and sets $tokens and $spans.
    tokenize::$type
    set max_idx 0
    if {[info exists grammar_program($type)]} {
        foreach {cnt spans1 divs1} [grammar_program_parse $type] {break}
    } else {
        array set rule $grammar($type)
        set rn [lindex $grammar($type) 0]
        foreach {cnt spans1 divs1} [check_rule $rn 0] {break}
    }
    set spans [lsort -index 1 -integer [concat $spans $spans1]]
    # Convert divs from character-oriented to line-oriented.
    set divs {}
    set p0 0
    set d0 0
    foreach div [lsort -index 0 -integer $divs1] {
        incr d0 [num_eols [string range $text $p0 [expr [lindex $div 0] - 1]]]
        set p0 [lindex $div 0]
        set d1 [expr $p0 + [lindex $div 1] - 2]
        set d1 [expr [num_eols [string range $text $p0 $d1]] + 1]
        lappend divs [list $d0 $d1]
    }
    set textlen [string length $text]
    set tokcnt [llength $tokens]
    if {![set valid [expr $cnt >= $tokcnt]]} {
        if {$max_idx >= 0 && $max_idx < $tokcnt} {
            set pos [lindex [lindex $tokens $max_idx] 1]
        } else {
            set pos 0
        }
        while {[llength $spans] > 0 && $pos <= [lindex [lindex $spans end] 1]} {
            set spans [lrange $spans 0 end-1]
        }
        lappend spans [list err $pos [expr $textlen - $pos]]
    } elseif {[lsearch0 $spans err] >= 0} {
        # In case of temporarily ignored kludges.
        set valid 0
    }
    return [list $valid $spans $divs]
}
proc artwork::generic_divs {} {
    # We do not modify $text.
    upvar text text
    # Blank lines delimit each generic div.
    set divs {}
    set pos 0
    set d0 -1
    set l 0
    set z [string length $text]
    while {$pos < $z} {
        if {[regexp -indices -start $pos -- "\n" $text x]} {
            set a [lindex $x 0]
            set x [string range $text $pos $a]
        } else {
            set a $z
            set x [string range $text $pos end]
        }
        if {[string compare [string trim $x] ""]} {
            if {$d0 < 0} {
                set d0 $l
                set d1 1
            } else {
                incr d1
            }
        } elseif {$d0 >= 0} {
            lappend divs [list $d0 $d1]
            set d0 -1
        }
        incr l
        set pos [expr $a + 1]
    }
    if {$d0 >= 0} {
        lappend divs [list $d0 $d1]
    }
    return $divs
}
proc artwork::compile_grammar {type} {
    return 0
}
proc artwork::grammar_program_parse {type} {
    variable grammar_program
    # We use these upvars read-only.
    upvar tokens tokens
    # We use this upvar read-write.
    upvar max_idx max_idx
    array set table $grammar_program($type)
    set spans {}
    set divs {}
    set stack {}
    set state 0
    set i 0
    while {1} {
        set nexti [expr $i + 1]
        set tok [lindex $tokens $i]
        set x [list [lindex $tok 0] $state]
        if {[info exists table($x)]} {
            set do $table($x)
        } else {
            set x [list * $state]
            if {[catch { set do $table($x) }]} {
                set do {{err}}
            }
        }
        foreach d $do {
            set d0 [lindex $d 0]
            switch -- $d0 {
                push {
                    lappend stack [concat $i [lrange $d 1 end]]
                    continue
                }
                pop - span-top - div-top - check - goto-top {
                    if {[llength $stack]} {
                        set top [lindex $stack end]
                        set tok0 [lindex $tokens [lindex $top 0]]
                        set i0 [lindex $tok0 1]
                        set i1 [expr [lindex $tok 1] - $i0 + [lindex $tok 2]]
                    } else {
                        set ret -1
                        break
                    }
                }
                span {
                    lappend spans [concat [lindex $d 1] [lrange $tok 1 2]]
                    continue
                }
                div {
                    set i0 [lindex $tok 1]
                    set i1 [lindex $tok 2]
                    lappend divs [lrange $tok 1 2]
                    continue
                }
                redo {
                    set state [lindex $d 1]
                    set nexti [expr $i - 0[lindex $d 2]]
                    continue
                }
                goto {
                    set state [lindex $d 1]
                    continue
                }
                skip-next {
                    if {[llength $d] > 1} {
                        incr nexti [lindex $d 1]
                    } else {
                        incr nexti
                    }
                    continue
                }
                done    { set ret $i; break }
                default { set ret -1; break }
            }
            switch -- $d0 {
                pop  { set stack [lreplace $stack end end] }
                span-top {
                    lappend spans [list [lindex $d 1] $i0 $i1]
                }
                div-top {
                    lappend divs [list $i0 $i1]
                }
                check {
                    set c [concat [lrange $top 1 end] [lindex $tok0 0]]
                    set k [llength $d]
                    for {set j 1} {$j < $k} {incr j} {
                        if {[lsearch -exact $c [lindex $d $j]] >= 0} {
                            break
                        }
                    }
                    if {$j >= $k} {
                        set ret -1
                        break
                    }
                }
                goto-top { set state [lindex $top 1] }
            }
        }
        if {[info exists ret]} {
            set max_idx $i
            break
        }
        set i $nexti
    }
    return [list $ret $spans $divs]
}
proc artwork::check_rule {rulename idx} {
    # We use these upvars read-only.
    upvar tokens tokens rule rule
    # We use this upvar read-write.
    upvar max_idx max_idx
    set tok [lindex $tokens $idx]
    if {![info exists rule($rulename)]} {
        # Assume it's an implicit terminal with no span.
        if {[string compare $rulename [lindex $tok 0]]} {
            set cnt -1
        } else {
            set cnt  1
            if {$max_idx <= $idx} {
                set max_idx [expr $idx + 1]
            }
        }
        return [list $cnt {} {}]
    }
    foreach {ruletok ruletype ruledef} $rule($rulename) {break}
    switch -- $ruletype {
        * {
            if {$idx < [llength $tokens]} {
                set rulename [lindex $tok 0]
            } else {
                set rulename "{no-such-rule}"
            }
            set ruletype .
        }
    }
    switch -- $ruletype {
        . {
            if {[string compare $rulename [lindex $tok 0]]} {
                return {-1 {} {}}
            }
            if {$max_idx <= $idx} {
                set max_idx [expr $idx + 1]
            }
            set i0 [lindex $tok 1]
            set i1 [lindex $tok 2]
            switch -- $ruletok {
                "" {
                    return {1 {} {}}
                }
                div {
                    # This matches an explicit terminal rule with a div.
                    return [list 1 {} [list [list $i0 $i1]]]
                }
                default {
                    # This matches an explicit terminal rule with a span.
                    return [list 1 [list [list $ruletok $i0 $i1]] {}]
                }
            }
        }
        = { set n  0 }
        | { set n -1 }
    }
    set spans {}
    set divs {}
    set i $idx
    foreach {rn rep} $ruledef {
        while {1} {
            foreach {n s d} [check_rule $rn $i] {break}
            if {$n >= 0} {
                switch -- $rep {
                    ! { return [list -1 {} {}] }
                }
                incr i $n
                set spans [concat $spans $s]
                set divs  [concat $divs  $d]
                switch -- $rep {
                    +     { set rep * }
                    1 - ? { break }
                }
            } else {
                switch -- $rep {
                    ! {
                        switch -- $ruletype {
                            = { set n 0 }
                        }
                    }
                    * - ? { set n 0 }
                }
                break
            }
        }
        switch -- $ruletype {
            = {
                if {$n < 0} {
                    set spans {}
                    set divs  {}
                    break
                }
            }
            | {
                if {$n >= 0} {
                    break
                }
            }
        }
    }
    if {$n >= 0} {
        set cnt [expr $i - $idx]
        if {$max_idx < $i} {
            set max_idx $i
        }
    } else {
        set cnt -1
    }
    if {$cnt > 0 && [string compare $ruletok ""]} {
        set i0 [lindex $tok 1]
        set tok1 [lindex $tokens [expr $idx + $cnt - 1]]
        set i1 [expr [lindex $tok1 1] - $i0 + [lindex $tok1 2]]
        switch -- $ruletok {
            div     { lappend divs        [list          $i0 $i1]  }
            default { set     spans [list [list $ruletok $i0 $i1]] }
        }
    }
    return [list $cnt $spans $divs]
}
#       }}}2 procs
#       {{{2 grammars
#           {{{3 abnf
#               {{{4 proc artwork::tokenize::abnf
# We introduce a tokenizer, because doing everything off of the original
# grammar with a generic parser in Tcl proves to be way too slow.
proc artwork::tokenize::abnf {} {
    # We do not modify $text.
    upvar text text tokens tokens spans spans
    foreach x {
        ALPHA BIT CHAR CR CRLF CTL DIGIT DQUOTE
        HEXDIG HTAB LF LWSP OCTET SP VCHAR WSP
    } {
        # ABNF core rule names.
        set Chash($x) core
    }
    set pos 0
    set tokens {}
    set spans {}
    set z [string length $text]
    # According to RFC 4234, Section 2.2:
    #   For visual ease, rule definitions are left aligned.
    #   When a rule requires multiple lines,
    #   the continuation lines are indented.
    #   The left alignment and indentation are relative to the first lines
    #   of the ABNF rules and need not match the left margin of the document.
    # For some reason, this behavior wasn't itself encoded in ABNF!
    # We will try to maintain a notion of per-rule left margin.
    # Negative means were currently outside of a rule.
    # The nl token mean the end of a rule.
    set margin -1
    while {$pos < $z} {
        if {[regexp -indices -start $pos -- "\[\"<;\]" $text x]} {
            set a [lindex $x 0]
            switch -- [string range $text $a [lindex $x 1]] {
                \" { set cc " !#-~";  set d "\""; set tt char-val  }
                <  { set cc " -=?-~"; set d ">";  set tt prose-val }
                ;  { set cc "\t -~";  set d "\n"; set tt comment   }
            }
        } else {
            set a $z
        }
        while {1} {
            set p0 $pos
            set m [expr ($margin >= 0) ? -1 : 0]
            while {1} {
                if {[regexp -indices -start $pos -- {\A[ \t]+} $text x]} {
                    set pos [expr [lindex $x 1] + 1]
                    if {$m < 0} {
                        # A non-empty line continues with wsp (so far).
                        set nt wsp
                    } else {
                        set s [string range $text [lindex $x 0] [lindex $x 1]]
                        # Accounts for tabs.
                        while {[set x [string first "\t" $s]] >= 0} {
                            incr m $x
                            incr m [expr 8 - ($m % 8)]
                            set s [string range $s [expr $x + 1] end]
                        }
                        incr m [string length $s]
                    }
                }
                if {$margin >= 0} {
                    if {$m > $margin} {
                        # The wsp token is a form of rule continuation.
                        set nt wsp
                    } elseif {$m >= 0} {
                        # Keep nt as nl, if so, but never again wsp.
                        set margin -1
                    }
                }
                if {![regexp -start $pos -- {\A\n} $text]} {
                    break
                }
                # The nl token would mean the end of a rule.
                set nt nl
                incr pos
                set m 0
            }
            if {[info exists nt]} {
                if {![string compare [lindex [lindex $tokens end] 0] wsp]} {
                    # Speed up parsing ("wsp *" can become "wsp ?", "wsp +" can
                    # become "wsp 1", and "wsp *  nl 1" can become "nl 1").
                    set tokens [lreplace $tokens end end]
                }
                # Pretend it's one character long to minimize any current div.
                lappend tokens [list $nt $p0 1]
                unset nt
            }
            if {$margin < 0} {
                set margin $m
            }
            if {$pos >= $a} {
                break
            }
            if {[regexp -start $pos -- {\A[A-Za-z][A-Za-z0-9-]*} $text x]} {
                # RFC 4234, Section 2.1:  Rule names are case-insensitive.
                if {[info exists Chash([string toupper $x])]} {
                    set tok core
                } else {
                    set tok name
                }
            } elseif {[regexp -start $pos -expanded -- \
                              {\A%([bB][01]+((\.[01]+)+|-[01]+)?
                                  |[dD][0-9]+((\.[0-9]+)+|-[0-9]+)?
                                  |[xX][0-9A-Fa-f]+((\.[0-9A-Fa-f]+)+
                                                   |-[0-9A-Fa-f]+)?)} \
                              $text x]} {
                if {   [regexp -- {^%.([^-]+)-([^-]+)$} $x xx yy zz]
                    && [str_pad_cmp $yy $zz] != -1} {
                    set tok err
                } else {
                    set tok num-val
                }
            } elseif {[regexp -start $pos -- {\A=/?} $text x]} {
                set tok eq
            } elseif {[regexp -start $pos -- \
                              {\A([0-9]+|[0-9]*\*[0-9]*)} $text x]} {
                set tok repeat
            } elseif {[regexp -start $pos -- {\A[](/)[]} $text x]} {
                switch -- $x {
                    [ { set tok lsqb  }
                    ] { set tok rsqb  }
                    default { set tok $x }
                }
            } else {
                set tok err
            }
            switch -- $tok {
                err {
                    lappend spans [list err $pos [expr $z - $pos]]
                    set pos $z
                    break
                }
            }
            set len [string length $x]
            lappend tokens [list $tok $pos $len]
            incr pos $len
        }
        if {$pos >= $z} {
            break
        }
        incr pos
        regexp -start $pos -indices -- "\\A\[$cc\]*" $text x
        set len [expr [lindex $x 1] - $pos + 1]
        switch -- $tt {
            comment { lappend spans [list com [expr $pos - 1] [expr $len + 1]] }
            default { lappend tokens [list $tt $pos $len] }
        }
        incr pos $len
        if {$pos >= $z} {
            break
        }
        if {![regexp -start $pos -- "\\A$d" $text]} {
            lappend spans [list err $pos [expr $z - $pos]]
            set pos $z
            break
        }
        switch -- $tt {
            comment {
                # We rely on the next iteration to produces the wsp or nl token.
            }
            default { incr pos }
        }
    }
}
#               }}}4 proc artwork::tokenize::abnf
#               {{{4 artwork::grammar(abnf)
set artwork::grammar(abnf) {
    rulelist {"" = {rule-nl +}}
    rule-nl {
        ""  | {
            rule 1
            nl   1}}
    rule {
        div = {
            ruledef       1
            wsp           ?
            eq            1
            alternation   1
            nl            1}}
    ruledef {
        def | {
            name 1
            core 1}}
    nameuse {id  = {name 1}}
    coreuse {key = {core 1}}
    alternation {
        ""  = {
            concatenation  1
            /concatenation *}}
    /concatenation {
        ""  = {
            /             1
            concatenation 1}}
    concatenation {
        ""  = {
            wsp        ?
            repetition 1
            wsp-rep    *
            wsp        ?}}
    wsp-rep {
        ""  = {
            wsp        1
            repetition 1}}
    repetition {
        ""  = {
            repeat  ?
            element 1}}
    repeat {rep . {}}
    element {
        ""  | {
            char-val  1
            num-val   1
            nameuse   1
            group     1
            option    1
            coreuse   1
            prose-val 1}}
    group {
        ""  = {
            (           1
            alternation 1
            )           1}}
    option {
        ""  = {
            lsqb        1
            alternation 1
            rsqb        1}}
    char-val  {str . {}}
    num-val   {val . {}}
    prose-val {str . {}}
}
# First {token state} pair-items are hash keys and must be in the
# same canonical form as would be produced by [list token state].
set artwork::grammar_program(abnf) {
    {{} 1}  {done}
    {nl 0}  {{goto 1}}
    {nl 1}  {}
    {nl 7}  {{check rule} div-top pop {goto 1}}
    {nl 8}  {{redo 7}}
    {name 0}  {{push rule} {span def} {goto 2}}
    {name 1}  {{redo 0}}
    {name 4}  {{span id} {goto 7}}
    {name 5}  {{redo 4}}
    {name 6}  {{redo 4}}
    {name 8}  {{redo 4}}
    {name 9}  {{redo 4}}
    {core 0}  {{push rule} {span def} {goto 2}}
    {core 1}  {{redo 0}}
    {core 4}  {{span key} {goto 7}}
    {core 5}  {{redo 4}}
    {core 6}  {{redo 4}}
    {core 8}  {{redo 4}}
    {core 9}  {{redo 4}}
    {wsp 2}  {{goto 3}}
    {wsp 4}  {{goto 5}}
    {wsp 7}  {{goto 8}}
    {eq 2}  {{goto 4}}
    {eq 3}  {{goto 4}}
    {repeat 4}  {{span rep} {goto 6}}
    {repeat 5}  {{redo 4}}
    {repeat 8}  {{span rep} {goto 9}}
    {char-val 4}  {{span str} {goto 7}}
    {char-val 5}  {{redo 4}}
    {char-val 6}  {{redo 4}}
    {char-val 8}  {{redo 4}}
    {char-val 9}  {{redo 4}}
    {num-val 4}  {{span val} {goto 7}}
    {num-val 5}  {{redo 4}}
    {num-val 6}  {{redo 4}}
    {num-val 8}  {{redo 4}}
    {num-val 9}  {{redo 4}}
    {prose-val 4}  {{span str} {goto 7}}
    {prose-val 5}  {{redo 4}}
    {prose-val 6}  {{redo 4}}
    {prose-val 8}  {{redo 4}}
    {prose-val 9}  {{redo 4}}
    {( 4}  {push}
    {( 5}  {{redo 4}}
    {( 6}  {{redo 4}}
    {( 8}  {{redo 4}}
    {( 9}  {{redo 4}}
    {lsqb 4}  {push}
    {lsqb 5}  {{redo 4}}
    {lsqb 6}  {{redo 4}}
    {lsqb 8}  {{redo 4}}
    {lsqb 9}  {{redo 4}}
    {/ 7}  {{goto 4}}
    {/ 8}  {{goto 4}}
    {) 7}  {{check (} pop}
    {) 8}  {{redo 7}}
    {rsqb 7}  {{check lsqb} pop}
    {rsqb 8}  {{redo 7}}
}
#               }}}4 artwork::grammar(abnf)
#           }}}3 abnf
#           {{{3 mib
#               {{{4 proc artwork::tokenize::mib
proc artwork::tokenize::mib {} {
    # We do not modify $text.
    upvar text text tokens tokens spans spans
    # Switch statements are not implemented with hashes, so fake it.
    foreach x {
        ALL APPLICATION
        BEGIN
        CHOICE
        DEFINITIONS
        END EXPORTS
        FROM
        IA5String IDENTIFIER IMPLICIT IMPLIED IMPORTS INCLUDES INTEGER
        LAST-UPDATED
        MAX
        NULL
        OBJECT OCTET OF
        SEQUENCE SIZE STRING SYNTAX
        UNIVERSAL
        MACRO
        NOTATION
        TYPE
        Update
        VALUE
        ACCESS AUGMENTS
        CONTACT-INFO CREATION-REQUIRES
        BITS
        DEFVAL DESCRIPTION DISPLAY-HINT
        ENTERPRISE EXTENDS
        GROUP
        INDEX INSTALL-ERRORS
        MANDATORY-GROUPS MAX-ACCESS MIN-ACCESS MODULE
        NOTIFICATIONS
        OBJECTS ORGANIZATION
        PIB-ACCESS PIB-DEFINITIONS PIB-INDEX PIB-MIN-ACCESS
        PIB-REFERENCES PIB-TAG POLICY-ACCESS PRODUCT-RELEASE
        REFERENCE REVISION
        STATUS SUBJECT-CATEGORIES SUPPORTS SYNTAX
        UNIQUENESS UNITS
        VARIABLES VARIATION
        WRITE-SYNTAX
    } {
        # ASN.1 reserved words (current and deprecated)
        # and IETF reserved words.
        set Uhash($x) self
    }
    foreach x {
        Counter32 Counter64
        Gauge32
        Integer32 Integer64 IpAddress
        Opaque
        TimeTicks
        Unsigned32 Unsigned64
    } {
        # IETF application-defined types names.
        set Uhash($x) Itn
    }
    foreach x {
        AGENT-CAPABILITIES
        MODULE-COMPLIANCE MODULE-IDENTITY
        NOTIFICATION-GROUP NOTIFICATION-TYPE
        OBJECT-GROUP OBJECT-IDENTITY OBJECT-TYPE
        TEXTUAL-CONVENTION TRAP-TYPE
    } {
        # IETF macro names.
        set Uhash($x) Imn
    }
    foreach x {
        ABSENT ABSTRACT-SYNTAX ANY AUTOMATIC
        BIT BMPString BOOLEAN BY
        CHARACTER CLASS COMPONENT COMPONENTS CONSTRAINED
        CONTAINING
        DEFAULT DEFINED
        EMBEDDED ENCODED ENCODING-CONTROL ENUMERATED
        EXCEPT EXPLICIT EXTENSIBILITY EXTERNAL
        FALSE
        GeneralizedTime GeneralString GraphicString
        INSTRUCTIONS INTERSECTION ISO646String
        MIN MINUS-INFINITY
        NOT-A-NUMBER NumericString
        ObjectDescriptor OPTIONAL
        PDV PLUS-INFINITY PRESENT PrintableString PRIVATE
        REAL RELATIVE-OID
        SET
        T61String TAGS TeletexString TRUE TYPE-IDENTIFIER
        UNION UNIQUE UniversalString UTCTime UTF8String
        VideotexString VisibleString
        WITH
    } {
        # ASN.1 reserved words (forbidden).
        set Uhash($x) err
    }
    foreach x {
        type
        value
        accessible-for-notify all
        current
        deprecated
        install install-notify
        mandatory
        not-accessible notify not-implemented
        obsolete optional
        read-create read-only read-write report-only
        write-only
    } {
        # ASN.1 type and value (deprecated) and IETF ids.
        set Lhash($x) self
    }
    set pos 0
    set tokens {}
    set spans {}
    set z [string length $text]
    set in_macro 0
    while {$pos < $z} {
        if {[regexp -indices -start $pos -- "--|\"" $text x]} {
            set a [lindex $x 0]
            switch -- [string range $text $a [lindex $x 1]] {
                \" { set tt quoted-string }
                -- { set tt comment       }
            }
        } else {
            set a $z
        }
        while {1} {
            if {[regexp -indices -start $pos -- {\A[ \t\n]+} $text x]} {
                set pos [expr [lindex $x 1] + 1]
            }
            if {$pos >= $a} {
                break
            }
            set p2 -1
            set len -1
            if {[regexp -start $pos -- {\A[A-Z](-?[A-Za-z0-9]+)*} $text x]} {
                set len [string length $x]
                if {[info exists Uhash($x)]} {
                    switch -- $Uhash($x) {
                        self {
                            # ASN.1 reserved words (current and deprecated)
                            # and IETF reserved words.
                            set tok $x
                            # Cheat.
                            lappend spans [list key $pos $len]
                            # XXX
                            switch -- $x {
                                MACRO { incr in_macro }
                                END { if {$in_macro > 0} {incr in_macro -1} }
                            }
                        }
                        Itn { set prefix_tok /Itn; set tok $x }
                        Imn { set prefix_tok /Imn; set tok $x }
                        err { set tok err }
                    }
                } else {
                    set tok type-ref
                }
            } elseif {[regexp -start $pos -- {\A[a-z](-?[A-Za-z0-9]+)*} $text x]} {
                # Hyphens are allowed for backward compatibility with SMIv1.
                # Extra token to avoid considering them all.
                set prefix_tok /id
                set len [string length $x]
                if {[info exists Lhash($x)]} {
                    set tok $x
                } else {
                    set tok id
                }
            } elseif {   [regexp -start $pos -indices -- \
                                 {\A'([01]{8})*'[Bb]} $text x]
                      || [regexp -start $pos -indices -- \
                                 {\A'([0-9A-Fa-f]{2})*'[Hh]} $text x]} {
                set tok radix-string
                incr pos
                set p2 [expr [lindex $x 1] + 1]
                set len [expr $p2 - $pos - 2]
            } elseif {[regexp -start $pos -- {\A::=} $text x]} {
                set tok ::=
                # XXX
                if {$in_macro > 0} {
                    set tx [lindex $tokens end]
                    switch -- [lindex $tx 0] {
                        type-ref {
                            set tokens [lreplace $tokens end end \
                                        [lreplace $tx 0 0 type-ref-macsyn]]
                        }
                    }
                }
            } elseif {[regexp -start $pos -- {\A\.\.} $text x]} {
                set tok ..
            } elseif {[regexp -start $pos -- {\A[0-9]+} $text x]} {
                set len [string length $x]
                if {![string compare [string index $x 0] "0"]} {
                    if {$len == 1} {
                        set tok zero
                    } else {
                        set tok err
                    }
                } elseif {$len < 10} {
                    set tok positive31
                } elseif {$len == 10} {
                    if {[string compare $x "2147483648"] < 0} {
                        set tok positive31
                    } elseif {[string compare $x "4294967296"] < 0} {
                        set tok positive32
                    } else {
                        set tok positive63
                    }
                } elseif {$len < 19} {
                    set tok positive63
                } elseif {$len == 19} {
                    if {[string compare $x "9223372036854775808"] < 0} {
                        set tok positive63
                    } else {
                        set tok positive64
                    }
                } elseif {$len == 20} {
                    if {[string compare $x "18446744073709551616"] < 0} {
                        set tok positive64
                    } else {
                        set tok positive-big
                    }
                } else {
                    set tok positive-big
                }
            } elseif {[regexp -start $pos -- {\A-[0-9]+} $text x]} {
                set len [string length $x]
                if {![string compare [string index $x 1] "0"]} {
                    set tok err
                } elseif {$len < 11} {
                    set tok negative31
                } elseif {$len == 11} {
                    if {[string compare $x "-2147483648"] <= 0} {
                        set tok negative31
                    } else {
                        set tok negative63
                    }
                } elseif {$len < 20} {
                    set tok negative63
                } elseif {$len == 20} {
                    if {[string compare $x "-9223372036854775808"] <= 0} {
                        set tok negative63
                    } else {
                        set tok negative-big
                    }
                } else {
                    set tok negative-big
                }
            } elseif {[regexp -start $pos -- {\A[]{(|,--.;:)}[]} $text x]} {
                switch -- $x {
                    ;  { set tok semi }
                    [  { set tok lsqb }
                    ]  { set tok rsqb }
                    \{ { set tok lcub }
                    \} { set tok rcub }
                    default { set tok $x }
                }
            } else {
                set tok err
            }
            switch -glob -- $tok {
                zero - positive* - negative* {
                    # Cheat.
                    lappend spans [list val $pos $len]
                }
                err {
                    lappend spans [list err $pos [expr $z - $pos]]
                    set pos $z
                    break
                }
            }
            if {$len < 0} {
                set len [string length $x]
            }
            if {[info exists prefix_tok]} {
                lappend tokens [list $prefix_tok $pos $len]
                unset prefix_tok
            }
            lappend tokens [list $tok $pos $len]
            if {$p2 >= 0} {
                set pos $p2
            } else {
                incr pos $len
            }
        }
        if {$pos >= $z} {
            break
        }
        switch -- $tt {
            quoted-string {
                lappend tokens [list quot $pos 1]
                incr pos
                while {1} {
                    regexp -start $pos -indices -- {\A[\t !#-~]*} $text x
                    set p2 [expr [lindex $x 1] + 1]
                    if {$p2 > $pos} {
                        lappend tokens [list qstr $pos [expr $p2 - $pos]]
                        set pos $p2
                    }
                    set x [string index $text $pos]
                    if {![string compare $x \"]} {
                        lappend tokens [list quot $pos 1]
                        incr pos
                        break
                    }
                    if {[string compare $x "\n"]} {
                        lappend spans [list err $pos [expr $z - $pos]]
                        set pos $z
                        break
                    }
                    incr pos
                    if {[regexp -start $pos -indices -- {\A[\t ]+} $text x]} {
                        # Eliminate indentation white-space on subsequent lines.
                        set pos [expr [lindex $x 1] + 1]
                    }
                }
            }
            comment {
                regexp -start $pos -indices -- \
                       {\A--([^-\n]|----|-[^-\n])*} $text x
                set p2 [expr [lindex $x 1] + 1]
                if {   $p2 < $z
                    && ![string compare [string index $text $p2] "-"]} {
                    incr p2
                    if {![string compare [string index $text $p2] "-"]} {
                        incr p2
                    }
                }
                lappend spans [list com $pos [expr $p2 - $pos]]
                set pos $p2
            }
        }
    }
}
#               }}}4 proc artwork::tokenize::mib
#               {{{4 artwork::grammar(mib)
set artwork::grammar(mib) {
    mib-file {"" = {module *}}
    module {
        div = {
            type-ref-def   1
            lcub-oid-rcub  ?
            definitions-kw 1
            ::=            1
            BEGIN          1
            exports-stmt   ?
            imports-stmt   ?
            definition     *
            END            1}}
    definitions-kw {
        ""  | {
            DEFINITIONS     1
            PIB-DEFINITIONS 1}}
    exports-stmt {
        div = {
            EXPORTS  1
            exported ?
            semi     1}}
    exported {
        ""  | {
            ALL            1
            export-id-list 1}}
    export-id-list {
        ""  = {
            export-id  1
            ,export-id *}}
    ,export-id {
        ""  = {
            ,         1
            export-id 1}}
    export-id {
        ""  | {
            id-use              1
            type-ref-use        1
            IpAddress-use       1
            Opaque-use          1
            TimeTicks-use       1
            IETF-macro-name-use 1}}
    imports-stmt {
        div = {
            IMPORTS  1
            imported *
            semi     1}}
    imported {
        ""  = {
            import-id-list 1
            FROM           1
            type-ref-use   1}}
    import-id-list {
        ""  = {
            import-id  1
            ,import-id *}}
    ,import-id {
        ""  = {
            ,         1
            import-id 1}}
    import-id {
        ""  | {
            semi                !
            id-use              1
            type-ref-use        1
            BITS                1
            MANDATORY-GROUPS    1
            IETF-macro-name-use 1
            IETF-type-name-use  1}}
    definition {
        div | {
            END        !
            id-defn1   1
            tr-defn1   1
            macro-defn 1}}
    id-defn1 {
        ""  = {
            id-def   1
            id-defn2 1}}
    id-defn2 {
        ""  | {
            value-defn       1
            obj-type-defn    1
            obj-group-defn   1
            mod-compl-defn   1
            mod-id-defn      1
            obj-id-defn      1
            notif-type-defn  1
            notif-group-defn 1
            trap-type-defn   1
            agent-caps-defn  1}}
    tr-defn1 {
        ""  | {
            type-defn 1
            tr-defn2  1}}
    tr-defn2 {
        ""  = {
            type-ref-err 1
            value-defn   1}}
    mod-id-defn {
        ""  = {
            MODULE-IDENTITY-use 1
            subj-cats-clause    ?
            LAST-UPDATED        1
            quoted-string       1
            ORGANIZATION        1
            quoted-string       1
            CONTACT-INFO        1
            quoted-string       1
            description-clause  1
            revision-clause     *
            ::=                 1
            lcub-oid-rcub       1}}
    subj-cats-clause {
        ""  = {
            SUBJECT-CATEGORIES 1
            lcub               1
            cat-ids            1
            rcub               1}}
    cat-ids {
        ""  | {
            IETF-pib-all-kw   1
            id(positive)-list 1}}
    description-clause {
        div = {
            DESCRIPTION   1
            quoted-string 1}}
    revision-clause {
        div = {
            REVISION           1
            quoted-string      1
            description-clause 1}}
    obj-id-defn {
        ""  = {
            OBJECT-IDENTITY-use 1
            status-clause       1
            description-clause  1
            ref-clause          ?
            ::=                 1
            lcub-oid-rcub       1}}
    status-clause {
        ""  = {
            STATUS            1
            IETF-status-id-kw 1}}
    ref-clause {
        ""  = {
            REFERENCE     1
            quoted-string 1}}
    obj-type-defn {
        ""  = {
            OBJECT-TYPE-use    1
            syntax-clause      1
            units-clause       ?
            access-clause      ?
            sppi-refs-clause   ?
            sppi-tag-clause    ?
            status-clause      1
            description-clause ?
            sppi-errors-clause ?
            ref-clause         ?
            index-clause       ?
            mib-index-clause   ?
            sppi-unique-clause ?
            defval-clause      ?
            ::=                1
            lcub-oid-rcub      1}}
    syntax-clause {
        ""  = {
            SYNTAX 1
            syntax 1}}
    units-clause {
        ""  = {
            UNITS         1
            quoted-string 1}}
    access-clause {
        ""  | {
            max-access-clause 1
            pib-access-clause 1}}
    max-access-clause {
        ""  = {
            max-access-kw     1
            IETF-access-id-kw 1}}
    max-access-kw {
        ""  | {
            MAX-ACCESS 1
            ACCESS     1}}
    pib-access-clause {
        ""  = {
            pib-access-kw         1
            IETF-pib-access-id-kw 1}}
    pib-access-kw {
        ""  | {
            POLICY-ACCESS 1
            PIB-ACCESS    1}}
    sppi-refs-clause {
        ""  = {
            PIB-REFERENCES 1
            lcub-oid-rcub  1}}
    sppi-tag-clause {
        ""  = {
            PIB-TAG       1
            lcub-oid-rcub 1}}
    sppi-errors-clause {
        ""  = {
            INSTALL-ERRORS        1
            lcub                  1
            id(positive)-list     1
            rcub                  1}}
    index-clause {
        ""  | {
            pib-index-clause 1
            augments-clause  1
            extends-clause   1}}
    pib-index-clause {
        ""  = {
            PIB-INDEX     1
            lcub-oid-rcub 1}}
    augments-clause {
        ""  = {
            AUGMENTS      1
            lcub-oid-rcub 1}}
    extends-clause {
        ""  = {
            EXTENDS       1
            lcub-oid-rcub 1}}
    mib-index-clause {
        ""  = {
            INDEX           1
            lcub            1
            index-type-list 1
            rcub            1}}
    index-type-list {
        ""  = {
            index-type  1
            ,index-type *}}
    ,index-type {
        ""  = {
            ,          1
            index-type 1}}
    index-type {
        ""  = {
            IMPLIED ?
            oid     1}}
    sppi-unique-clause {
        ""  = {
            UNIQUENESS 1
            lcub       1
            oid-list   ?
            rcub       1}}
    defval-clause {
        ""  = {
            DEFVAL 1
            lcub   1
            defval 1
            rcub   1}}
    defval {
        ""  | {
            int                  1
            radix-string         1
            quoted-string        1
            id-use               1
            lcub-oid-defval-rcub 1
            lcub-id-list-rcub    1}}
    lcub-oid-defval-rcub {
        ""  = {
            lcub          1
            sub-id-defval +
            rcub          1}}
    lcub-id-list-rcub {
        ""  = {
            lcub    1
            id-list ?
            rcub    1}}
    notif-type-defn {
        ""  = {
            NOTIFICATION-TYPE-use 1
            objs-clause           ?
            status-clause         1
            description-clause    1
            ref-clause            ?
            ::=                   1
            lcub-oid-rcub         1}}
    objs-clause {
        ""  = {
            OBJECTS            1
            lcub-oid-list-rcub 1}}
    trap-type-defn {
        ""  = {
            TRAP-TYPE-use      1
            ENTERPRISE         1
            oid                1
            vars-clause        ?
            description-clause ?
            ref-clause         ?
            ::=                1
            int                1}}
    vars-clause {
        ""  = {
            VARIABLES          1
            lcub-oid-list-rcub 1}}
    value-defn {
        ""  = {
            OBJECT-IDENTIFIER 1
            ::=               1
            lcub-oid-rcub     1}}
    type-defn {
        ""  = {
            type-name-def 1
            ::=           1
            type-decl     1}}
    type-name-def {
        ""  | {
            type-ref-def       1
            IETF-type-name-def 1}}
    type-decl {
        ""  | {
            syntax      1
            tc-stmt     1
            choice-stmt 1}}
    tc-stmt {
        ""  = {
            TEXTUAL-CONVENTION-use 1
            display-hint-clause    ?
            status-clause          1
            description-clause     1
            ref-clause             ?
            syntax-clause          1}}
    display-hint-clause {
        ""  = {
            DISPLAY-HINT  1
            quoted-string 1}}
    choice-stmt {
        ""  = {
            CHOICE          1
            lcub            1
            named-type-list 1
            rcub            1}}
    named-type-list {
        ""  = {
            named-type  1
            ,named-type *}}
    ,named-type {
        ""  = {
            ,          1
            named-type 1}}
    named-type {
        ""  = {
            id-def   1
            n-t-type 1}}
    n-t-type {
        ""  | {
            type-ref-use       1
            IETF-type-name-use 1
            NULL               1
            octet-str          1
            OBJECT-IDENTIFIER  1
            INTEGER(0..MAX)    1
            INTEGER(9)         1
            Integer32(ranges)  1}}
    INTEGER(0..MAX) {
        ""  = {
            INTEGER 1
            (       1
            zero    1
            ..      1
            MAX     1
            )       1}}
    mod-compl-defn {
        ""  = {
            MODULE-COMPLIANCE-use 1
            status-clause         1
            description-clause    1
            ref-clause            ?
            compl-module-clause   +
            ::=                   1
            lcub-oid-rcub         1}}
    compl-module-clause {
        ""  = {
            MODULE           1
            compl-mod-name   ?
            mand-grps-clause ?
            compl            *}}
    compl-mod-name {
        ""  = {
            type-ref-use 1
            oid          ?}}
    mand-grps-clause {
        ""  = {
            MANDATORY-GROUPS   1
            lcub-oid-list-rcub 1}}
    compl {
        ""  | {
            compl-group 1
            compl-obj   1}}
    compl-group {
        ""  = {
            GROUP              1
            oid                1
            description-clause 1}}
    compl-obj {
        ""  = {
            OBJECT              1
            oid                 1
            syntax-clause       ?
            write-syntax-clause ?
            *min-access-clause  ?
            description-clause  1}}
    write-syntax-clause {
        ""  = {
            WRITE-SYNTAX 1
            syntax       1}}
    *min-access-clause {
        ""  | {
            min-access-clause     1
            pib-min-access-clause 1}}
    min-access-clause {
        ""  = {
            MIN-ACCESS        1
            IETF-access-id-kw 1}}
    pib-min-access-clause {
        ""  = {
            PIB-MIN-ACCESS        1
            IETF-pib-access-id-kw 1}}
    obj-group-defn {
        ""  = {
            OBJECT-GROUP-use   1
            objs-clause        1
            status-clause      1
            description-clause 1
            ref-clause         ?
            ::=                1
            lcub-oid-rcub      1}}
    notif-group-defn {
        ""  = {
            NOTIFICATION-GROUP-use 1
            notifs-clause          1
            status-clause          1
            description-clause     1
            ref-clause             ?
            ::=                    1
            lcub-oid-rcub          1}}
    notifs-clause {
        ""  = {
            NOTIFICATIONS      1
            lcub-oid-list-rcub 1}}
    agent-caps-defn {
        ""  = {
            AGENT-CAPABILITIES-use 1
            PRODUCT-RELEASE        1
            quoted-string          1
            status-clause          1
            description-clause     1
            ref-clause             ?
            agent-caps-mod-part    *
            ::=                    1
            lcub-oid-rcub          1}}
    agent-caps-mod-part {
        ""  = {
            SUPPORTS           1
            type-ref-use       1
            oid                ?
            INCLUDES           1
            lcub-oid-list-rcub 1
            variation          *}}
    variation {
        ""  = {
            VARIATION           1
            oid                 1
            syntax-clause       ?
            write-syntax-clause ?
            access-part         ?
            creation-part       ?
            defval-clause       ?
            description-clause  1}}
    access-part {
        ""  = {
            ACCESS            1
            IETF-access-id-kw 1}}
    creation-part {
        ""  = {
            CREATION-REQUIRES  1
            lcub-oid-list-rcub 1}}
    lcub-oid-rcub {
        ""  = {
            lcub 1
            oid  1
            rcub 1}}
    lcub-oid-list-rcub {
        ""  = {
            lcub     1
            oid-list 1
            rcub     1}}
    oid-list {
        ""  = {
            oid  1
            ,oid *}}
    ,oid {
        ""  = {
            ,   1
            oid 1}}
    oid {"" = {sub-id +}}
    sub-id {
        ""  | {
            ,              !
            rcub           !
            uint32         1
            id(uint32)     1
            id-use         1
            mod-id(uint32) 1
            mod-id         1
            type-ref-err   1}}
    mod-id {
        ""  = {
            type-ref-use 1
            .            1
            id-use       1}}
    mod-id(uint32) {
        ""  = {
            type-ref-use 1
            .            1
            id(uint32)   1}}
    sub-id-defval {
        ""  | {
            rcub       !
            id(uint32) 1
            uint32     1}}
    syntax {
        ""  | {
            bits-construct        1
            basic-syntax          1
            type-tag-basic-syntax 1
            type-ref-use          1
            SEQUENCE-OF-syntax    1
            SEQUENCE-syntax       1
            appl-syntax           1}}
    bits-construct {
        ""  = {
            BITS              1
            lcub              1
            id-def(uint)-list 1
            rcub              1}}
    type-tag-basic-syntax {
        ""  = {
            type-tag     1
            basic-syntax 1}}
    type-tag {
        ""  = {
            lsqb     1
            class    1
            uint     1
            rsqb     1
            IMPLICIT 1}}
    class {
        ""  | {
            APPLICATION 1
            UNIVERSAL   1}}
    basic-syntax {
        ""  | {
            INTEGER(9)        1
            Integer32(ranges) 1
            type*(*)          1
            octet-str         1
            obj-id(*)         1}}
    INTEGER(9) {
        ""  = {
            INTEGER 1
            (9)     ?}}
    Integer32(ranges) {
        ""  = {
            Integer32-use 1
            (ranges)      ?}}
    type*(*) {
        ""  = {
            type-ref-use 1
            .IntType     ?
            (*)          1}}
    .IntType {
        ""  = {
            .            1
            type-ref-use 1}}
    octet-str {
        ""  = {
            OCTET-STRING 1
            (SIZE)       ?}}
    obj-id(*) {
        ""  = {
            OBJECT-IDENTIFIER 1
            (*)               ?}}
    SEQUENCE-OF-syntax {
        ""  = {
            SEQUENCE     1
            OF           1
            type-ref-use 1}}
    SEQUENCE-syntax {
        ""  = {
            SEQUENCE      1
            lcub          1
            seq-item-list 1
            rcub          1}}
    seq-item-list {
        ""  = {
            seq-item  1
            ,seq-item *}}
    ,seq-item {
        ""  = {
            ,        1
            seq-item 1}}
    seq-item {
        ""  = {
            id-use     1
            seq-syntax 1
            kludge-(*) ?}}
    seq-syntax {
        ""  | {
            INTEGER            1
            BITS               1
            OCTET-STRING       1
            OBJECT-IDENTIFIER  1
            type-ref-use       1
            IETF-type-name-use 1}}
    kludge-(*) {err = {(*) 1}}
    appl-syntax {
        ""  | {
            IpAddress(*)       1
            Counter32(*)       1
            Gauge32(ranges)    1
            Unsigned32(ranges) 1
            TimeTicks-use      1
            Opaque(SIZE)       1
            Counter64(*)       1
            Integer64(ranges)  1
            Unsigned64(ranges) 1}}
    IpAddress(*) {
        ""  = {
            IpAddress-use 1
            (*)           ?}}
    Counter32(*) {
        ""  = {
            Counter32-use 1
            (*)           ?}}
    Gauge32(ranges) {
        ""  = {
            Gauge32-use 1
            (ranges)    ?}}
    Unsigned32(ranges) {
        ""  = {
            Unsigned32-use 1
            (ranges)       ?}}
    Opaque(SIZE) {
        ""  = {
            Opaque-use 1
            (SIZE)     ?}}
    Counter64(*) {
        ""  = {
            Counter64-use 1
            (*)           ?}}
    Integer64(ranges) {
        ""  = {
            Integer64-use 1
            (ranges)      ?}}
    Unsigned64(ranges) {
        ""  = {
            Unsigned64-use 1
            (ranges)       ?}}
    (*) {
        ""  | {
            (ranges) 1
            (SIZE)   1
            enum     1}}
    (9) {
        ""  | {
            (ranges) 1
            enum     1}}
    (SIZE) {
        ""  = {
            (        1
            SIZE     1
            (ranges) 1
            )        1}}
    (ranges) {
        ""  = {
            (      1
            range  1
            |range *
            )      1}}
    |range {
        ""  = {
            |     1
            range 1}}
    range {
        ""  = {
            bound   1
            ..bound ?}}
    ..bound {
        ""  = {
            ..    1
            bound 1}}
    bound {
        ""  | {
            int          1
            radix-string 1}}
    enum {
        ""  = {
            lcub             1
            id-def(int)-list 1
            rcub             1}}
    macro-defn {
        ""  = {
            IETF-macro-name-def 1
            MACRO               1
            ::=                 1
            BEGIN               1
            TYPE                1
            NOTATION            1
            ::=                 1
            type-notation       +
            VALUE               1
            NOTATION            1
            ::=                 1
            value-notation      1
            macro-syntax        *
            END                 1}}
    type-notation {
        ""  | {
            type-ref-use  1
            VALUE         !
            quoted-string 1
            t-n-type      1
            t-n-value     1}}
    t-n-type {
        ""  = {
            type-kw      1
            (            1
            TYPE         ?
            type-ref-use 1
            )            1}}
    t-n-value {
        ""  = {
            value-kw  1
            (         1
            t-n-v-arg 1
            )         1}}
    t-n-v-arg {
        ""  | {
            value-arg1 1
            value-arg2 1}}
    value-notation {
        ""  = {
            value-kw 1
            (        1
            VALUE    1
            v-n-arg  1
            )        1}}
    v-n-arg {
        ""  | {
            OBJECT-IDENTIFIER 1
            INTEGER           1
            type-ref-use      1}}
    macro-syntax {
        ""  = {
            type-ref-macsyn   1
            ::=               1
            macro-syntax-alt  1
            |macro-syntax-alt *}}
    |macro-syntax-alt {
        ""  = {
            |                1
            macro-syntax-alt 1}}
    macro-syntax-alt {
        ""  = {
            macro-syntax-item +}}
    macro-syntax-item {
        ""  | {
            type-ref-use    1
            END             !
            type-ref-macsyn !
            quoted-string   1
            m-s-a-type      1
            m-s-a-value     1
            id-use          1}}
    m-s-a-type {
        ""  = {
            type-kw       1
            (m-s-a-t-arg) ?}}
    (m-s-a-t-arg) {
        ""  = {
            (      1
            id-use 1
            )      1}}
    m-s-a-value {
        ""  = {
            value-kw    1
            (           1
            m-s-a-v-arg 1
            )           1}}
    m-s-a-v-arg {
        ""  | {
            OBJECT-IDENTIFIER 1
            IA5String         1
            type-ref-use      1
            value-arg1        1
            value-arg3        1}}
    value-arg1 {
        ""  = {
            Update       1
            type-ref-use 1}}
    value-arg2 {
        ""  = {
            id-use            1
            OBJECT-IDENTIFIER 1}}
    value-arg3 {
        ""  = {
            id-use       1
            type-ref-use 1}}
    OBJECT-IDENTIFIER {
        ""  = {
            OBJECT     1
            IDENTIFIER 1}}
    OCTET-STRING {
        ""  = {
            OCTET  1
            STRING 1}}
    type-ref-def {def = {type-ref 1}}
    type-ref-use {id  = {type-ref 1}}
    type-ref-err {err = {type-ref 1}}
    type-ref-macsyn {def . {}}
    id-def {def = {/id 1  * 1}}
    id-use {id  = {/id 1  * 1}}
    id-kw  {key = {/id 1  * 1}}
    id-list {
        ""  = {
            id-use  1
            ,id-use *}}
    ,id-use {
        ""  = {
            ,      1
            id-use 1}}
    quoted-string {
        ""  = {
            quot 1
            qstr *
            quot 1}}
    qstr {str . {}}
    positive {
        ""  | {
            positive31   1
            positive32   1
            positive63   1
            positive64   1
            positive-big 1}}
    negative {
        ""  | {
            negative31   1
            negative63   1
            negative-big 1}}
    uint {
        ""  | {
            zero     1
            positive 1}}
    uint32 {
        ""  | {
            positive31   1
            zero     1
            positive32   1}}
    int {
        ""  | {
            positive31   1
            zero         1
            positive32   1
            negative31   1
            positive63   1
            positive64   1
            negative63   1
            positive-big 1
            negative-big 1}}
    id(positive)-list {
        ""  = {
            id(positive)  1
            ,id(positive) *}}
    ,id(positive) {
        ""  = {
            ,            1
            id(positive) 1}}
    id(positive) {
        ""  = {
            id-use   1
            (        1
            positive 1
            )        1}}
    id-def(uint)-list {
        ""  = {
            id-def(uint)  1
            ,id-def(uint) *}}
    ,id-def(uint) {
        ""  = {
            ,        1
            id-def(uint) 1}}
    id-def(uint) {
        ""  = {
            id-def 1
            (      1
            uint   1
            )      1}}
    id(uint32) {
        ""  = {
            id-use 1
            (      1
            uint32 1
            )      1}}
    id-def(int)-list {
        ""  = {
            id-def(int)  1
            ,id-def(int) *}}
    ,id-def(int) {
        ""  = {
            ,       1
            id-def(int) 1}}
    id-def(int) {
        ""  = {
            id-def 1
            (      1
            int    1
            )      1}}
    radix-string {val . {}}
    IETF-macro-name-def {def = {/Imn 1  * 1}}
    IETF-macro-name-use {id  = {/Imn 1  * 1}}
    AGENT-CAPABILITIES-use {rep = {/Imn 1  AGENT-CAPABILITIES 1}}
    MODULE-COMPLIANCE-use  {rep = {/Imn 1  MODULE-COMPLIANCE  1}}
    MODULE-IDENTITY-use    {rep = {/Imn 1  MODULE-IDENTITY    1}}
    NOTIFICATION-GROUP-use {rep = {/Imn 1  NOTIFICATION-GROUP 1}}
    NOTIFICATION-TYPE-use  {rep = {/Imn 1  NOTIFICATION-TYPE  1}}
    OBJECT-GROUP-use       {rep = {/Imn 1  OBJECT-GROUP       1}}
    OBJECT-IDENTITY-use    {rep = {/Imn 1  OBJECT-IDENTITY    1}}
    OBJECT-TYPE-use        {rep = {/Imn 1  OBJECT-TYPE        1}}
    TEXTUAL-CONVENTION-use {rep = {/Imn 1  TEXTUAL-CONVENTION 1}}
    TRAP-TYPE-use          {rep = {/Imn 1  TRAP-TYPE          1}}
    IETF-type-name-def {def = {/Itn 1  * 1}}
    IETF-type-name-use {id  = {/Itn 1  * 1}}
    Counter32-use  {id = {/Itn 1  Counter32  1}}
    Counter64-use  {id = {/Itn 1  Counter64  1}}
    Gauge32-use    {id = {/Itn 1  Gauge32    1}}
    Integer32-use  {id = {/Itn 1  Integer32  1}}
    Integer64-use  {id = {/Itn 1  Integer64  1}}
    IpAddress-use  {id = {/Itn 1  IpAddress  1}}
    Opaque-use     {id = {/Itn 1  Opaque     1}}
    TimeTicks-use  {id = {/Itn 1  TimeTicks  1}}
    Unsigned32-use {id = {/Itn 1  Unsigned32 1}}
    Unsigned64-use {id = {/Itn 1  Unsigned64 1}}
    type-kw  {key = {/id 1  type  1}}
    value-kw {key = {/id 1  value 1}}
    IETF-status-id-kw {key = {/id 1  IETF-status-id 1}}
    IETF-status-id {
        ""  | {
            current    1
            mandatory  1
            deprecated 1
            obsolete   1
            optional   1}}
    IETF-access-id-kw {key = {/id 1  IETF-access-id 1}}
    IETF-access-id {
        ""  | {
            read-only             1
            not-accessible        1
            read-create           1
            read-write            1
            not-implemented       1
            accessible-for-notify 1
            write-only            1}}
    IETF-pib-access-id-kw {key = {/id 1  IETF-pib-access-id 1}}
    IETF-pib-access-id {
        ""  | {
            not-accessible 1
            install        1
            notify         1
            install-notify 1
            report-only    1}}
    IETF-pib-all-kw {key = {/id 1  IETF-pib-all 1}}
    IETF-pib-all {"" = {all 1}}
    * {"" *}
}
# First {token state} pair-items are hash keys and must be in the
# same canonical form as would be produced by [list token state].
set artwork::grammar_program(mib) {
    {{} 0}  {done}
    {type-ref 0}  {{push module} {span def} {goto m1}}
    {lcub m1}  {{push m1} {redo lor1d}}
    {DEFINITIONS m1}  {{span key} {goto m3}}
    {DEFINITIONS m2}  {{redo m1}}
    {PIB-DEFINITIONS m1}  {{span key} {goto m3}}
    {PIB-DEFINITIONS m2}  {{redo m1}}
    {::= m3}  {{goto m4}}
    {BEGIN m4}  {{goto m5}}
    {END m5}  {{redo m7}}
    {END m6}  {{redo m7}}
    {END m7}  {{check module} div-top pop {goto 0}}
    {EXPORTS m5}  {{push exports} {goto ex1}}
    {IMPORTS m5}  {{push imports} {goto im1}}
    {IMPORTS m6}  {{redo m5}}
    {/id m5}  {{redo m7}}
    {/id m6}  {{redo m7}}
    {/id m7}  {{push defn} {span def} skip-next {goto m9}}
    {type-ref m5}  {{redo m7}}
    {type-ref m6}  {{redo m7}}
    {type-ref m7}  {{push defn} {goto m11}}
    {/Imn m5}  {{redo m7}}
    {/Imn m6}  {{redo m7}}
    {/Imn m7}  {{push defn} {span def} skip-next {goto mac0}}
    {/Itn m5}  {{redo m7}}
    {/Itn m6}  {{redo m7}}
    {/Itn m7}  {{push defn} {span def} skip-next {goto td0}}
    {/Imn m9}  {{goto m10}}
    {OBJECT m9}  {{goto m14}}
    {MODULE-IDENTITY m10}     {{span rep} {goto my1}}
    {OBJECT-IDENTITY m10}     {{span rep} {goto oy1}}
    {OBJECT-TYPE m10}         {{span rep} {goto ot1}}
    {NOTIFICATION-TYPE m10}   {{span rep} {goto nt0}}
    {TRAP-TYPE m10}           {{span rep} {goto tt0}}
    {MODULE-COMPLIANCE m10}   {{span rep} {goto mc0}}
    {OBJECT-GROUP m10}        {{span rep} {goto og0}}
    {NOTIFICATION-GROUP m10}  {{span rep} {goto ng0}}
    {AGENT-CAPABILITIES m10}  {{span rep} {goto ac0}}
    {::= m11}  {{redo m12 1}}
    {OBJECT m11}  {{redo m13 1}}
    {type-ref m12}  {{span def} skip-next {goto td1}}
    {type-ref m13}  {{span err} skip-next {goto m14}}
    {IDENTIFIER m14}  {{goto oi0}}
    {* m99}  {{check defn} div-top pop {goto m7}}
    {semi ex1}  {{redo ex3}}
    {semi ex3}  {{check exports} div-top pop {goto m6}}
    {semi ex4}  {{redo ex3}}
    {ALL ex1}  {{goto ex4}}
    {/id ex1}  {{redo ex2}}
    {/id ex2}  {{span id} skip-next {goto ex3}}
    {type-ref ex1}  {{redo ex2}}
    {type-ref ex2}  {{span id} {goto ex3}}
    {/Itn ex1}  {{redo ex2}}
    {/Itn ex2}  {{span id} skip-next {goto ex3}}
    {/Imn ex1}  {{redo ex2}}
    {/Imn ex2}  {{span id} skip-next {goto ex3}}
    {, ex3}  {{goto ex2}}
    {semi im1}  {{check imports} div-top pop {goto m7}}
    {/id im1}  {{span id} skip-next {goto im3}}
    {/id im2}  {{redo im1}}
    {type-ref im1}  {{span id} {goto im3}}
    {type-ref im2}  {{redo im1}}
    {BITS im1}  {{goto im3}}
    {BITS im2}  {{goto im3}}
    {MANDATORY-GROUPS im1}  {{goto im3}}
    {MANDATORY-GROUPS im2}  {{goto im3}}
    {/Imn im1}  {{span id} skip-next {goto im3}}
    {/Imn im2}  {{redo im1}}
    {/Itn im1}  {{span id} skip-next {goto im3}}
    {/Itn im2}  {{redo im1}}
    {, im3}  {{goto im2}}
    {FROM im3}  {{goto im4}}
    {type-ref im4}  {{span id} {goto im1}}
    {SUBJECT-CATEGORIES my1}  {{goto my2}}
    {lcub my2}  {{goto my3}}
    {/id my3}  {{goto my4}}
    {all my4}  {{span key} {goto my11}}
    {id my4}   {{span id} {goto my5}}
    {* my4}    {{span id} {goto my5}}
    {( my5}  {{goto my6}}
    {positive31 my6}    {{goto my7}}
    {positive32 my6}    {{goto my7}}
    {positive63 my6}    {{goto my7}}
    {positive64 my6}    {{goto my7}}
    {positive-big my6}  {{goto my7}}
    {) my7}  {{goto my8}}
    {rcub my8}  {{goto my20}}
    {, my8}     {{goto my9}}
    {/id my9}  {{goto my10}}
    {all my10}  {{span err} {goto my11}}
    {id my10}   {{span id} {goto my5}}
    {* my10}    {{span id} {goto my5}}
    {rcub my11}  {{goto my20}}
    {LAST-UPDATED my1}   {{redo my20}}
    {LAST-UPDATED my20}   {{push my21} {goto qs1}}
    {ORGANIZATION my21}  {{push my22} {goto qs1}}
    {CONTACT-INFO my22}  {{push my23} {goto qs1}}
    {DESCRIPTION my23}   {{push my24} {goto qs1d}}
    {::= my24}           {{goto lor1d}}
    {REVISION my24}      {{push my25} {goto qs1x}}
    {DESCRIPTION my25}   {{push my24} {goto qs1dd}}
    {STATUS oy1}  {{goto oy2}}
    {/id oy2}  {{goto oy3}}
    {current oy3}     {{span key} {goto oy4}}
    {deprecated oy3}  {{span key} {goto oy4}}
    {obsolete oy3}    {{span key} {goto oy4}}
    {* oy3}           {{span err} {goto oy4}}
    {DESCRIPTION oy4}  {{push oy5} {goto qs1d}}
    {REFERENCE oy5}    {{push oy6} {goto qs1}}
    {::= oy5}  {{goto lor1d}}
    {::= oy6}  {{goto lor1d}}
    {SYNTAX ot1}  {{push ot2} {goto sx0}}
    {UNITS ot2}  {{push ot3} {goto qs1}}
    {MAX-ACCESS ot2}  {{goto ot4}}
    {MAX-ACCESS ot3}  {{goto ot4}}
    {/id ot4}  {{goto ot5}}
    {not-accessible ot5}         {{span key} {goto ot12}}
    {accessible-for-notify ot5}  {{span key} {goto ot12}}
    {read-only ot5}              {{span key} {goto ot12}}
    {read-write ot5}             {{span key} {goto ot12}}
    {read-create ot5}            {{span key} {goto ot12}}
    {* ot5}                      {{span err} {goto ot12}}
    {ACCESS ot2}  {{goto ot6}}
    {ACCESS ot3}  {{goto ot6}}
    {/id ot6}  {{goto ot7}}
    {read-only ot7}       {{span key} {goto ot15}}
    {read-write ot7}      {{span key} {goto ot15}}
    {write-only ot7}      {{span key} {goto ot15}}
    {not-accessible ot7}  {{span key} {goto ot15}}
    {* ot7}               {{span err} {goto ot15}}
    {PIB-ACCESS ot2}  {{goto ot8}}
    {PIB-ACCESS ot3}  {{goto ot8}}
    {/id ot8}  {{goto ot9}}
    {install ot9}         {{span key} {goto ot10}}
    {notify ot9}          {{span key} {goto ot10}}
    {install-notify ot9}  {{span key} {goto ot10}}
    {report-only ot9}     {{span key} {goto ot10}}
    {* ot9}               {{span err} {goto ot10}}
    {PIB-REFERENCES ot2}  {{redo ot10}}
    {PIB-REFERENCES ot3}  {{redo ot10}}
    {PIB-REFERENCES ot10}  {{push ot11} {goto lor1}}
    {PIB-TAG ot2}  {{redo ot11}}
    {PIB-TAG ot3}  {{redo ot11}}
    {PIB-TAG ot10}  {{redo ot11}}
    {PIB-TAG ot11}  {{push ot12} {goto lor1}}
    {STATUS ot2}  {{goto ot13}}
    {STATUS ot3}  {{goto ot13}}
    {STATUS ot10}  {{goto ot13}}
    {STATUS ot11}  {{goto ot13}}
    {STATUS ot12}  {{goto ot13}}
    {/id ot13}  {{goto ot14}}
    {current ot14}     {{span key} {goto ot20}}
    {obsolete ot14}    {{span key} {goto ot20}}
    {deprecated ot14}  {{span key} {goto ot20}}
    {* ot14}           {{span err} {goto ot20}}
    {STATUS ot15}  {{goto ot16}}
    {/id ot16}  {{goto ot17}}
    {mandatory ot17}   {{span key} {goto ot20}}
    {optional ot17}    {{span key} {goto ot20}}
    {obsolete ot17}    {{span key} {goto ot20}}
    {deprecated ot17}  {{span key} {goto ot20}}
    {* ot17}           {{span err} {goto ot20}}
    {DESCRIPTION ot20}  {{push ot21} {goto qs1d}}
    {INSTALL-ERRORS ot20}  {{goto ot22}}
    {INSTALL-ERRORS ot21}  {{goto ot22}}
    {lcub ot22}  {{goto ot23}}
    {/id ot23}  {{goto ot24}}
    {id ot24}   {{span id} {goto ot25}}
    {* ot24}    {{span id} {goto ot25}}
    {( ot25}  {{goto ot26}}
    {positive31 ot26}    {{goto ot27}}
    {positive32 ot26}    {{goto ot27}}
    {positive63 ot26}    {{goto ot27}}
    {positive64 ot26}    {{goto ot27}}
    {positive-big ot26}  {{goto ot27}}
    {) ot27}  {{goto ot28}}
    {rcub ot28}  {{goto ot40}}
    {, ot28}     {{goto ot29}}
    {/id ot29}  {{goto ot30}}
    {id ot30}   {{span id} {goto ot25}}
    {* ot30}    {{span id} {goto ot25}}
    {rcub ot31}  {{goto ot40}}
    {REFERENCE ot20}  {{redo ot40}}
    {REFERENCE ot21}  {{redo ot40}}
    {REFERENCE ot40}  {{push ot41} {goto qs1}}
    {PIB-INDEX ot20}  {{redo ot41}}
    {PIB-INDEX ot21}  {{redo ot41}}
    {PIB-INDEX ot40}  {{redo ot41}}
    {PIB-INDEX ot41}  {{push ot44} {goto lor1}}
    {AUGMENTS ot20}   {{redo ot41}}
    {AUGMENTS ot21}   {{redo ot41}}
    {AUGMENTS ot40}   {{redo ot41}}
    {AUGMENTS ot41}   {{push ot44} {goto lor1}}
    {EXTENDS ot20}    {{redo ot41}}
    {EXTENDS ot21}    {{redo ot41}}
    {EXTENDS ot40}    {{redo ot41}}
    {EXTENDS ot41}    {{push ot44} {goto lor1}}
    {INDEX ot20}  {{goto ot45}}
    {INDEX ot21}  {{goto ot45}}
    {INDEX ot40}  {{goto ot45}}
    {INDEX ot41}  {{goto ot45}}
    {INDEX ot44}  {{goto ot45}}
    {lcub ot45}  {{goto ot46}}
    {IMPLIED ot46}  {{goto ot47}}
    {* ot46} {{push ot48} {redo oid1}}
    {* ot47} {{push ot48} {redo oid1}}
    {rcub ot48}  {{goto ot50}}
    {, ot48}     {{goto ot46}}
    {UNIQUENESS ot20}  {{goto ot51}}
    {UNIQUENESS ot21}  {{goto ot51}}
    {UNIQUENESS ot40}  {{goto ot51}}
    {UNIQUENESS ot41}  {{goto ot51}}
    {UNIQUENESS ot44}  {{goto ot51}}
    {UNIQUENESS ot50}  {{goto ot51}}
    {lcub ot51}  {{goto ot52}}
    {rcub ot52}  {{goto ot60}}
    {* ot52} {{push ot53} {redo oid1}}
    {, ot53} {{goto ot54}}
    {rcub ot53}  {{goto ot60}}
    {* ot54} {{push ot53} {redo oid1}}
    {DEFVAL ot20}  {{redo ot60}}
    {DEFVAL ot21}  {{redo ot60}}
    {DEFVAL ot40}  {{redo ot60}}
    {DEFVAL ot41}  {{redo ot60}}
    {DEFVAL ot44}  {{redo ot60}}
    {DEFVAL ot50}  {{redo ot60}}
    {DEFVAL ot60}  {{push ot70} {goto dv1}}
    {::= ot20}  {{goto lor1d}}
    {::= ot21}  {{goto lor1d}}
    {::= ot40}  {{goto lor1d}}
    {::= ot41}  {{goto lor1d}}
    {::= ot44}  {{goto lor1d}}
    {::= ot50}  {{goto lor1d}}
    {::= ot60}  {{goto lor1d}}
    {::= ot70}  {{goto lor1d}}
    {OBJECTS nt0}  {{goto nt1}}
    {lcub nt1}  {{push nt2} {goto oid1}}
    {rcub nt2}  {{goto nt10}}
    {, nt2}     {{push nt2} {goto oid1}}
    {STATUS nt0}   {{goto nt11}}
    {STATUS nt10}  {{goto nt11}}
    {/id nt11}  {{goto nt12}}
    {current nt12}     {{span key} {goto nt20}}
    {deprecated nt12}  {{span key} {goto nt20}}
    {obsolete nt12}    {{span key} {goto nt20}}
    {* nt12}           {{span err} {goto nt20}}
    {DESCRIPTION nt20}  {{push nt30} {goto qs1d}}
    {REFERENCE nt30}  {{push nt40} {goto qs1}}
    {::= nt30}  {{goto lor1d}}
    {::= nt40}  {{goto lor1d}}
    {ENTERPRISE tt0} {{push tt10} {goto oid1}}
    {VARIABLES tt10} {{goto tt11}}
    {lcub tt11}  {{push tt12} {goto oid1}}
    {rcub tt12}  {{goto tt20}}
    {, tt12}     {{push tt12} {goto oid1}}
    {DESCRIPTION tt10}  {{redo tt20}}
    {DESCRIPTION tt20}  {{push tt30} {goto qs1d}}
    {REFERENCE tt10}  {{redo tt30}}
    {REFERENCE tt20}  {{redo tt30}}
    {REFERENCE tt30}  {{push tt40} {goto qs1}}
    {::= tt10}  {{goto tt41}}
    {::= tt20}  {{goto tt41}}
    {::= tt30}  {{goto tt41}}
    {::= tt40}  {{goto tt41}}
    {zero tt41}         {{redo m99}}
    {positive31 tt41}   {{redo m99}}
    {positive32 tt41}   {{redo m99}}
    {positive63 tt41}   {{redo m99}}
    {positive64 tt41}   {{redo m99}}
    {positive-big tt41} {{redo m99}}
    {negative31 tt41}   {{redo m99}}
    {negative63 tt41}   {{redo m99}}
    {negative-big tt41} {{redo m99}}
    {::= oi0}  {{goto lor1d}}
    {::= td0}  {{goto td1}}
    {* td1}  {{push td3} {redo sx0}}
    {/Imn td1}  {{goto td2}}
    {TEXTUAL-CONVENTION td2}  {{span rep} {goto tc0}}
    {CHOICE td1}  {{goto ch0}}
    {* td3}  {{redo m99 1}}
    {DISPLAY-HINT tc0}  {{push tc10} {goto qs1}}
    {STATUS tc0} {{goto tc11}}
    {STATUS tc10} {{goto tc11}}
    {/id tc11}  {{goto tc12}}
    {current tc12}     {{span key} {goto tc20}}
    {deprecated tc12}  {{span key} {goto tc20}}
    {obsolete tc12}    {{span key} {goto tc20}}
    {* tc12}           {{span err} {goto tc20}}
    {DESCRIPTION tc20}  {{push tc30} {goto qs1d}}
    {REFERENCE tc30}    {{push tc40} {goto qs1}}
    {SYNTAX tc30}  {{redo tc40}}
    {SYNTAX tc40}  {{push td3} {goto sx0}}
    {lcub ch0}  {{goto ch1}}
    {/id ch1}  {{span def} skip-next {goto ch2}}
    {type-ref ch2}  {{span id} {goto ch20}}
    {NULL ch2}  {{goto ch20}}
    {OBJECT ch2}  {{goto ch3}}
    {IDENTIFIER ch3} {{goto ch20}}
    {OCTET ch2}  {{goto ch4}}
    {STRING ch4}  {{push ch20} {goto sxs0}}
    {INTEGER ch2}  {{goto ch5}}
    {* ch5}  {{redo ch20}}
    {lcub ch5}  {{push ch20} {goto sxe0}}
    {( ch5}  {{goto ch6}}
    {zero ch6}  {{goto ch7}}
    {* ch6}  {{push ch20} {redo sxr1}}
    {.. ch7}  {{goto ch8}}
    {* ch7}  {{push ch20} {redo sxr1 1}}
    {MAX ch8}  {{goto ch9}}
    {* ch8}  {{push ch20} {redo sxr1 2}}
    {) ch9}  {{goto ch20}}
    {/Itn ch2}  {{span id} {goto ch10}}
    {Integer32 ch10}  {{push ch20} {goto sxr0}}
    {* ch10}  {{goto ch20}}
    {, ch20}  {{goto ch1}}
    {rcub ch20}  {{redo m99}}
    {STATUS mc0} {{goto mc1}}
    {/id mc1}  {{goto mc2}}
    {current mc2}     {{span key} {goto mc10}}
    {deprecated mc2}  {{span key} {goto mc10}}
    {obsolete mc2}    {{span key} {goto mc10}}
    {* mc2}           {{span err} {goto mc10}}
    {DESCRIPTION mc10}  {{push mc20} {goto qs1d}}
    {REFERENCE mc20}  {{push mc30} {goto qs1}}
    {MODULE mc20}  {{goto mc31}}
    {MODULE mc30}  {{goto mc31}}
    {type-ref mc31}  {{span id} {goto mc32}}
    {* mc32}  {{push mc33} {redo oid1}}
    {MANDATORY-GROUPS mc31}  {{goto mc34}}
    {MANDATORY-GROUPS mc32}  {{goto mc34}}
    {MANDATORY-GROUPS mc33}  {{goto mc34}}
    {lcub mc34}  {{push mc35} {goto oid1}}
    {rcub mc35}  {{goto mc36}}
    {, mc35}     {{push mc35} {goto oid1}}
    {GROUP mc31}  {{redo mc36}}
    {GROUP mc32}  {{redo mc36}}
    {GROUP mc33}  {{redo mc36}}
    {GROUP mc36}  {{push mc37} {goto oid1}}
    {DESCRIPTION mc37}  {{push mc36} {goto qs1d}}
    {OBJECT mc31}  {{redo mc36}}
    {OBJECT mc32}  {{redo mc36}}
    {OBJECT mc33}  {{redo mc36}}
    {OBJECT mc36}  {{push mc38} {goto oid1}}
    {SYNTAX mc38}  {{push mc39} {goto sx0}}
    {WRITE-SYNTAX mc38}  {{redo mc39}}
    {WRITE-SYNTAX mc39}  {{push mc40} {goto sx0}}
    {MIN-ACCESS mc38}  {{goto mc41}}
    {MIN-ACCESS mc39}  {{goto mc41}}
    {MIN-ACCESS mc40}  {{goto mc41}}
    {/id mc41}  {{goto mc42}}
    {not-accessible mc42}         {{span key} {goto mc45}}
    {accessible-for-notify mc42}  {{span key} {goto mc45}}
    {read-only mc42}              {{span key} {goto mc45}}
    {read-write mc42}             {{span key} {goto mc45}}
    {read-create mc42}            {{span key} {goto mc45}}
    {* mc42}                      {{span err} {goto mc45}}
    {PIB-MIN-ACCESS mc38}  {{goto mc43}}
    {PIB-MIN-ACCESS mc39}  {{goto mc43}}
    {PIB-MIN-ACCESS mc40}  {{goto mc43}}
    {/id mc43}  {{goto mc44}}
    {not-accessible mc44}  {{span key} {goto mc45}}
    {install mc44}         {{span key} {goto mc45}}
    {notify mc44}          {{span key} {goto mc45}}
    {install-notify mc44}  {{span key} {goto mc45}}
    {report-only mc44}     {{span key} {goto mc45}}
    {* mc44}               {{span err} {goto mc45}}
    {DESCRIPTION mc38}  {{redo mc45}}
    {DESCRIPTION mc39}  {{redo mc45}}
    {DESCRIPTION mc40}  {{redo mc45}}
    {DESCRIPTION mc45}  {{push mc36} {goto qs1d}}
    {MODULE mc31}  {{goto mc31}}
    {MODULE mc32}  {{goto mc31}}
    {MODULE mc33}  {{goto mc31}}
    {MODULE mc36}  {{goto mc31}}
    {::= mc31}  {{goto lor1d}}
    {::= mc32}  {{goto lor1d}}
    {::= mc33}  {{goto lor1d}}
    {::= mc36}  {{goto lor1d}}
    {OBJECTS og0}  {{goto og1}}
    {lcub og1}  {{push og2} {goto oid1}}
    {rcub og2}  {{goto og10}}
    {, og2}     {{push og2} {goto oid1}}
    {STATUS og10}  {{goto og11}}
    {/id og11}  {{goto og12}}
    {current og12}     {{span key} {goto og20}}
    {deprecated og12}  {{span key} {goto og20}}
    {obsolete og12}    {{span key} {goto og20}}
    {* og12}           {{span err} {goto og20}}
    {DESCRIPTION og20}  {{push og30} {goto qs1d}}
    {REFERENCE og30}  {{push og40} {goto qs1}}
    {::= og30}  {{goto lor1d}}
    {::= og40}  {{goto lor1d}}
    {NOTIFICATIONS ng0}  {{goto ng1}}
    {lcub ng1}  {{push ng2} {goto oid1}}
    {rcub ng2}  {{goto ng10}}
    {, ng2}     {{push ng2} {goto oid1}}
    {STATUS ng10}  {{goto ng11}}
    {/id ng11}  {{goto ng12}}
    {current ng12}     {{span key} {goto ng20}}
    {deprecated ng12}  {{span key} {goto ng20}}
    {obsolete ng12}    {{span key} {goto ng20}}
    {* ng12}           {{span err} {goto ng20}}
    {DESCRIPTION ng20}  {{push ng30} {goto qs1d}}
    {REFERENCE ng30}  {{push ng40} {goto qs1}}
    {::= ng30}  {{goto lor1d}}
    {::= ng40}  {{goto lor1d}}
    {PRODUCT-RELEASE ac0}  {{push ac10} {goto qs1}}
    {STATUS ac10}  {{goto ac11}}
    {/id ac11}  {{goto ac12}}
    {current ac12}   {{span key} {goto ac20}}
    {obsolete ac12}  {{span key} {goto ac20}}
    {* ac12}         {{span err} {goto ac20}}
    {DESCRIPTION ac20}  {{push ac30} {goto qs1d}}
    {REFERENCE ac30}  {{push ac40} {goto qs1}}
    {SUPPORTS ac30} {{goto ac41}}
    {SUPPORTS ac40} {{goto ac41}}
    {type-ref ac41} {{span id} {goto ac42}}
    {* ac42}  {{push ac43} {redo oid1}}
    {INCLUDES ac42} {{goto ac44}}
    {INCLUDES ac43} {{goto ac44}}
    {lcub ac44}  {{push ac45} {goto oid1}}
    {rcub ac45}  {{goto ac50}}
    {, ac45}     {{push ac45} {goto oid1}}
    {SUPPORTS ac50} {{goto ac41}}
    {VARIATION ac50} {{push ac51} {goto oid1}}
    {SYNTAX ac51} {{push ac52} {goto sx0}}
    {WRITE-SYNTAX ac51} {{redo ac52}}
    {WRITE-SYNTAX ac52} {{push ac53} {goto sx0}}
    {ACCESS ac51}  {{goto ac54}}
    {ACCESS ac52}  {{goto ac54}}
    {ACCESS ac53}  {{goto ac54}}
    {/id ac54}  {{goto ac55}}
    {not-implemented ac55}  {{span key} {goto ac56}}
    {accessible-for-notify ac55}  {{span key} {goto ac56}}
    {read-only ac55}    {{span key} {goto ac56}}
    {read-write ac55}   {{span key} {goto ac56}}
    {read-create ac55}  {{span key} {goto ac56}}
    {write-only ac55}   {{span key} {goto ac56}}
    {* ac55}            {{span err} {goto ac56}}
    {CREATION-REQUIRES ac51}  {{goto ac57}}
    {CREATION-REQUIRES ac52}  {{goto ac57}}
    {CREATION-REQUIRES ac53}  {{goto ac57}}
    {CREATION-REQUIRES ac56}  {{goto ac57}}
    {lcub ac57}  {{push ac58} {goto oid1}}
    {rcub ac58}  {{goto ac59}}
    {, ac58}     {{push ac58} {goto oid1}}
    {DEFVAL ac51}  {{redo ac59}}
    {DEFVAL ac52}  {{redo ac59}}
    {DEFVAL ac53}  {{redo ac59}}
    {DEFVAL ac56}  {{redo ac59}}
    {DEFVAL ac59}  {{push ac60} {goto dv1}}
    {DESCRIPTION ac51}  {{redo ac60}}
    {DESCRIPTION ac52}  {{redo ac60}}
    {DESCRIPTION ac53}  {{redo ac60}}
    {DESCRIPTION ac56}  {{redo ac60}}
    {DESCRIPTION ac59}  {{redo ac60}}
    {DESCRIPTION ac60}  {{push ac50} {goto qs1d}}
    {::= ac50}  {{goto lor1d}}
    {lcub dv1}  {{goto dv2}}
    {lcub dv1}  {{goto dv2}}
    {radix-string dv2}  {{goto dv19}}
    {zero dv2}          {{goto dv19}}
    {positive31 dv2}    {{goto dv19}}
    {positive32 dv2}    {{goto dv19}}
    {positive63 dv2}    {{goto dv19}}
    {positive64 dv2}    {{goto dv19}}
    {positive-big dv2}  {{goto dv19}}
    {negative31 dv2}    {{goto dv19}}
    {negative63 dv2}    {{goto dv19}}
    {negative-big dv2}  {{goto dv19}}
    {quot dv2}  {{push dv19} {goto qs2}}
    {/id dv2}   {{span id} skip-next {goto dv19}}
    {lcub dv2}  {{goto dv3}}
    {rcub dv3}  {{goto dv19}}
    {/id dv3}  {{span id} skip-next {goto dv4}}
    {rcub dv4}  {{goto dv19}}
    {, dv4}  {{goto dv5}}
    {/id dv5}  {{span id} skip-next {goto dv6}}
    {rcub dv6}  {{goto dv19}}
    {, dv6}  {{goto dv5}}
    {( dv4}  {{goto dv7}}
    {zero dv7}        {{goto dv8}}
    {positive31 dv7}  {{goto dv8}}
    {positive32 dv7}  {{goto dv8}}
    {) dv8}  {{goto dv9}}
    {zero dv3}        {{goto dv9}}
    {positive31 dv3}  {{goto dv9}}
    {positive32 dv3}  {{goto dv9}}
    {rcub dv9}  {{goto dv19}}
    {/id dv9}  {{span id} skip-next {goto dv10}}
    {( dv10}  {{goto dv11}}
    {zero dv11}        {{goto dv12}}
    {positive31 dv11}  {{goto dv12}}
    {positive32 dv11}  {{goto dv12}}
    {) dv12}  {{goto dv9}}
    {zero dv9}        {{goto dv9}}
    {positive31 dv9}  {{goto dv9}}
    {positive32 dv9}  {{goto dv9}}
    {rcub dv19}  {goto-top pop}
    {BITS sx0}  {{goto sx1}}
    {lcub sx1}  {{goto sx2}}
    {/id sx2}  {{span def} skip-next {goto sx3}}
    {( sx3}  {{goto sx4}}
    {zero sx4}          {{goto sx5}}
    {positive31 sx4}    {{goto sx5}}
    {positive32 sx4}    {{goto sx5}}
    {positive63 sx4}    {{goto sx5}}
    {positive64 sx4}    {{goto sx5}}
    {positive-big sx4}  {{goto sx5}}
    {) sx5}  {{goto sx6}}
    {, sx6}  {{goto sx2}}
    {rcub sx6}  {goto-top pop}
    {type-ref sx0}  {{span id} {goto sx7}}
    {. sx7}  {{redo sx32}}
    {( sx7}  {{redo sx32}}
    {lcub sx7}  {{redo sx32}}
    {* sx7}  {redo goto-top pop}
    {SEQUENCE sx0}  {{goto sx10}}
    {OF sx10}  {{goto sx11}}
    {type-ref sx11}  {{span id} goto-top pop}
    {lcub sx10}  {{goto sx12}}
    {/id sx12}  {{span id} skip-next {goto sx13}}
    {INTEGER sx13}  {{goto sx16}}
    {BITS sx13}  {{goto sx16}}
    {OCTET sx13}  {{goto sx14}}
    {STRING sx14}  {{goto sx16}}
    {OBJECT sx13}  {{goto sx15}}
    {IDENTIFIER sx15}  {{goto sx16}}
    {type-ref sx13}  {{span id} {goto sx16}}
    {/Itn sx13}  {{span id} skip-next {goto sx16}}
    {, sx16}  {{goto sx12}}
    {rcub sx16}  {goto-top pop}
    {* sx16}  {{push sx18} {redo sxn0}}
    {* sx17}  {{span-top err} pop {goto sx18}}
    {, sx18}  {{goto sx12}}
    {rcub sx18}  {goto-top pop}
    {lsqb sx0}  {{goto sx20}}
    {APPLICATION sx20}  {{goto sx21}}
    {zero sx21}          {{goto sx22}}
    {positive31 sx21}    {{goto sx22}}
    {positive32 sx21}    {{goto sx22}}
    {positive63 sx21}    {{goto sx22}}
    {positive64 sx21}    {{goto sx22}}
    {positive-big sx21}  {{goto sx22}}
    {rsqb sx22}  {{goto sx23}}
    {IMPLICIT sx23}  {{goto sx30}}
    {/Itn sx0}  {{goto sx25}}
    {Integer32 sx25}  {{span id} {push sx38} {goto sxr0}}
    {TimeTicks sx25}   {{span id} goto-top pop}
    {IpAddress sx25}   {{span id} {push sx26} {goto sxa0}}
    {Counter32 sx25}   {{span id} {push sx26} {goto sxa0}}
    {Counter64 sx25}   {{span id} {push sx26} {goto sxa0}}
    {Gauge32 sx25}     {{span id} {push sx26} {goto sxr0}}
    {Integer64 sx25}   {{span id} {push sx26} {goto sxr0}}
    {Unsigned32 sx25}  {{span id} {push sx26} {goto sxr0}}
    {Unsigned64 sx25}  {{span id} {push sx26} {goto sxr0}}
    {Opaque sx25}      {{span id} {push sx26} {goto sxs0}}
    {* sx26}  {redo goto-top pop}
    {* sx0}  {{redo sx30}}
    {INTEGER sx30}  {{push sx38} {goto sxre0}}
    {/Itn sx30}  {{goto sx31}}
    {Integer32 sx31}  {{span id} {push sx38} {goto sxr0}}
    {OCTET sx30}  {{goto sx35}}
    {OBJECT sx30}  {{goto sx36}}
    {type-ref sx30}  {{span id} {goto sx32}}
    {. sx32}  {{goto sx33}}
    {( sx32}  {{push sx38} {goto sxa1}}
    {lcub sx32}  {{push sx38} {redo sxe0}}
    {type-ref sx33}  {{span id} {goto sx34}}
    {( sx34}  {{push sx38} {goto sxa1}}
    {lcub sx34}  {{push sx38} {redo sxe0}}
    {STRING sx35}  {{push sx38} {goto sxs0}}
    {IDENTIFIER sx36}  {{push sx38} {goto sxa0}}
    {* sx38}  {redo goto-top pop}
    {( sxr0}  {{goto sxr1}}
    {SIZE sxr1}  {{push sxx9} {redo sx81}}
    {* sxr1}  {{push sxr2} {redo sx71}}
    {) sxr2}  {pop goto-top pop}
    {lcub sxr0}  {{push sxx9} {goto sx91}}
    {* sxr0}  {redo goto-top pop}
    {( sxs0}  {{goto sxs1}}
    {SIZE sxs1}  {{push sxs2} {redo sx81}}
    {* sxs1}  {{push sxx9} {redo sx71}}
    {) sxs2}  {pop goto-top pop}
    {lcub sxs0}  {{push sxx9} {goto sx91}}
    {* sxs0}  {redo goto-top pop}
    {( sxe0}  {{goto sxe1}}
    {SIZE sxe1}  {{push sxx9} {redo sx81}}
    {* sxe1}  {{push sxx9} {redo sx71}}
    {lcub sxe0}  {{push sxe2} {goto sx91}}
    {rcub sxe2}  {pop goto-top pop}
    {* sxe0}  {redo goto-top pop}
    {( sxa0}  {{goto sxa1}}
    {SIZE sxa1}  {{push sxs2} {redo sx81}}
    {* sxa1}  {{push sxr2} {redo sx71}}
    {lcub sxa0}  {{push sxe2} {goto sx91}}
    {* sxa0}  {redo goto-top pop}
    {( sxn0}  {{goto sxn1}}
    {SIZE sxn1}  {{push sxx9} {redo sx81}}
    {* sxn1}  {{push sxx9} {redo sx71}}
    {lcub sxn0}  {{push sxx9} {goto sx91}}
    {* sxn0}  {redo goto-top pop}
    {( sxre0}  {{goto sxre1}}
    {SIZE sxre1}  {{push sxx9} {redo sx81}}
    {* sxre1}  {{push sxr2} {redo sx71}}
    {lcub sxre0}  {{push sxe2} {goto sx91}}
    {* sxre0}  {redo goto-top pop}
    {* sxx9}  {pop {span-top err} goto-top pop}
    {( sx70}  {{goto sx71}}
    {radix-string sx71}  {{goto sx72}}
    {zero sx71}          {{goto sx72}}
    {positive31 sx71}    {{goto sx72}}
    {positive32 sx71}    {{goto sx72}}
    {positive63 sx71}    {{goto sx72}}
    {positive64 sx71}    {{goto sx72}}
    {positive-big sx71}  {{goto sx72}}
    {negative31 sx71}    {{goto sx72}}
    {negative63 sx71}    {{goto sx72}}
    {negative-big sx71}  {{goto sx72}}
    {| sx72}  {{goto sx71}}
    {) sx72}  {redo goto-top}
    {.. sx72}  {{goto sx73}}
    {radix-string sx73}  {{goto sx74}}
    {zero sx73}          {{goto sx74}}
    {positive31 sx73}    {{goto sx74}}
    {positive32 sx73}    {{goto sx74}}
    {positive63 sx73}    {{goto sx74}}
    {positive64 sx73}    {{goto sx74}}
    {positive-big sx73}  {{goto sx74}}
    {negative31 sx73}    {{goto sx74}}
    {negative63 sx73}    {{goto sx74}}
    {negative-big sx73}  {{goto sx74}}
    {| sx74}  {{goto sx71}}
    {) sx74}  {redo goto-top}
    {( sx80}  {{goto sx81}}
    {SIZE sx81}  {{push sx82} {goto sx70}}
    {) sx82}  {pop {goto sx83}}
    {) sx83}  {redo goto-top}
    {lcub sx90}  {{goto sx91}}
    {/id sx91}  {{span def} skip-next {goto sx92}}
    {( sx92}  {{goto sx93}}
    {zero sx93}          {{goto sx94}}
    {positive31 sx93}    {{goto sx94}}
    {positive32 sx93}    {{goto sx94}}
    {positive63 sx93}    {{goto sx94}}
    {positive64 sx93}    {{goto sx94}}
    {positive-big sx93}  {{goto sx94}}
    {negative31 sx93}    {{goto sx94}}
    {negative63 sx93}    {{goto sx94}}
    {negative-big sx93}  {{goto sx94}}
    {) sx94}  {{goto sx95}}
    {, sx95}  {{goto sx91}}
    {rcub sx95}  {redo goto-top}
    {MACRO mac0}  {{goto mac1}}
    {::= mac1}  {{goto mac2}}
    {BEGIN mac2}  {{goto mac3}}
    {TYPE mac3}  {{goto mac4}}
    {NOTATION mac4}  {{goto mac5}}
    {::= mac5}  {{goto mac10}}
    {type-ref mac10}  {{span id} {goto mac30}}
    {quot mac10}  {{push mac30} {goto qs2}}
    {/id mac10}  {{goto mac11}}
    {type mac11}  {{span key} {goto mac12}}
    {( mac12}  {{goto mac13}}
    {TYPE mac13}  {{goto mac14}}
    {type-ref mac13}  {{span id} {goto mac15}}
    {type-ref mac14}  {{span id} {goto mac15}}
    {) mac15}  {{goto mac30}}
    {value mac11}  {{span key} {goto mac20}}
    {( mac20}  {{goto mac22}}
    {Update mac22}  {{goto mac23}}
    {type-ref mac23}  {{span id} {goto mac29}}
    {/id mac22}  {{span id} skip-next {goto mac24}}
    {OBJECT mac24}  {{goto mac25}}
    {IDENTIFIER mac25}  {{goto mac29}}
    {) mac29}  {{goto mac30}}
    {type-ref mac30}  {{span id} {goto mac30}}
    {quot mac30}  {{push mac30} {goto qs2}}
    {/id mac30}  {{goto mac11}}
    {VALUE mac30}  {{goto mac31}}
    {NOTATION mac31} {{goto mac32}}
    {::= mac32}  {{goto mac33}}
    {/id mac33}  {{goto mac34}}
    {value mac34}  {{span key} {goto mac35}}
    {( mac35}  {{goto mac36}}
    {VALUE mac36}  {{goto mac37}}
    {OBJECT mac37}  {{goto mac38}}
    {IDENTIFIER mac38} {{goto mac39}}
    {INTEGER mac37}  {{goto mac39}}
    {type-ref mac37}  {{span id} {goto mac39}}
    {) mac39}  {{goto mac40}}
    {END mac40}  {{redo mac60}}
    {type-ref-macsyn mac40}  {{span def} {goto mac41}}
    {::= mac41}  {{goto mac50}}
    {type-ref mac50}  {{span id} {goto mac60}}
    {quot mac50}  {{push mac60} {goto qs2}}
    {/id mac50}  {{goto mac51}}
    {* mac51}  {{span id} {goto mac60}}
    {type mac51}  {{span key} {goto mac52}}
    {* mac52}  {{redo mac60}}
    {( mac52}  {{goto mac53}}
    {/id mac53}  {{span id} skip-next {goto mac59}}
    {value mac51}  {{span key} {goto mac55}}
    {( mac55}  {{goto mac56}}
    {OBJECT mac56}  {{goto mac57}}
    {IDENTIFIER mac57}  {{goto mac59}}
    {IA5String mac56}  {{goto mac59}}
    {type-ref mac56}  {{span id} {goto mac59}}
    {Update mac56}  {{goto mac58}}
    {type-ref mac58}  {{span id} {goto mac59}}
    {/id mac56}  {{span id} skip-next {goto mac58}}
    {) mac59}  {{goto mac60}}
    {* mac60}  {{redo mac50}}
    {| mac60}  {{goto mac50}}
    {type-ref-macsyn mac60}  {{redo mac40}}
    {END mac60}  {{redo m99}}
    {lcub lor1}  {{push lor2} {goto oid1}}
    {rcub lor2}  {goto-top pop}
    {lcub lor1d}  {{push lor2d} {goto oid1}}
    {rcub lor2d}  {{redo m99}}
    {zero oid1}        {{goto oid2}}
    {positive31 oid1}  {{goto oid2}}
    {positive32 oid1}  {{goto oid2}}
    {/id oid1}  {{span id} skip-next {goto oid3}}
    {type-ref oid1}  {{goto oid6}}
    {, oid2}  {redo goto-top pop}
    {rcub oid2}  {redo goto-top pop}
    {* oid2}  {redo goto-top pop}
    {zero oid2}        {}
    {positive31 oid2}  {}
    {positive32 oid2}  {}
    {/id oid2}  {{span id} skip-next {goto oid3}}
    {type-ref oid2}  {{goto oid6}}
    {, oid3}  {redo goto-top pop}
    {rcub oid3}  {redo goto-top pop}
    {zero oid3}        {{goto oid2}}
    {positive31 oid3}  {{goto oid2}}
    {positive32 oid3}  {{goto oid2}}
    {* oid3}  {{redo oid2}}
    {( oid3}  {{goto oid4}}
    {zero oid4}        {{goto oid5}}
    {positive31 oid4}  {{goto oid5}}
    {positive32 oid4}  {{goto oid5}}
    {) oid5}  {{goto oid2}}
    {. oid6}  {{redo oid7 1}}
    {* oid6}  {{redo oid9 1}}
    {type-ref oid7}  {{span id} skip-next {goto oid8}}
    {/id oid8}  {{span id} skip-next {goto oid3}}
    {type-ref oid9}  {{span err} {goto oid2}}
    {quot qs1}  {{goto qs2}}
    {qstr qs2}  {{span str}}
    {quot qs2}  {goto-top pop}
    {quot qs1x}  {{goto qs2x}}
    {qstr qs2x}  {{span str}}
    {quot qs2x}  {goto-top}
    {quot qs1d}  {{goto qs2d}}
    {qstr qs2d}  {{span str}}
    {quot qs2d}  {div-top goto-top pop}
    {quot qs1dd}  {{goto qs2dd}}
    {qstr qs2dd}  {{span str}}
    {quot qs2dd}  {div-top goto-top pop div-top pop}
}
#               }}}4 artwork::grammar(mib)
#           }}}3 mib
#       }}}2 grammars
#   }}}1 artwork content processing
#   {{{1 xdv validator
# pity i didn't build this into xml2rfc initially,
# because integrating properly would be a lot of work...
#       {{{2 namespace
namespace eval xdv {
    variable dtd
    # This ::xdv::lineno is 0-based.
    variable lineno -1
    catch { array unset dtd }
}
#       }}}2 namespace
#       {{{2 rfc2629 DTD
# Strict content model does not allow section in back...
set xdv::dtd(rfc2629.cmodel) \
    [list rfc           [list front             ""   \
                              middle            ""   \
                              back              "?"] \
          front         [list title             ""   \
                              author            "+"  \
                              date              ""   \
                              area              "*"  \
                              workgroup         "*"  \
                              keyword           "*"  \
                              abstract          "?"  \
                              note              "*"] \
          middle        [list section           "+"  \
                              appendix          "*"  \
                              section           "*"] \
          back          [list references        "*"  \
                              section           "*"] \
          title         {}                           \
          author        [list organization      "?"   \
                              address           "*"] \
          organization  {}                           \
          address       [list postal            "?"  \
                              phone             "?"  \
                              facsimile         "?"  \
                              email             "?"  \
                              uri               "?"] \
          postal        [list street            "+"  \
                              [list city             \
                                    region           \
                                    code             \
                                    country]    *]   \
          street        {}                           \
          city          {}                           \
          region        {}                           \
          code          {}                           \
          country       {}                           \
          phone         {}                           \
          facsimile     {}                           \
          email         {}                           \
          uri           {}                           \
          date          {}                           \
          area          {}                           \
          workgroup     {}                           \
          keyword       {}                           \
          abstract      [list t                 "+"] \
          note          [list t                 "+"] \
          section       [list [list t                \
                                    figure           \
                                    texttable        \
                                    iref]       "*"  \
                                    section     "*"] \
          appendix      [list [list t                \
                                    figure           \
                                    texttable        \
                                    iref]       "*"  \
                                    appendix    "*"] \
          t             [list [list list             \
                                    figure           \
                                    xref             \
                                    eref             \
                                    iref             \
                                    cref             \
                                    vspace           \
                                    spanx]      "*"] \
          list          [list t                 "+"] \
          xref          {}                           \
          eref          {}                           \
          iref          {}                           \
          cref          {}                           \
          vspace        {}                           \
          spanx         {}                           \
          figure        [list iref              "*"  \
                              preamble          "?"  \
                              artwork           ""   \
                              postamble         "?"] \
          preamble      [list [list xref             \
                                    eref             \
                                    iref             \
                                    cref             \
                                    spanx]      "*"] \
          artwork       {}                           \
          postamble     [list [list xref             \
                                    eref             \
                                    iref             \
                                    cref             \
                                    spanx]      "*"] \
          texttable     [list preamble          "?"  \
                              ttcol             "+"  \
                              c                 "*"  \
                              postamble         "?"] \
          ttcol         {}                           \
          c             [list [list xref             \
                                    eref             \
                                    iref             \
                                    cref             \
                                    spanx]      "*"] \
          references    [list reference         "+"] \
          reference     [list front             ""   \
                              seriesInfo        "*"  \
                              format            "*"  \
                              annotation        "*"] \
          seriesInfo    {}                           \
          format        {}                           \
          annotation    [list [list xref             \
                                    eref             \
                                    iref             \
                                    cref             \
                                    spanx]      "*"]]
set xdv::dtd(rfc2629.pcdata) \
    [list annotation   \
          area         \
          artwork      \
          c            \
          city         \
          code         \
          country      \
          cref         \
          email        \
          eref         \
          facsimile    \
          keyword      \
          organization \
          phone        \
          postamble    \
          preamble     \
          region       \
          spanx        \
          street       \
          t            \
          ttcol        \
          title        \
          uri          \
          workgroup    \
          xref]
set xdv::dtd(rfc2629.rattrs) \
    [list note          [list title]  \
          section       [list title]  \
          appendix      [list title]  \
          xref          [list target] \
          eref          [list target] \
          iref          [list item]   \
          seriesInfo    [list name    \
                              value]  \
          format        [list type]]
set xdv::dtd(rfc2629.oattrs) \
    [list rfc           [list number      \
                              obsoletes   \
                              updates     \
                              category    \
                              seriesNo    \
                              ipr         \
                              iprExtract  \
                              submissionType \
                              docName     \
                              xml:lang]   \
          title         [list abbrev]     \
          author        [list initials    \
                              surname     \
                              fullname    \
                              role]       \
          organization  [list abbrev]     \
          date          [list day         \
                              month       \
                              year]       \
          section       [list anchor      \
                              toc]        \
          appendix      [list anchor      \
                              toc]        \
          t             [list anchor      \
                              hangText]   \
          list          [list style       \
                              hangIndent  \
                              counter]    \
          xref          [list pageno      \
                              format]     \
          iref          [list subitem     \
                              primary]    \
          cref          [list anchor      \
                              source]     \
          spanx         [list xml:space   \
                              style]      \
          vspace        [list blankLines] \
          figure        [list anchor      \
                              title       \
                              suppress-title \
                              src         \
                              align       \
                              alt         \
                              width       \
                              height]     \
          artwork       [list xml:space   \
                              name        \
                              type        \
                              src         \
                              align       \
                              alt         \
                              width       \
                              height]     \
          texttable     [list anchor      \
                              title       \
                              suppress-title \
                              align       \
                              style]      \
          ttcol         [list width       \
                              align]      \
          references    [list title]      \
          reference     [list anchor      \
                              target]     \
          seriesInfo    [list name        \
                              value]      \
          format        [list target      \
                              octets]]  \
set xdv::dtd(rfc2629.anchors) \
    [list anchor]
#       }}}2 rfc2629 DTD
#       {{{2 procs
proc xdv::validate_tree {root CM RA OA AN PC} {
    variable anchorX {}
    validate_tree_aux $root $CM $RA $OA $AN $PC {}
}
proc xdv::validate_tree_aux {parent CM RA OA AN PC stack} {
    variable anchorX
    variable dtd
    set name [lindex $parent 0]
    array set attrs [lindex $parent 1]
    set children [lrange $parent 2 end]
    lappend stack [list $name [array get attrs]]
    array set cmodel $dtd($CM)
    if {![info exists cmodel($name)]} {
        report "not expecting <$name> element" $stack
    }
    array set required $dtd($RA)
    if {[info exists required($name)]} {
        foreach k [set expected $required($name)] {
            if {![info exists attrs($k)]} {
                report "missing $k attribute in <$name> element" $stack
            }
        }
    } else {
        set expected {}
    }
    array set optional $dtd($OA)
    if {[catch { set optional($name) } possible]} {
        set possible {}
    }
    foreach k [array names attrs] {
        if {([string first . $k] < 0) \
                && ([lsearch -exact $expected $k] < 0) \
                && ([lsearch -exact $possible $k] < 0)} {
            report "unexpected $k attribute in <$name> element" $stack
        }
    }
    foreach {k v} [array get attrs] {
        if {[lsearch -exact $dtd($AN) $name/$k] >= 0} {
            if {[lsearch -exact $anchorX $v] >= 0} {
                report "duplicate anchor '$v'" $stack
            }
            lappend anchorX $v
        }
    }
    if {([info exists attrs(.pcdata)]) \
            && ([lsearch $dtd($PC) $name] < 0)} {
        report "not expecting pcdata in <$name> element" $stack
    }
    if {[catch { validate_cmodel $children $cmodel($name) } result]} {
        # The $stack list will have been upvar-appended on error.
        report $result $stack
    }
    foreach child $children {
        validate_tree_aux $child $CM $RA $OA $AN $PC $stack
    }
}
proc xdv::validate_cmodel {children cmodel} {
    # Uses uplevel proc xdv::shift_cmodel.
    # Uses uplevel proc xdv::xmerge.
    upvar name n
    set err "with content model {$cmodel} for <$n>"
    shift_cmodel
    set seen {}
    set expected {}
    foreach child $children {
        set e [lindex $child 0]
        while {1} {
            if {[lsearch -exact $elems $e] >= 0} {
                set expected {}
                switch -- $quant {
                    +      { set quant "*" }
                    ? - "" { shift_cmodel }
                }
            } else {
                switch -- $quant {
                    ? - * {
                        xmerge
                        shift_cmodel
                        continue
                    }
                    default {
                        upvar stack s
                        lappend s [list $e [lindex $child 1]]
                        append err ", seen {$seen} so far, now expecting "
                        switch -- [llength $elems] {
                            0       { lappend expected "</$n>" }
                            default { xmerge }
                        }
                        append err [or_list $expected]
                        error "$err, but not <$e>"
                    }
                }
            }
            break
        }
        lappend seen "$e"
    }
    switch -- $quant {
        ? - *   {}
        default {
            if {[llength $elems] > 0} {
                set err0 "seen {$seen} so far, first expecting "
                xmerge
                append err0 [or_list $expected]
                error "$err0 but got </$n>, $err"
            }
        }
    }
}
proc xdv::shift_cmodel {} {
    uplevel 1 {
        set elems  [lindex $cmodel 0]
        set quant  [lindex $cmodel 1]
        set cmodel [lrange $cmodel 2 end]
    }
}
proc xdv::xmerge {} {
    uplevel 1 {
        foreach x $elems {
            set y "<$x>"
            if {[lsearch -exact $expected $y] < 0} {
                lappend expected $y
            }
        }
    }
}
proc xdv::or_list {items} {
    set t ""
    set s ""
    set i 1
    set n [llength $items]
    foreach e $items {
        append t $s$e
        if {[incr i] == $n} {
            if {$n > 2} {
                set s ", or "
            } else {
                set s " or "
            }
        } else {
            set s ", "
        }
    }
    return $t
}
proc xdv::report {result stack} {
    global options
    if {[set i [llength $stack]] > 0} {
        array set attrs [lindex [lindex $stack end] 1]
        if {[info exists attrs(.lineno)]} {
            append result " around line $attrs(.lineno)"
        }
        # only report stack if fatal.
        if {$options(.STRICT)} {
            set text "Syntax:"
            while {$i > 0} {
                set frame [lindex $stack [incr i -1]]
                array set attrs [lindex $frame 1]
                append text "\n    "
                if {[info exists attrs(.lineno)]} {
                    append text [expr $attrs(.lineno) + 1]:
                }
                append text <[lindex $frame 0]
                foreach {k v} [lindex $frame 1] {
                    if {[string first . $k] < 0} {
                        regsub -all -- \" $v {\"} v
                        append text " $k=\"$v\""
                    }
                }
                append text ">"
            }
            append result "\n\n$text"
        }
    }
    unexpected [unex_condtype] $result
}
#       }}}2 procs
#   }}}1 xdv validator
#   {{{1 tclsh/wish linkage
global guiP
if {[info exists guiP]} {
    return
}
set guiP 0
if {[llength $argv] > 1} {
    if {[catch {
        check_vrsn
        switch -- [llength $argv] {
            2 {
                set file [lindex $argv 1]
                if {![string compare $tcl_platform(platform) \
                             windows]} {
                    set f ""
                    foreach c [split $file ""] {
                        switch -- $c {
                            "\\"    { append f "\\\\" }
                            "\a"    { append f "\\a"  }
                            "\b"    { append f "\\b"  }
                            "\f"    { append f "\\f"  }
                            "\n"    { append f "\\n"  }
                            "\r"    { append f "\\r"  }
                            "\v"    { append f "\\v"  }
                            default { append f $c     }
                        }
                    }
                    set file $f
                }
                eval [file tail [file rootname [lindex $argv 0]]] \
                           $file
            }
            3 { xml2rfc [lindex $argv 1] [lindex $argv 2] }
        }
        check_vrsn_idle
    } result]} {
        if {![catch {package require Tk}]} {
            catch { wm geometry . 10x10+-100+-100 }
            catch { wm withdraw . }
            bgerror $result
        } else {
            puts stderr "$prog: error: $result"
        }
        exit 1
    }
    exit 0
} elseif {[catch {package require Tk}]} {
    set guiP -1
    #puts stdout ""
    puts stdout "invoke as \"xml2rfc   input-file output-file\""
    puts stdout "       or \"xml2txt   input-file\""
    puts stdout "       or \"xml2html  input-file\""
    puts stdout "       or \"xml2nroff input-file\""
    puts stdout "       or \"xml2unpg  input-file\""
} else {
    set guiP 1
    proc convert {w} {
        global prog
        global tcl_platform
        if {![string compare [set input [.input.ent get]] ""]} {
            tk_dialog .error "$prog: oops!" "no input file-name specified" \
                      error 0 OK
            return
        }
        set output [.output.ent get]
        if {[catch { xml2rfc $input $output } result]} {
            tk_dialog .error "$prog: oops!" $result error 0 OK
        } elseif {![string compare $tcl_platform(platform) windows]} {
            tk_dialog .ok xml2rfc "Finished." "" 0 OK
        }
    }
    proc fileDialog {w ent operation} {
        global tcl_platform
        # tcl_platform(platform) tcl_platform(os) windowingsystem tk_getSaveFile
        # ---------------------- ---------------- --------------- --------------
        # dos                    ""               ?               ?
        # macintosh              MacOS            classic         native
        # unix                   Darwin           aqua            native
        # unix                   Darwin           x11             proc
        # unix                   `uname -s`       x11             proc
        # windows                Win32s           win32           native
        # windows                Windows 95       win32           native
        # windows                Windows NT       win32           native
        # windows                Windows CE       win32           native
        # However [tk windowingsystem] did not exist before 8.4.
        if {![catch {set winsys [tk windowingsystem]}]} {
            set ext [expr    ![string compare $winsys classic] \
                          || ![string compare $winsys aqua]    ]
        } else {
            set ext [expr    [catch {info body tk_getSaveFile}              ] \
                          && [string compare $tcl_platform(platform) windows] ]
        }
        switch -- $tcl_platform(platform) {
            windows { set dx .txt }
            default { set dx ""   }
        }
        set in_types {
            {"XML files"               .xml  }
            {"All files"               *     }
        }
        set out_types {
            {"TeXT files"              .txt  }
            {"HTML files"              .html }
            {"NRoff files"             .nr   }
            {"UNPaGinated text files"  .unpg }
            {"XML files"               .xml  }
        }
        if {![string compare $operation "input"]} {
            set file [tk_getOpenFile -filetypes $in_types -parent $w]
        } else {
            if {   ![catch { set browse [.output.ent get] }]
                &&  [string compare $browse ""]} {
                if {!$ext} {
                    set browse [file rootname $browse]
                }
            } else {
                if {   ![catch { set browse [.input.ent get] }]
                    &&  [string compare $browse ""]} {
                    set browse [file rootname $browse]
                } else {
                    set browse Untitled
                }
                if {$ext} {
                    append browse ".txt"
                }
            }
            set file [tk_getSaveFile -filetypes $out_types -parent $w    \
                                     -initialdir  [file dirname $browse] \
                                     -initialfile [file tail    $browse] \
                                     -defaultextension $dx               ]
        }
        if [string compare $file ""] {
            $ent delete 0 end
            $ent insert 0 $file
            $ent xview end
            if {   ![string compare $operation "input"]
                && (    [catch { set browse [.output.ent get] }]
                    || ![string compare $browse ""])} {
                catch {
                    .output.ent insert 0 [file rootname $file].txt
                    .output.ent xview end
                }
            }
        }
    }
    eval destroy [winfo child .]
    wm title . $prog
    wm iconname . $prog
    wm geometry . +300+300
    label .msg -font "Helvetica 14" -wraplength 4i -justify left \
          -text "Convert XML to RFC"
    pack .msg -side top
    frame .buttons
    pack .buttons -side bottom -fill x -pady 2m
    pack \
        [button .buttons.code -text Convert -command "convert ."] \
        [button .buttons.dismiss -text Quit -command "destroy ."] \
        -side left -expand 1
    foreach i {input output} {
        set f [frame .$i]
        label $f.lab -text "Select $i file: " -anchor e -width 20
        entry $f.ent -width 20
        button $f.but -text "Browse ..." -command "fileDialog . $f.ent $i"
        pack $f.lab -side left
        pack $f.ent -side left -expand yes -fill x
        pack $f.but -side left
        pack $f -fill x -padx 1c -pady 3
    }
    check_vrsn
}
#   }}}1 tclsh/wish linkage
# vi: set sw=4 et si sta fdm=marker:
 
     |