test_driver.cc 134 KB
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
#include <qpdf/assert_test.h>

// This program tests miscellaneous functionality in the qpdf library
// that we don't want to pollute the qpdf program with.

#include <qpdf/QPDF.hh>

#include <qpdf/BufferInputSource.hh>
#include <qpdf/Pl_Buffer.hh>
#include <qpdf/Pl_Discard.hh>
#include <qpdf/Pl_Flate.hh>
#include <qpdf/Pl_StdioFile.hh>
#include <qpdf/Pl_String.hh>
#include <qpdf/QIntC.hh>
#include <qpdf/QPDFAcroFormDocumentHelper.hh>
#include <qpdf/QPDFEmbeddedFileDocumentHelper.hh>
#include <qpdf/QPDFJob.hh>
#include <qpdf/QPDFNameTreeObjectHelper.hh>
#include <qpdf/QPDFNumberTreeObjectHelper.hh>
#include <qpdf/QPDFOutlineDocumentHelper.hh>
#include <qpdf/QPDFPageDocumentHelper.hh>
#include <qpdf/QPDFPageLabelDocumentHelper.hh>
#include <qpdf/QPDFPageObjectHelper.hh>
#include <qpdf/QPDFSystemError.hh>
#include <qpdf/QPDFUsage.hh>
#include <qpdf/QPDFWriter.hh>
#include <qpdf/QTC.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/global.hh>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <sstream>

static char const* whoami = nullptr;

void
usage()
{
    std::cerr << "Usage: " << whoami << " n filename1 [arg2]" << '\n';
    exit(2);
}

// Derive from QPDFNumberTreeObjectHelper -- See test 61
class ExtendNameTree: public QPDFNameTreeObjectHelper
{
  public:
    ExtendNameTree(QPDFObjectHandle o, QPDF& q);
    ~ExtendNameTree() override;
};

ExtendNameTree::ExtendNameTree(QPDFObjectHandle o, QPDF& q) :
    QPDFNameTreeObjectHelper(o, q)
{
}

ExtendNameTree::~ExtendNameTree()
{
    std::cout << "~ExtendNameTree called" << '\n';
}

class Provider: public QPDFObjectHandle::StreamDataProvider
{
  public:
    Provider(std::shared_ptr<Buffer> b) :
        b(b)
    {
    }
    ~Provider() override = default;
    void
    provideStreamData(int objid, int generation, Pipeline* p) override
    {
        // Don't change signature to use QPDFObjGen const& to detect problems forwarding to legacy
        // implementations.
        p->write(b->getBuffer(), b->getSize());
        if (this->bad_length) {
            unsigned char ch = ' ';
            p->write(&ch, 1);
        }
        p->finish();
    }
    void
    badLength(bool v)
    {
        this->bad_length = v;
    }

  private:
    std::shared_ptr<Buffer> b;
    bool bad_length{false};
};

class ParserCallbacks: public QPDFObjectHandle::ParserCallbacks
{
  public:
    ~ParserCallbacks() override = default;
    void contentSize(size_t size) override;
    void handleObject(QPDFObjectHandle, size_t, size_t) override;
    void handleEOF() override;
};

void
ParserCallbacks::contentSize(size_t size)
{
    std::cout << "content size: " << size << '\n';
}

void
ParserCallbacks::handleObject(QPDFObjectHandle obj, size_t offset, size_t length)
{
    if (obj.isName() && (obj.getName() == "/Abort")) {
        std::cout << "test suite: terminating parsing" << '\n';
        terminateParsing();
    }
    std::cout << obj.getTypeName() << ", offset=" << offset << ", length=" << length << ": ";
    if (obj.isInlineImage()) {
        // Exercise getTypeCode
        assert(obj.getTypeCode() == ::ot_inlineimage);
        std::cout << QUtil::hex_encode(obj.getInlineImageValue()) << '\n';
    } else {
        std::cout << obj.unparse() << '\n';
    }
}

void
ParserCallbacks::handleEOF()
{
    std::cout << "-EOF-" << '\n';
}

class TokenFilter: public QPDFObjectHandle::TokenFilter
{
  public:
    TokenFilter() = default;
    ~TokenFilter() override = default;
    void
    handleToken(QPDFTokenizer::Token const& t) override
    {
        if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_string, "Potato")) {
            // Exercise unparsing of strings by token constructor
            writeToken(QPDFTokenizer::Token(QPDFTokenizer::tt_string, "Salad"));
        } else {
            writeToken(t);
        }
    }
    void
    handleEOF() override
    {
        writeToken(QPDFTokenizer::Token(QPDFTokenizer::tt_name, "/bye"));
        write("\n");
    }
};

static std::string
getPageContents(QPDFObjectHandle page)
{
    std::shared_ptr<Buffer> b1 = page.getKey("/Contents").getStreamData();
    return std::string(reinterpret_cast<char*>(b1->getBuffer()), b1->getSize()) + "\0";
}

static void
checkPageContents(QPDFObjectHandle page, std::string const& wanted_string)
{
    std::string contents = getPageContents(page);
    if (contents.find(wanted_string) == std::string::npos) {
        std::cout << "didn't find " << wanted_string << " in " << contents << '\n';
    }
}

static QPDFObjectHandle
createPageContents(QPDF& pdf, std::string const& text)
{
    std::string contents = "BT /F1 15 Tf 72 720 Td (" + text + ") Tj ET\n";
    return QPDFObjectHandle::newStream(&pdf, contents);
}

static void
print_rect(std::ostream& out, QPDFObjectHandle::Rectangle const& r)
{
    out << "[" << r.llx << ", " << r.lly << ", " << r.urx << ", " << r.ury << "]";
}

#define assert_compare_numbers(expected, expr) compare_numbers(#expr, expected, expr)

template <typename T1, typename T2>
static void
compare_numbers(char const* description, T1 const& expected, T2 const& actual)
{
    if (expected != actual) {
        std::cerr << description << ": expected = " << expected << "; actual = " << actual << '\n';
    }
}

static void
test_0_1(QPDF& pdf, char const* arg2)
{
    QPDFObjectHandle trailer = pdf.getTrailer();
    QPDFObjectHandle qtest = trailer.getKey("/QTest");

    if (!trailer.hasKey("/QTest")) {
        // This will always happen when /QTest is null because
        // hasKey returns false for null keys regardless of
        // whether the key exists or not.  That way there's never
        // any difference between a key that is present and null
        // and a key that is absent.
        QTC::TC("qpdf", "main QTest implicit");
        std::cout << "/QTest is implicit" << '\n';
    }

    QTC::TC("qpdf", "main QTest indirect", qtest.isIndirect() ? 1 : 0);
    std::cout << "/QTest is " << (qtest.isIndirect() ? "in" : "") << "direct and has type "
              << qtest.getTypeName() << " (" << qtest.getTypeCode() << ")" << '\n';

    if (qtest.isNull()) {
        QTC::TC("qpdf", "main QTest null");
        std::cout << "/QTest is null" << '\n';
    } else if (qtest.isBool()) {
        QTC::TC("qpdf", "main QTest bool", qtest.getBoolValue() ? 1 : 0);
        std::cout << "/QTest is Boolean with value " << (qtest.getBoolValue() ? "true" : "false")
                  << '\n';
    } else if (qtest.isInteger()) {
        QTC::TC("qpdf", "main QTest int");
        std::cout << "/QTest is an integer with value " << qtest.getIntValue() << '\n';
    } else if (qtest.isReal()) {
        QTC::TC("qpdf", "main QTest real");
        std::cout << "/QTest is a real number with value " << qtest.getRealValue() << '\n';
    } else if (qtest.isName()) {
        QTC::TC("qpdf", "main QTest name");
        std::cout << "/QTest is a name with value " << qtest.getName() << '\n';
    } else if (qtest.isString()) {
        QTC::TC("qpdf", "main QTest string");
        std::cout << "/QTest is a string with value " << qtest.getStringValue() << '\n';
    } else if (qtest.isArray()) {
        QTC::TC("qpdf", "main QTest array");
        std::cout << "/QTest is an array with " << qtest.getArrayNItems() << " items" << '\n';
        int i = 0;
        for (auto& iter: qtest.aitems()) {
            QTC::TC("qpdf", "main QTest array indirect", iter.isIndirect() ? 1 : 0);
            std::cout << "  item " << i << " is " << (iter.isIndirect() ? "in" : "") << "direct"
                      << '\n';
            ++i;
        }
    } else if (qtest.isDictionary()) {
        QTC::TC("qpdf", "main QTest dictionary");
        std::cout << "/QTest is a dictionary" << '\n';
        for (auto& iter: qtest.ditems()) {
            QTC::TC("qpdf", "main QTest dictionary indirect", iter.second.isIndirect() ? 1 : 0);
            std::cout << "  " << iter.first << " is " << (iter.second.isIndirect() ? "in" : "")
                      << "direct" << '\n';
        }
    } else if (qtest.isStream()) {
        QTC::TC("qpdf", "main QTest stream");
        std::cout << "/QTest is a stream.  Dictionary: " << qtest.getDict().unparse() << '\n';

        std::cout << "Raw stream data:" << '\n';
        std::cout.flush();
        QUtil::binary_stdout();
        auto out = std::make_shared<Pl_StdioFile>("raw", stdout);
        qtest.pipeStreamData(out.get(), 0, qpdf_dl_none);

        std::cout << '\n' << "Uncompressed stream data:" << '\n';
        if (qtest.pipeStreamData(nullptr, 0, qpdf_dl_all)) {
            std::cout.flush();
            QUtil::binary_stdout();
            out = std::make_shared<Pl_StdioFile>("filtered", stdout);
            qtest.pipeStreamData(out.get(), 0, qpdf_dl_all);
            std::cout << '\n' << "End of stream data" << '\n';
        } else {
            std::cout << "Stream data is not filterable." << '\n';
        }
    } else {
        // Should not happen!
        std::cout << "/QTest is an unknown object" << '\n';
    }

    std::cout << "unparse: " << qtest.unparse() << '\n'
              << "unparseResolved: " << qtest.unparseResolved() << '\n';
}

static void
test_2(QPDF& pdf, char const* arg2)
{
    // Encrypted file.  This test case is designed for a specific
    // PDF file.

    QPDFObjectHandle trailer = pdf.getTrailer();
    std::cout << trailer.getKey("/Info").getKey("/CreationDate").getStringValue() << '\n';
    std::cout << trailer.getKey("/Info").getKey("/Producer").getStringValue() << '\n';

    QPDFObjectHandle encrypt = trailer.getKey("/Encrypt");
    std::cout << encrypt.getKey("/O").unparse() << '\n';
    std::cout << encrypt.getKey("/U").unparse() << '\n';

    QPDFObjectHandle root = pdf.getRoot();
    QPDFObjectHandle pages = root.getKey("/Pages");
    QPDFObjectHandle kids = pages.getKey("/Kids");
    QPDFObjectHandle page = kids.getArrayItem(1); // second page
    QPDFObjectHandle contents = page.getKey("/Contents");
    QUtil::binary_stdout();
    auto out = std::make_shared<Pl_StdioFile>("filtered", stdout);
    contents.pipeStreamData(out.get(), 0, qpdf_dl_generalized);
}

static void
test_3(QPDF& pdf, char const* arg2)
{
    QPDFObjectHandle streams = pdf.getTrailer().getKey("/QStreams");
    for (int i = 0; i < streams.getArrayNItems(); ++i) {
        QPDFObjectHandle stream = streams.getArrayItem(i);
        std::cout << "-- stream " << i << " --" << '\n';
        std::cout.flush();
        QUtil::binary_stdout();
        auto out = std::make_shared<Pl_StdioFile>("tokenized stream", stdout);
        stream.pipeStreamData(out.get(), qpdf_ef_normalize, qpdf_dl_generalized);
    }
}

static void
test_4(QPDF& pdf, char const* arg2)
{
    // Mutability testing: Make /QTest direct recursively, then
    // copy to /Info.  Also make some other mutations so we can
    // tell the difference and ensure that the original /QTest
    // isn't effected.
    QPDFObjectHandle trailer = pdf.getTrailer();
    QPDFObjectHandle qtest = trailer.getKey("/QTest");
    qtest.makeDirect();
    qtest.removeKey("/Subject");
    qtest.replaceKey("/Author", QPDFObjectHandle::newString("Mr. Potato Head"));
    // qtest.A and qtest.B.A were originally the same object.
    // They no longer are after makeDirect().  Mutate one of them
    // and ensure the other is not changed.  These test cases are
    // crafted around a specific set of input files.
    QPDFObjectHandle A = qtest.getKey("/A");
    if (A.getArrayItem(0).getIntValue() == 1) {
        // Test mutators
        A.setArrayItem(1, QPDFObjectHandle::newInteger(5)); // 1 5 3
        A.insertItem(2, QPDFObjectHandle::newInteger(10));  // 1 5 10 3
        A.appendItem(QPDFObjectHandle::newInteger(12));     // 1 5 10 3 12
        A.eraseItem(3);                                     // 1 5 10 12
        A.insertItem(4, QPDFObjectHandle::newInteger(6));   // 1 5 10 12 6
        A.insertItem(0, QPDFObjectHandle::newInteger(9));   // 9 1 5 10 12 6
    } else {
        std::vector<QPDFObjectHandle> items;
        items.push_back(QPDFObjectHandle::newInteger(14));
        items.push_back(QPDFObjectHandle::newInteger(15));
        items.push_back(QPDFObjectHandle::newInteger(9));
        A.setArrayFromVector(items);
    }

    QPDFObjectHandle qtest2 = trailer.getKey("/QTest2");
    if (!qtest2.isNull()) {
        // Test allow_streams=true
        qtest2.makeDirect(true);
        trailer.replaceKey("/QTest2", qtest2);
    }

    trailer.replaceKey("/Info", pdf.makeIndirectObject(qtest));
    QPDFWriter w(pdf, nullptr);
    w.setQDFMode(true);
    w.setStaticID(true);
    w.write();

    // Prevent "done" message from getting appended
    exit(0);
}

static void
test_5(QPDF& pdf, char const* arg2)
{
    int pageno = 0;
    for (auto& page: QPDFPageDocumentHelper(pdf).getAllPages()) {
        ++pageno;
        std::cout << "page " << pageno << ":" << '\n';
        std::cout << "  images:" << '\n';
        for (auto const& iter2: page.getImages()) {
            std::string const& name = iter2.first;
            QPDFObjectHandle image = iter2.second;
            QPDFObjectHandle dict = image.getDict();
            long long width = dict.getKey("/Width").getIntValue();
            long long height = dict.getKey("/Height").getIntValue();
            std::cout << "    " << name << ": " << width << " x " << height << '\n';
        }

        std::cout << "  content:" << '\n';
        std::vector<QPDFObjectHandle> content = page.getPageContents();
        for (auto& iter2: content) {
            std::cout << "    " << iter2.unparse() << '\n';
        }

        std::cout << "end page " << pageno << '\n';
    }

    QPDFObjectHandle root = pdf.getRoot();
    QPDFObjectHandle qstrings = root.getKey("/QStrings");
    if (qstrings.isArray()) {
        std::cout << "QStrings:" << '\n';
        int nitems = qstrings.getArrayNItems();
        for (int i = 0; i < nitems; ++i) {
            std::cout << qstrings.getArrayItem(i).getUTF8Value() << '\n';
        }
    }

    QPDFObjectHandle qnumbers = root.getKey("/QNumbers");
    if (qnumbers.isArray()) {
        std::cout << "QNumbers:" << '\n';
        int nitems = qnumbers.getArrayNItems();
        for (int i = 0; i < nitems; ++i) {
            std::cout << QUtil::double_to_string(
                             qnumbers.getArrayItem(i).getNumericValue(), 3, false)
                      << '\n';
        }
    }
}

static void
test_6(QPDF& pdf, char const* arg2)
{
    QPDFObjectHandle root = pdf.getRoot();
    QPDFObjectHandle metadata = root.getKey("/Metadata");
    if (!metadata.isStream()) {
        throw std::logic_error("test 6 run on file with no metadata");
    }
    std::string buf;
    Pl_String bufpl("buffer", nullptr, buf);
    metadata.pipeStreamData(&bufpl, 0, qpdf_dl_none);
    bool cleartext = false;
    if (buf.substr(0, 9) == "<?xpacket") {
        cleartext = true;
    }
    std::cout << "encrypted=" << (pdf.isEncrypted() ? 1 : 0)
              << "; cleartext=" << (cleartext ? 1 : 0) << '\n';
}

static void
test_7(QPDF& pdf, char const* arg2)
{
    QPDFObjectHandle root = pdf.getRoot();
    QPDFObjectHandle qstream = root.getKey("/QStream");
    if (!qstream.isStream()) {
        throw std::logic_error("test 7 run on file with no QStream");
    }
    qstream.replaceStreamData(
        "new data for stream\n", QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull());
    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setStreamDataMode(qpdf_s_preserve);
    w.write();
}

static void
test_8(QPDF& pdf, char const* arg2)
{
    QPDFObjectHandle root = pdf.getRoot();
    QPDFObjectHandle qstream = root.getKey("/QStream");
    if (!qstream.isStream()) {
        throw std::logic_error("test 7 run on file with no QStream");
    }
    Pl_Buffer p1("buffer");
    Pl_Flate p2("compress", &p1, Pl_Flate::a_deflate);
    p2 << "new data for stream\n";
    p2.finish();
    auto b = p1.getBufferSharedPointer();
    // This is a bogus way to use StreamDataProvider, but it does
    // adequately test its functionality.
    auto* provider = new Provider(b);
    auto p = std::shared_ptr<QPDFObjectHandle::StreamDataProvider>(provider);
    qstream.replaceStreamData(
        p, QPDFObjectHandle::newName("/FlateDecode"), QPDFObjectHandle::newNull());
    provider->badLength(false);
    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    // Linearize to force the provider to be called multiple times.
    w.setLinearization(true);
    w.setStreamDataMode(qpdf_s_preserve);
    w.write();

    // Every time a provider pipes stream data, it has to provide
    // the same amount of data.
    provider->badLength(true);
    try {
        qstream.getStreamData();
        std::cout << "oops -- getStreamData didn't throw" << '\n';
    } catch (std::exception const& e) {
        std::cout << "exception: " << e.what() << '\n';
    }
}

static void
test_9(QPDF& pdf, char const* arg2)
{
    QPDFObjectHandle root = pdf.getRoot();
    // Explicitly exercise the Buffer version of newStream
    auto buf = std::make_shared<Buffer>(20U);
    unsigned char* bp = buf->getBuffer();
    memcpy(bp, "data for new stream\n", 20); // no null!
    QPDFObjectHandle qstream = QPDFObjectHandle::newStream(&pdf, buf);
    QPDFObjectHandle rstream = QPDFObjectHandle::newStream(&pdf);
    try {
        rstream.getStreamData();
        std::cout << "oops -- getStreamData didn't throw" << '\n';
    } catch (std::logic_error const& e) {
        std::cout << "exception: " << e.what() << '\n';
    }
    rstream.replaceStreamData(
        "data for other stream\n", QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull());
    root.replaceKey("/QStream", qstream);
    root.replaceKey("/RStream", rstream);
    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setStreamDataMode(qpdf_s_preserve);
    w.write();
}

static void
test_10(QPDF& pdf, char const* arg2)
{
    std::vector<QPDFPageObjectHelper> pages = QPDFPageDocumentHelper(pdf).getAllPages();
    QPDFPageObjectHelper& ph(pages.at(0));
    ph.addPageContents(
        QPDFObjectHandle::newStream(&pdf, "BT /F1 12 Tf 72 620 Td (Baked) Tj ET\n"), true);
    ph.addPageContents(
        QPDFObjectHandle::newStream(&pdf, "BT /F1 18 Tf 72 520 Td (Mashed) Tj ET\n"), false);

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setStreamDataMode(qpdf_s_preserve);
    w.write();
}

static void
test_11(QPDF& pdf, char const* arg2)
{
    QPDFObjectHandle root = pdf.getRoot();
    QPDFObjectHandle qstream = root.getKey("/QStream");
    std::shared_ptr<Buffer> b1 = qstream.getStreamData();
    std::shared_ptr<Buffer> b2 = qstream.getRawStreamData();
    if ((b1->getSize() == 7) && (memcmp(b1->getBuffer(), "potato\n", 7) == 0)) {
        std::cout << "filtered stream data okay" << '\n';
    }
    if ((b2->getSize() == 15) && (memcmp(b2->getBuffer(), "706F7461746F0A\n", 15) == 0)) {
        std::cout << "raw stream data okay" << '\n';
    }
}

static void
test_12(QPDF& pdf, char const* arg2)
{
#ifdef _MSC_VER
# pragma warning(disable : 4996)
#endif
#if (defined(__GNUC__) || defined(__clang__))
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
    pdf.setOutputStreams(nullptr, nullptr);
#if (defined(__GNUC__) || defined(__clang__))
# pragma GCC diagnostic pop
#endif
    pdf.showLinearizationData();
}

static void
test_13(QPDF& pdf, char const* arg2)
{
    std::ostringstream out;
    std::ostringstream err;
#ifdef _MSC_VER
# pragma warning(disable : 4996)
#endif
#if (defined(__GNUC__) || defined(__clang__))
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
    pdf.setOutputStreams(&out, &err);
#if (defined(__GNUC__) || defined(__clang__))
# pragma GCC diagnostic pop
#endif
    pdf.showLinearizationData();
    std::cout << "---output---" << '\n' << out.str() << "---error---" << '\n' << err.str();
}

static void
test_14(QPDF& pdf, char const* arg2)
{
    // Exercise swap and replace.  This test case is designed for
    // a specific file.
    std::vector<QPDFObjectHandle> pages = pdf.getAllPages();
    if (pages.size() != 4) {
        throw std::logic_error("test 14 not called 4-page file");
    }
    // Swap pages 2 and 3
    auto orig_page2 = pages.at(1);
    auto orig_page3 = pages.at(2);
    assert(orig_page2.getKey("/OrigPage").getIntValue() == 2);
    assert(orig_page3.getKey("/OrigPage").getIntValue() == 3);
    pdf.swapObjects(orig_page2.getObjGen(), orig_page3.getObjGen());
    assert(orig_page2.getKey("/OrigPage").getIntValue() == 3);
    assert(orig_page3.getKey("/OrigPage").getIntValue() == 2);
    // Replace object and swap objects
    QPDFObjectHandle trailer = pdf.getTrailer();
    QPDFObjectHandle qdict = trailer.getKey("/QDict");
    QPDFObjectHandle qarray = trailer.getKey("/QArray");
    // Force qdict but not qarray to resolve
    qdict.isDictionary();
    QPDFObjectHandle new_dict = QPDFObjectHandle::newDictionary();
    new_dict.replaceKey("/NewDict", QPDFObjectHandle::newInteger(2));
    try {
        // Do it wrong first...
        pdf.replaceObject(qdict.getObjGen(), qdict);
    } catch (std::logic_error const&) {
        std::cout << "caught logic error as expected" << '\n';
    }
    pdf.replaceObject(qdict.getObjGen(), new_dict);
    // Now qdict points to the new dictionary
    std::cout << "old dict: " << qdict.getKey("/NewDict").getIntValue() << '\n';
    // Swap dict and array
    pdf.swapObjects(qdict.getObjGen(), qarray.getObjGen());
    // Now qarray will resolve to new object and qdict resolves to
    // the array
    std::cout << "swapped array: " << qdict.getArrayItem(0).getName() << '\n';
    std::cout << "new dict: " << qarray.getKey("/NewDict").getIntValue() << '\n';
    // Reread qdict, still pointing to an array
    qdict = pdf.getObjectByObjGen(qdict.getObjGen());
    std::cout << "swapped array: " << qdict.getArrayItem(0).getName() << '\n';

    // Exercise getAsMap and getAsArray
    std::vector<QPDFObjectHandle> array_elements = qdict.getArrayAsVector();
    std::map<std::string, QPDFObjectHandle> dict_items = qarray.getDictAsMap();
    if ((array_elements.size() == 1) && (array_elements.at(0).getName() == "/Array") &&
        (dict_items.size() == 1) && (dict_items["/NewDict"].getIntValue() == 2)) {
        std::cout << "array and dictionary contents are correct" << '\n';
    }

    // Exercise writing to memory buffer
    for (int i = 0; i < 2; ++i) {
        QPDFWriter w(pdf);
        w.setOutputMemory();
        // Exercise setOutputMemory with and without static ID
        w.setStaticID(i == 0);
        w.setStreamDataMode(qpdf_s_preserve);
        w.write();
        Buffer* b = w.getBuffer();
        std::string const filename = (i == 0 ? "a.pdf" : "b.pdf");
        FILE* f = QUtil::safe_fopen(filename.c_str(), "wb");
        fwrite(b->getBuffer(), b->getSize(), 1, f);
        fclose(f);
        delete b;
    }
}

static void
test_15(QPDF& pdf, char const* arg2)
{
    std::vector<QPDFObjectHandle> const& pages = pdf.getAllPages();
    // Reference to original page numbers for this test case are
    // numbered from 0.

    // Remove pages from various places, checking to make sure
    // that our pages reference is getting updated.
    assert(pages.size() == 10);
    assert(!pdf.everPushedInheritedAttributesToPages());
    pdf.removePage(pages.back()); // original page 9
    assert(pdf.everPushedInheritedAttributesToPages());
    assert(pages.size() == 9);
    pdf.removePage(*pages.begin()); // original page 0
    assert(pages.size() == 8);
    checkPageContents(pages.at(4), "Original page 5");
    pdf.removePage(pages.at(4)); // original page 5
    assert(pages.size() == 7);
    checkPageContents(pages.at(4), "Original page 6");
    checkPageContents(pages.at(0), "Original page 1");
    checkPageContents(pages.at(6), "Original page 8");

    // Insert pages

    // Create some content streams.
    std::vector<QPDFObjectHandle> contents;
    contents.push_back(createPageContents(pdf, "New page 1"));
    contents.push_back(createPageContents(pdf, "New page 0"));
    contents.push_back(createPageContents(pdf, "New page 5"));
    contents.push_back(createPageContents(pdf, "New page 6"));
    contents.push_back(createPageContents(pdf, "New page 11"));
    contents.push_back(createPageContents(pdf, "New page 12"));

    // Create some page objects.  Start with an existing
    // dictionary and modify it.  Using the results of
    // getDictAsMap to create a new dictionary effectively creates
    // a shallow copy.
    QPDFObjectHandle page_template = pages.at(0);
    std::vector<QPDFObjectHandle> new_pages;
    bool first = true;
    for (auto const& iter: contents) {
        // We will retain indirect object references to other
        // indirect objects other than page content.
        QPDFObjectHandle page = page_template.shallowCopy();
        page.replaceKey("/Contents", iter);
        if (first) {
            // leave direct
            first = false;
        } else {
            page = pdf.makeIndirectObject(page);
        }
        new_pages.push_back(page);
    }

    // Now insert the pages
    pdf.addPage(new_pages.at(0), true);
    checkPageContents(pages.at(0), "New page 1");
    pdf.addPageAt(new_pages.at(1), true, pages.at(0));
    assert(pages.at(0).getObjGen() == new_pages.at(1).getObjGen());
    pdf.addPageAt(new_pages.at(2), true, pages.at(5));
    assert(pages.at(5).getObjGen() == new_pages.at(2).getObjGen());
    pdf.addPageAt(new_pages.at(3), false, pages.at(5));
    assert(pages.at(6).getObjGen() == new_pages.at(3).getObjGen());
    assert(pages.size() == 11);
    pdf.addPage(new_pages.at(4), false);
    assert(pages.at(11).getObjGen() == new_pages.at(4).getObjGen());
    pdf.addPageAt(new_pages.at(5), false, pages.back());
    assert(pages.size() == 13);
    checkPageContents(pages.at(0), "New page 0");
    checkPageContents(pages.at(1), "New page 1");
    checkPageContents(pages.at(5), "New page 5");
    checkPageContents(pages.at(6), "New page 6");
    checkPageContents(pages.at(11), "New page 11");
    checkPageContents(pages.at(12), "New page 12");

    // Exercise writing to FILE*
    FILE* out = QUtil::safe_fopen("a.pdf", "wb");
    QPDFWriter w(pdf, "FILE* a.pdf", out, true);
    w.setStaticID(true);
    w.setStreamDataMode(qpdf_s_preserve);
    w.write();
}

static void
test_16(QPDF& pdf, char const* arg2)
{
    // Insert a page manually and then update the cache.
    assert(!pdf.everCalledGetAllPages());
    std::vector<QPDFObjectHandle> const& all_pages = pdf.getAllPages();
    assert(pdf.everCalledGetAllPages());

    QPDFObjectHandle contents = createPageContents(pdf, "New page 10");
    QPDFObjectHandle page = pdf.makeIndirectObject(QPDFObjectHandle(all_pages.at(0)).shallowCopy());
    page.replaceKey("/Contents", contents);

    // Insert the page manually.
    QPDFObjectHandle root = pdf.getRoot();
    QPDFObjectHandle pages = root.getKey("/Pages");
    QPDFObjectHandle kids = pages.getKey("/Kids");
    page.replaceKey("/Parent", pages);
    pages.replaceKey(
        "/Count", QPDFObjectHandle::newInteger(1 + QIntC::to_longlong(all_pages.size())));
    kids.appendItem(page);
    assert(all_pages.size() == 10);
    pdf.updateAllPagesCache();
    assert(pdf.everCalledGetAllPages());
    assert(all_pages.size() == 11);
    assert(all_pages.back().getObjGen() == page.getObjGen());

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setStreamDataMode(qpdf_s_preserve);
    w.write();
}

static void
test_17(QPDF& pdf, char const* arg2)
{
    // The input file to this test case has a duplicated page.
    QPDFObjectHandle page_kids = pdf.getRoot().getKey("/Pages").getKey("/Kids");
    assert(page_kids.getArrayItem(0).getObjGen() == page_kids.getArrayItem(1).getObjGen());
    std::vector<QPDFObjectHandle> const& pages = pdf.getAllPages();
    assert(pages.size() == 3);
    assert(!(pages.at(0).getObjGen() == pages.at(1).getObjGen()));
    assert(
        QPDFObjectHandle(pages.at(0)).getKey("/Contents").getObjGen() ==
        QPDFObjectHandle(pages.at(1)).getKey("/Contents").getObjGen());
    pdf.removePage(pages.at(0));
    assert(pages.size() == 2);
    std::shared_ptr<Buffer> b = QPDFObjectHandle(pages.at(0)).getKey("/Contents").getStreamData();
    std::string contents = std::string(reinterpret_cast<char const*>(b->getBuffer()), b->getSize());
    assert(contents.find("page 0") != std::string::npos);
}

static void
test_18(QPDF& pdf, char const* arg2)
{
    // Remove a page and re-insert it in the same file.
    std::vector<QPDFObjectHandle> const& pages = pdf.getAllPages();

    // Remove pages from various places, checking to make sure
    // that our pages reference is getting updated.
    assert(pages.size() == 10);
    QPDFObjectHandle page5 = pages.at(5);
    pdf.removePage(page5);
    assert(pages.size() == 9);
    pdf.addPage(page5, false);
    assert(pages.size() == 10);
    assert(pages.back().getObjGen() == page5.getObjGen());

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setStreamDataMode(qpdf_s_preserve);
    w.write();
}

static void
test_19(QPDF& pdf, char const* arg2)
{
    // Remove a page and re-insert it in the same file.
    std::vector<QPDFObjectHandle> const& pages = pdf.getAllPages();

    // Try to insert a page that's already there. A shallow copy
    // gets inserted instead.
    auto newpage = pages.at(5);
    size_t count = pages.size();
    pdf.addPage(newpage, false);
    auto last = pages.back();
    assert(pages.size() == count + 1);
    assert(!(last.getObjGen() == newpage.getObjGen()));
    assert(last.getKey("/Contents").getObjGen() == newpage.getKey("/Contents").getObjGen());
}

static void
test_20(QPDF& pdf, char const* arg2)
{
    // Shallow copy an array
    QPDFObjectHandle trailer = pdf.getTrailer();
    QPDFObjectHandle qtest = trailer.getKey("/QTest");
    QPDFObjectHandle copy = qtest.shallowCopy();
    // Append shallow copy of a scalar
    copy.appendItem(trailer.getKey("/Size").shallowCopy());
    trailer.replaceKey("/QTest2", copy);

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setStreamDataMode(qpdf_s_preserve);
    w.write();
}

static void
test_21(QPDF& pdf, char const* arg2)
{
    // Try to shallow copy a stream
    std::vector<QPDFObjectHandle> const& pages = pdf.getAllPages();
    QPDFObjectHandle page = pages.at(0);
    QPDFObjectHandle contents = page.getKey("/Contents");
    contents.shallowCopy();
    std::cout << "you can't see this" << '\n';
}

static void
test_22(QPDF& pdf, char const* arg2)
{
    // Try to remove a page we don't have
    QPDFPageDocumentHelper dh(pdf);
    std::vector<QPDFPageObjectHelper> pages = dh.getAllPages();
    QPDFPageObjectHelper& page = pages.at(0);
    dh.removePage(page);
    dh.removePage(page);
    std::cout << "you can't see this" << '\n';
}

static void
test_23(QPDF& pdf, char const* arg2)
{
    QPDFPageDocumentHelper dh(pdf);
    std::vector<QPDFPageObjectHelper> pages = dh.getAllPages();
    dh.removePage(pages.back());
}

static void
test_24(QPDF& pdf, char const* arg2)
{
    // Test behavior of reserved objects
    QPDFObjectHandle res1 = QPDFObjectHandle::newReserved(&pdf);
    QPDFObjectHandle res2 = QPDFObjectHandle::newReserved(&pdf);
    QPDFObjectHandle trailer = pdf.getTrailer();
    trailer.replaceKey("Array1", res1);
    trailer.replaceKey("Array2", res2);

    QPDFObjectHandle array1 = QPDFObjectHandle::newArray();
    QPDFObjectHandle array2 = QPDFObjectHandle::newArray();
    array1.appendItem(res2);
    array1.appendItem(QPDFObjectHandle::newInteger(1));
    array2.appendItem(res1);
    array2.appendItem(QPDFObjectHandle::newInteger(2));
    // Make sure trying to ask questions about a reserved object
    // doesn't break it.
    if (res1.isArray()) {
        std::cout << "oops -- res1 is an array" << '\n';
    }
    if (res1.isReserved()) {
        std::cout << "res1 is still reserved after checking if array" << '\n';
    }
    pdf.replaceReserved(res1, array1);
    if (res1.isReserved()) {
        std::cout << "oops -- res1 is still reserved" << '\n';
    } else {
        std::cout << "res1 is no longer reserved" << '\n';
    }
    res1.assertArray();
    std::cout << "res1 is an array" << '\n';

    try {
        res2.unparseResolved();
        std::cout << "oops -- didn't throw" << '\n';
    } catch (std::logic_error const& e) {
        std::cout << "logic error: " << e.what() << '\n';
    }
    try {
        res2.makeDirect();
        std::cout << "oops -- didn't throw" << '\n';
    } catch (std::logic_error const& e) {
        std::cout << "logic error: " << e.what() << '\n';
    }

    pdf.replaceReserved(res2, array2);

    res2.assertArray();
    std::cout << "res2 is an array" << '\n';

    // Verify that the previously added reserved keys can be
    // dereferenced properly now
    int i1 = res1.getArrayItem(0).getArrayItem(1).getIntValueAsInt();
    int i2 = res2.getArrayItem(0).getArrayItem(1).getIntValueAsInt();
    if ((i1 == 2) && (i2 == 1)) {
        std::cout << "circular access and lazy resolution worked" << '\n';
    }

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setStreamDataMode(qpdf_s_preserve);
    w.write();
}

static void
test_25(QPDF& pdf, char const* arg2)
{
    // The copy object tests are designed to work with a specific
    // file.  Look at the test suite for the file, and look at the
    // file for comments about the file's structure.

    // Copy qtest without crossing page boundaries.  Should get O1
    // and O2 and their streams but not O3 or any other pages.

    // Also verify that attempts to copy /Pages objects return null.

    assert(arg2 != nullptr);
    {
        // Make sure original PDF is out of scope when we write.
        QPDF oldpdf;
        oldpdf.processFile(arg2);
        QPDFObjectHandle qtest = oldpdf.getTrailer().getKey("/QTest");
        pdf.getTrailer().replaceKey("/QTest", pdf.copyForeignObject(qtest));

        assert(pdf.copyForeignObject(oldpdf.getRoot().getKey("/Pages")).isNull());
    }

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setStreamDataMode(qpdf_s_preserve);
    w.write();
}

static void
test_26(QPDF& pdf, char const* arg2)
{
    // Copy the O3 page using addPage.  Copy qtest without
    // crossing page boundaries.  In addition to previous results,
    // should get page O3 but no other pages including the page
    // that O3 points to.  Also, inherited object will have been
    // pushed down and will be preserved.

    {
        // Make sure original PDF is out of scope when we write.
        assert(arg2 != nullptr);
        QPDF oldpdf;
        oldpdf.processFile(arg2);
        QPDFObjectHandle qtest = oldpdf.getTrailer().getKey("/QTest");
        QPDFObjectHandle O3 = qtest.getKey("/O3");
        QPDFPageDocumentHelper(pdf).addPage(O3, false);
        pdf.getTrailer().replaceKey("/QTest", pdf.copyForeignObject(qtest));
    }

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setStreamDataMode(qpdf_s_preserve);
    w.write();
}

static void
test_27(QPDF& pdf, char const* arg2)
{
    // Copy O3 and the page O3 refers to before copying qtest.
    // Should get qtest plus only the O3 page and the page that O3
    // points to. Inherited objects should be preserved. This test
    // also exercises copying from a stream that has a buffer and
    // a provider, including copying a provider multiple times. We
    // also exercise setImmediateCopyFrom.

    // Create a provider. The provider stays in scope.
    std::shared_ptr<QPDFObjectHandle::StreamDataProvider> p1;
    {
        // Local scope
        Pl_Buffer pl("buffer");
        pl.writeCStr("new data for stream\n");
        pl.finish();
        auto b = pl.getBufferSharedPointer();
        auto* provider = new Provider(b);
        p1 = decltype(p1)(provider);
    }
    // Create a stream that uses a provider in empty1 and copy it
    // to empty2. It is copied from empty2 to the final pdf.
    QPDF empty1;
    empty1.emptyPDF();
    QPDFObjectHandle s1 = QPDFObjectHandle::newStream(&empty1);
    s1.replaceStreamData(p1, QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull());
    QPDF empty2;
    empty2.emptyPDF();
    s1 = empty2.copyForeignObject(s1);
    {
        // Make sure some source PDFs are out of scope when we
        // write.

        std::shared_ptr<QPDFObjectHandle::StreamDataProvider> p2;
        // Create another provider. This one will go out of scope
        // along with its containing qpdf, which has
        // setImmediateCopyFrom(true).
        {
            // Local scope
            Pl_Buffer pl("buffer");
            pl.writeCStr("more data for stream\n");
            pl.finish();
            auto b = pl.getBufferSharedPointer();
            auto* provider = new Provider(b);
            p2 = decltype(p2)(provider);
        }
        QPDF empty3;
        empty3.emptyPDF();
        empty3.setImmediateCopyFrom(true);
        QPDFObjectHandle s3 = QPDFObjectHandle::newStream(&empty3);
        s3.replaceStreamData(p2, QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull());
        assert(arg2 != nullptr);
        QPDF oldpdf;
        oldpdf.processFile(arg2);
        QPDFObjectHandle qtest = oldpdf.getTrailer().getKey("/QTest");
        QPDFObjectHandle O3 = qtest.getKey("/O3");
        QPDFPageDocumentHelper dh(pdf);
        dh.addPage(O3.getKey("/OtherPage"), false);
        dh.addPage(O3, false);
        QPDFObjectHandle s2 = QPDFObjectHandle::newStream(&oldpdf, "potato\n");
        auto trailer = pdf.getTrailer();
        trailer.replaceKey("/QTest", pdf.copyForeignObject(qtest));
        auto qtest2 = trailer.replaceKeyAndGetNew("/QTest2", QPDFObjectHandle::newArray());
        qtest2.appendItem(pdf.copyForeignObject(s1));
        qtest2.appendItem(pdf.copyForeignObject(s2));
        qtest2.appendItem(pdf.copyForeignObject(s3));
    }

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setCompressStreams(false);
    w.setDecodeLevel(qpdf_dl_generalized);
    w.write();
}

static void
test_28(QPDF& pdf, char const* arg2)
{
    // Copy foreign object errors
    try {
        pdf.copyForeignObject(pdf.getTrailer().getKey("/QTest"));
        std::cout << "oops -- didn't throw" << '\n';
    } catch (std::logic_error const& e) {
        std::cout << "logic error: " << e.what() << '\n';
    }
    try {
        pdf.copyForeignObject(QPDFObjectHandle::newInteger(1));
        std::cout << "oops -- didn't throw" << '\n';
    } catch (std::logic_error const& e) {
        std::cout << "logic error: " << e.what() << '\n';
    }
}

static void
test_29(QPDF& pdf, char const* arg2)
{
    // Detect mixed objects in QPDFWriter
    assert(arg2 != nullptr);
    auto other = QPDF::create();
    other->processFile(arg2);
    // We need to create a QPDF with mixed ownership to exercise
    // QPDFWriter's ownership check. To do this, we have to sneak the
    // foreign object inside an ownerless direct object to avoid
    // detection prior to calling QPDFWriter. Maybe a future version
    // of qpdf will be able prevent creating mixed ownership. Another
    // way to fake it out would be to call setDescription to
    // explicitly change the ownership to the wrong value.
    auto dict = QPDFObjectHandle::newDictionary();
    dict.replaceKey("/QTest", pdf.getTrailer().getKey("/QTest"));
    other->getTrailer().replaceKey("/QTest", dict);

    try {
        QPDFWriter w(*other, "a.pdf");
        w.write();
        std::cout << "oops -- didn't throw" << '\n';
    } catch (std::logic_error const& e) {
        std::cout << "logic error: " << e.what() << '\n';
    }

    // Make sure deleting the other source doesn't prevent detection.
    auto other2 = QPDF::create();
    other2->emptyPDF();
    dict = QPDFObjectHandle::newDictionary();
    dict.replaceKey("/QTest", other2->getRoot());
    other->getTrailer().replaceKey("/QTest", dict);
    other2 = nullptr;
    try {
        QPDFWriter w(*other, "a.pdf");
        w.write();
        std::cout << "oops -- didn't throw" << '\n';
    } catch (std::logic_error const& e) {
        std::cout << "logic error: " << e.what() << '\n';
    }

    // Detect adding a foreign object
    auto root1 = pdf.getRoot();
    auto root2 = other->getRoot();
    try {
        root1.replaceKey("/Oops", root2);
    } catch (std::logic_error const& e) {
        std::cout << "logic error: " << e.what() << '\n';
    }
}

static void
test_30(QPDF& pdf, char const* arg2)
{
    assert(arg2 != nullptr);
    QPDF encrypted;
    encrypted.processFile(arg2, "user");
    QPDFWriter w(pdf, "b.pdf");
    w.setStreamDataMode(qpdf_s_preserve);
    w.copyEncryptionParameters(encrypted);
    w.write();

    // Make sure the contents are actually the same
    QPDF final;
    final.processFile("b.pdf", "user");
    std::vector<QPDFObjectHandle> pages = pdf.getAllPages();
    std::string orig_contents = getPageContents(pages.at(0));
    pages = final.getAllPages();
    std::string new_contents = getPageContents(pages.at(0));
    if (orig_contents != new_contents) {
        std::cout << "oops -- page contents don't match" << '\n'
                  << "original:\n"
                  << orig_contents << "new:\n"
                  << new_contents << '\n';
    }
}

static void
test_31(QPDF& pdf, char const* arg2)
{
    auto o1 = "[/name 16059 3.14159 false\n"
              " << /key true /other [ (string1) (string2) ] >> null]"_qpdf;
    std::cout << o1.unparse() << '\n';
    QPDFObjectHandle o2 = QPDFObjectHandle::parse("   12345 \f  ");
    assert(o2.isInteger() && (o2.getIntValue() == 12345));
    try {
        QPDFObjectHandle::parse("[1 0 R]", "indirect test");
        std::cout << "oops -- didn't throw" << '\n';
    } catch (std::logic_error const& e) {
        std::cout << "logic error parsing indirect: " << e.what() << '\n';
    }
    try {
        QPDFObjectHandle::parse("0 trailing", "trailing test");
        std::cout << "oops -- didn't throw" << '\n';
    } catch (std::runtime_error const& e) {
        std::cout << "trailing data: " << e.what() << '\n';
    }
    assert(QPDFObjectHandle::parse(&pdf, "[5 0 R]").getArrayItem(0).isInteger());
    assert(!QPDFObjectHandle::parse(&pdf, "[5 0 R]").getArrayItem(0).isDirectNull());
    // Make sure an indirect integer followed by "0 R" is not
    // mistakenly parsed as an indirect object.
    assert(QPDFObjectHandle::parse(&pdf, "[5 0 R 0 R /X]").unparse() == "[ 5 0 R 0 (R) /X ]");
    assert(QPDFObjectHandle::parse(&pdf, "[1 0 R]", "indirect test").unparse() == "[ 1 0 R ]");
    // TC:QPDFParser bad brace
    assert(QPDFObjectHandle::parse(&pdf, "}").unparse() == "null");
    assert(QPDFObjectHandle::parse(&pdf, "{").unparse() == "null");
    // TC:QPDFParser bad dictionary close
    assert(QPDFObjectHandle::parse(&pdf, ">>").unparse() == "null");
    // TC:QPDFParser eof in parse
    assert(QPDFObjectHandle::parse(&pdf, "[7 0 R]").getArrayItem(0).isNull());
    assert(!QPDFObjectHandle::parse(&pdf, "[7 0 R]").getArrayItem(0).isDirectNull());
    assert(QPDFObjectHandle::parse(&pdf, "null").isDirectNull());
    // TC:QPDFParser invalid objgen
    assert(
        QPDFObjectHandle::parse(&pdf, "[0 0 R -1 0 R 1 65535 R 1 100000 R 1 -1 R]").unparse() ==
        "[ null null null null null ]");
}

static void
test_32(QPDF& pdf, char const* arg2)
{
    // Extra header text
    char const* filenames[] = {"a.pdf", "b.pdf", "c.pdf", "d.pdf"};
    for (int i = 0; i < 4; ++i) {
        bool linearized = ((i & 1) != 0);
        bool newline = ((i & 2) != 0);
        QPDFWriter w(pdf, filenames[i]);
        w.setStaticID(true);
        std::cout << "file: " << filenames[i] << '\n'
                  << "linearized: " << (linearized ? "yes" : "no") << '\n'
                  << "newline: " << (newline ? "yes" : "no") << '\n';
        w.setLinearization(linearized);
        if (linearized) {
            w.setCompressStreams(false); // avoid dependency on zlib's output
        }
        w.setExtraHeaderText(newline ? "%% Comment with newline\n" : "%% Comment\n% No newline");
        w.write();
    }
}

static void
test_33(QPDF& pdf, char const* arg2)
{
    // Test writing to a custom pipeline
    Pl_Buffer p("buffer");
    QPDFWriter w(pdf);
    w.setStaticID(true);
    w.setOutputPipeline(&p);
    w.write();
    auto b = p.getBufferSharedPointer();
    FILE* f = QUtil::safe_fopen("a.pdf", "wb");
    fwrite(b->getBuffer(), b->getSize(), 1, f);
    fclose(f);
}

static void
test_34(QPDF& pdf, char const* arg2)
{
    // Look at Extensions dictionary
    std::cout << "version: " << pdf.getPDFVersion() << '\n'
              << "extension level: " << pdf.getExtensionLevel() << '\n'
              << pdf.getRoot().getKey("/Extensions").unparse() << '\n';
    auto v = pdf.getVersionAsPDFVersion();
    std::string v_string;
    int extension_level;
    v.getVersion(v_string, extension_level);
    std::cout << "As PDFVersion: " << v_string << "/" << extension_level << '\n';
}

static void
test_35(QPDF& pdf, char const* arg2)
{
    // Extract attachments

    std::map<std::string, std::shared_ptr<Buffer>> attachments;
    QPDFObjectHandle root = pdf.getRoot();
    QPDFObjectHandle names = root.getKey("/Names");
    QPDFObjectHandle embeddedFiles = names.getKey("/EmbeddedFiles");
    names = embeddedFiles.getKey("/Names");
    for (int i = 0; i < names.getArrayNItems(); ++i) {
        QPDFObjectHandle item = names.getArrayItem(i);
        if (item.isDictionary() && item.getKey("/Type").isName() &&
            (item.getKey("/Type").getName() == "/Filespec") && item.getKey("/EF").isDictionary() &&
            item.getKey("/EF").getKey("/F").isStream()) {
            std::string filename = item.getKey("/F").getStringValue();
            QPDFObjectHandle stream = item.getKey("/EF").getKey("/F");
            attachments[filename] = stream.getStreamData();
        }
    }
    for (auto const& iter: attachments) {
        std::string const& filename = iter.first;
        std::string data = std::string(
            reinterpret_cast<char const*>(iter.second->getBuffer()), iter.second->getSize());
        bool is_binary = false;
        for (size_t i = 0; i < data.size(); ++i) {
            if ((data.at(i) < 0) || (data.at(i) > 126)) {
                is_binary = true;
                break;
            }
        }
        if (is_binary) {
            std::string t;
            for (size_t i = 0; i < std::min(data.size(), QIntC::to_size(20)); ++i) {
                if ((data.at(i) >= 32) && (data.at(i) <= 126)) {
                    t += data.at(i);
                } else {
                    t += ".";
                }
            }
            t += " (" + QUtil::uint_to_string(data.size()) + " bytes)";
            data = t;
        }
        std::cout << filename << ":\n" << data << "--END--\n";
    }
}

static void
test_36(QPDF& pdf, char const* arg2)
{
    // Extract raw unfilterable attachment

    QPDFObjectHandle root = pdf.getRoot();
    QPDFObjectHandle names = root.getKey("/Names");
    QPDFObjectHandle embeddedFiles = names.getKey("/EmbeddedFiles");
    names = embeddedFiles.getKey("/Names");
    for (int i = 0; i < names.getArrayNItems(); ++i) {
        QPDFObjectHandle item = names.getArrayItem(i);
        if (item.isDictionary() && item.getKey("/Type").isName() &&
            (item.getKey("/Type").getName() == "/Filespec") && item.getKey("/EF").isDictionary() &&
            item.getKey("/EF").getKey("/F").isStream() &&
            (item.getKey("/F").getStringValue() == "attachment1.txt")) {
            std::string filename = item.getKey("/F").getStringValue();
            QPDFObjectHandle stream = item.getKey("/EF").getKey("/F");
            Pl_Buffer p1("buffer");
            Pl_Flate p2("compress", &p1, Pl_Flate::a_inflate);
            stream.pipeStreamData(&p2, 0, qpdf_dl_none);
            auto buf = p1.getBufferSharedPointer();
            std::string data =
                std::string(reinterpret_cast<char const*>(buf->getBuffer()), buf->getSize());
            std::cout << stream.getDict().unparse() << filename << ":\n" << data << "--END--\n";
        }
    }
}

static void
test_37(QPDF& pdf, char const* arg2)
{
    // Parse content streams of all pages
    for (auto& page: QPDFPageDocumentHelper(pdf).getAllPages()) {
        ParserCallbacks cb;
        page.parseContents(&cb);
    }
}

static void
test_38(QPDF& pdf, char const* arg2)
{
    // Designed for override-compressed-object.pdf
    QPDFObjectHandle qtest = pdf.getRoot().getKey("/QTest");
    for (int i = 0; i < qtest.getArrayNItems(); ++i) {
        std::cout << qtest.getArrayItem(i).unparseResolved() << '\n';
    }
}

static void
test_39(QPDF& pdf, char const* arg2)
{
    // Display image filter and color set for each image on each page
    int pageno = 0;
    for (auto& page: QPDFPageDocumentHelper(pdf).getAllPages()) {
        std::cout << "page " << ++pageno << '\n';
        std::map<std::string, QPDFObjectHandle> images = page.getImages();
        for (auto& i_iter: images) {
            QPDFObjectHandle image_dict = i_iter.second.getDict();
            std::cout << "filter: " << image_dict.getKey("/Filter").unparseResolved()
                      << ", color space: " << image_dict.getKey("/ColorSpace").unparseResolved()
                      << '\n';
        }
    }
}

static void
test_40(QPDF& pdf, char const* arg2)
{
    // Write PCLm. This requires specially crafted PDF files. This
    // feature was implemented by Sahil Arora
    // <sahilarora.535@gmail.com> as part of a Google Summer of
    // Code project in 2017.
    assert(arg2 != nullptr);
    QPDFWriter w(pdf, arg2);
    w.setPCLm(true);
    w.setStaticID(true);
    w.write();
}

static void
test_41(QPDF& pdf, char const* arg2)
{
    // Apply a token filter. This test case is crafted to work
    // with coalesce.pdf.
    for (auto& page: QPDFPageDocumentHelper(pdf).getAllPages()) {
        page.addContentTokenFilter(
            std::shared_ptr<QPDFObjectHandle::TokenFilter>(new TokenFilter()));
    }
    QPDFWriter w(pdf, "a.pdf");
    w.setQDFMode(true);
    w.setStaticID(true);
    w.write();
}

static void
test_42(QPDF& pdf, char const* arg2)
{
    // Access objects as wrong type. This test case is crafted to work with object-types.pdf.
    QPDFObjectHandle qtest = pdf.getTrailer().getKey("/QTest");
    QPDFObjectHandle array = qtest.getKey("/Dictionary").getKey("/Key2");
    QPDFObjectHandle dictionary = qtest.getKey("/Dictionary");
    QPDFObjectHandle integer = qtest.getKey("/Integer");
    QPDFObjectHandle null = QPDFObjectHandle::newNull();
    assert(array.isArray());
    {
        // Exercise iterators directly
        auto ai = array.aitems();
        auto i = ai.begin();
        assert(i->getName() == "/Item0");
        auto& i_value = *i;
        --i;
        assert(i->getName() == "/Item0");
        ++i;
        ++i;
        ++i;
        assert(i == ai.end());
        ++i;
        assert(i == ai.end());
        assert(!i_value);
        --i;
        assert(i_value.getName() == "/Item2");
        assert(i->getName() == "/Item2");
    }
    assert(dictionary.isDictionary());
    {
        // Exercise iterators directly
        auto di = dictionary.ditems();
        auto i = di.begin();
        assert(i->first == "/Key1");
        auto& i_value = *i;
        assert(i->second.getName() == "/Value1");
        ++i;
        ++i;
        assert(i == di.end());
        assert(!i_value.second);
    }
    assert(qtest.getStringValue().empty());
    array.getArrayItem(-1).assertNull();
    array.getArrayItem(16059).assertNull();
    integer.getArrayItem(0).assertNull();
    integer.appendItem(null);
    array.eraseItem(-1);
    array.eraseItem(16059);
    array.insertItem(42, "/Dontpanic"_qpdf);
    array.setArrayItem(42, "/Dontpanic"_qpdf);
    integer.eraseItem(0);
    integer.insertItem(0, null);
    integer.setArrayFromVector(std::vector<QPDFObjectHandle>());
    integer.setArrayItem(0, null);
    assert(0 == integer.getArrayNItems());
    assert(integer.getArrayAsVector().empty());
    assert(false == integer.getBoolValue());
    assert(integer.getDictAsMap().empty());
    assert(integer.getKeys().empty());
    assert(false == integer.hasKey("/Potato"));
    integer.removeKey("/Potato");
    integer.replaceKey("/Potato", null);
    integer.replaceKey("/Potato", QPDFObjectHandle::newInteger(1));
    null.getKeyIfDict("/Integer").getKeyIfDict("/Potato").assertNull();
    qtest.getKey("/Integer").getKeyIfDict("/Potato");
    qtest.getKey("/Integer").getKey("/Potato");
    assert(integer.getInlineImageValue().empty());
    assert(0 == dictionary.getIntValue());
    assert("/QPDFFakeName" == integer.getName());
    assert("QPDFFAKE" == integer.getOperatorValue());
    assert("0.0" == dictionary.getRealValue());
    assert(integer.getStringValue().empty());
    assert(integer.getUTF8Value().empty());
    assert(0.0 == dictionary.getNumericValue());
    // Make sure error messages are okay for nested values
    std::cerr << "One error\n";
    assert(array.getArrayItem(0).getStringValue().empty());
    std::cerr << "One error\n";
    assert(dictionary.getKey("/Quack").getStringValue().empty());
    assert(dictionary.getKeyIfDict("/Quack").getStringValue().empty());
    assert(array.getArrayItem(1).isDictionary());
    assert(array.getArrayItem(1).getKey("/K").isArray());
    assert(array.getArrayItem(1).getKey("/K").getArrayItem(0).isName());
    assert("/V" == array.getArrayItem(1).getKey("/K").getArrayItem(0).getName());
    std::cerr << "Two errors\n";
    assert(array.getArrayItem(16059).getStringValue().empty());
    std::cerr << "One error\n";
    array.getArrayItem(1).getKey("/K").getArrayItem(0).getStringValue();
    // Stream dictionary
    QPDFObjectHandle page = pdf.getAllPages().at(0);
    assert("/QPDFFakeName" == page.getKey("/Contents").getDict().getKey("/Potato").getName());
    // Rectangle
    QPDFObjectHandle::Rectangle r0 = integer.getArrayAsRectangle();
    assert((r0.llx == 0) && (r0.lly == 0) && (r0.urx == 0) && (r0.ury == 0));
    QPDFObjectHandle rect =
        QPDFObjectHandle::newFromRectangle(QPDFObjectHandle::Rectangle(1.2, 3.4, 5.6, 7.8));
    QPDFObjectHandle::Rectangle r1 = rect.getArrayAsRectangle();
    assert(
        (r1.llx > 1.19) && (r1.llx < 1.21) && (r1.lly > 3.39) && (r1.lly < 3.41) &&
        (r1.urx > 5.59) && (r1.urx < 5.61) && (r1.ury > 7.79) && (r1.ury < 7.81));
    assert(!"[1 2 3 4 5]"_qpdf.isRectangle());
    r1 = "[1 2 3 4 5]"_qpdf.getArrayAsRectangle();
    assert(r0.llx == 0 && r0.lly == 0 && r0.urx == 0 && r0.ury == 0);
    assert(!"[1 2 3]"_qpdf.isRectangle());
    r1 = "[1 2 3]"_qpdf.getArrayAsRectangle();
    assert(r0.llx == 0 && r0.lly == 0 && r0.urx == 0 && r0.ury == 0);
    assert(!"[1 2 false 4]"_qpdf.isRectangle());
    r1 = "[1 2 false 4]"_qpdf.getArrayAsRectangle();
    assert(r0.llx == 0 && r0.lly == 0 && r0.urx == 0 && r0.ury == 0);
    // Matrix
    auto matrix =
        QPDFObjectHandle::newFromMatrix(QPDFObjectHandle::Matrix{1.2, 3.4, 5.6, 7.8, 9.1, 2.3});
    auto m1 = matrix.getArrayAsMatrix();
    assert(
        m1.a > 1.19 && m1.a < 1.21 && m1.b > 3.39 && m1.b < 3.41 && m1.c > 5.59 && m1.c < 5.61 &&
        m1.d > 7.79 && m1.d < 7.81 && m1.e > 9.09 && m1.e < 9.11 && m1.f > 2.29 && m1.f < 2.31);
    assert(matrix.isMatrix());
    matrix = QPDFObjectHandle::newFromMatrix(QPDFMatrix{1.2, 3.4, 5.6, 7.8, 9.1, 2.3});
    m1 = matrix.getArrayAsMatrix();
    assert(
        m1.a > 1.19 && m1.a < 1.21 && m1.b > 3.39 && m1.b < 3.41 && m1.c > 5.59 && m1.c < 5.61 &&
        m1.d > 7.79 && m1.d < 7.81 && m1.e > 9.09 && m1.e < 9.11 && m1.f > 2.29 && m1.f < 2.31);
    assert(matrix.isMatrix());
    assert(!"[1 2 3 4 5]"_qpdf.isMatrix());
    m1 = "[1 2 3 4 5]"_qpdf.getArrayAsMatrix();
    assert(m1.a == 0 && m1.b == 0 && m1.c == 0 && m1.d == 0 && m1.e == 0 && m1.f == 0);
    assert(!"[1 2 3 4 5 6 7]"_qpdf.isMatrix());
    m1 = "[1 2 3 4 5 6 7]"_qpdf.getArrayAsMatrix();
    assert(m1.a == 0 && m1.b == 0 && m1.c == 0 && m1.d == 0 && m1.e == 0 && m1.f == 0);
    assert(!"[1 2 3 false 5 6 7]"_qpdf.isMatrix());
    m1 = "[1 2 3 false 5 6 7]"_qpdf.getArrayAsMatrix();
    assert(m1.a == 0 && m1.b == 0 && m1.c == 0 && m1.d == 0 && m1.e == 0 && m1.f == 0);
    assert(!"42"_qpdf.isMatrix());
    m1 = "42"_qpdf.getArrayAsMatrix();
    assert(m1.a == 0 && m1.b == 0 && m1.c == 0 && m1.d == 0 && m1.e == 0 && m1.f == 0);

    // Uninitialized
    QPDFObjectHandle uninitialized;
    assert(!uninitialized);
    assert(!uninitialized.isInteger());
    assert(!uninitialized.isDictionary());
    assert(!uninitialized.isScalar());

    // Reference
    auto indirect = pdf.newIndirectNull();
    QPDFObjGen indirect_og{indirect.getObjGen()};
    pdf.replaceObject(indirect, array);
    assert(array.isIndirect());
    assert(indirect.isArray());
    assert(array.getObjGen() == indirect_og);
    assert(array.isArray());
    assert(indirect.isArray());
    assert(indirect.unparse() == indirect_og.unparse(' ') + " R");

    auto pl1 = Pl_Buffer("");
    array.writeJSON(2, &pl1, true);
    pl1.finish();
    assert(pl1.getString() == std::string("\"" + indirect_og.unparse(' ') + " R\""));

    array.setArrayItem(1, "42"_qpdf);
    assert(indirect.getArrayItem(1).getIntValue() == 42);

    pdf.replaceObject(indirect, "42"_qpdf);
    assert(array.isInteger());
}

static void
test_43(QPDF& pdf, char const* arg2)
{
    // Forms
    QPDFAcroFormDocumentHelper afdh(pdf);
    if (!afdh.hasAcroForm()) {
        std::cout << "no forms\n";
        return;
    }
    std::cout << "iterating over form fields\n";
    for (auto& ffh: afdh.getFormFields()) {
        std::cout << "Field: " << ffh.getObjectHandle().unparse() << '\n';
        QPDFFormFieldObjectHelper node = ffh;
        while (!node.isNull()) {
            QPDFFormFieldObjectHelper parent(node.getParent());
            std::cout << "  Parent: "
                      << (parent.isNull() ? std::string("none")
                                          : parent.getObjectHandle().unparse())
                      << '\n';
            node = parent;
        }
        std::cout << "  Fully qualified name: " << ffh.getFullyQualifiedName() << '\n';
        std::cout << "  Partial name: " << ffh.getPartialName() << '\n';
        std::cout << "  Alternative name: " << ffh.getAlternativeName() << '\n';
        std::cout << "  Mapping name: " << ffh.getMappingName() << '\n';
        std::cout << "  Field type: " << ffh.getFieldType() << '\n';
        std::cout << "  Value: " << ffh.getValue().unparse() << '\n';
        std::cout << "  Value as string: " << ffh.getValueAsString() << '\n';
        std::cout << "  Default value: " << ffh.getDefaultValue().unparse() << '\n';
        std::cout << "  Default value as string: " << ffh.getDefaultValueAsString() << '\n';
        std::cout << "  Default appearance: " << ffh.getDefaultAppearance() << '\n';
        std::cout << "  Quadding: " << ffh.getQuadding() << '\n';
        std::vector<QPDFAnnotationObjectHelper> annotations = afdh.getAnnotationsForField(ffh);
        for (auto& aoh: annotations) {
            std::cout << "  Annotation: " << aoh.getObjectHandle().unparse() << '\n';
        }
    }
    std::cout << "iterating over annotations per page\n";
    for (auto& page: QPDFPageDocumentHelper(pdf).getAllPages()) {
        std::cout << "Page: " << page.getObjectHandle().unparse() << '\n';
        for (auto& ah: afdh.getWidgetAnnotationsForPage(page)) {
            std::cout << "  Annotation: " << ah.getObjectHandle().unparse() << '\n';
            std::cout << "    Field: "
                      << (afdh.getFieldForAnnotation(ah).getObjectHandle().unparse()) << '\n';
            std::cout << "    Subtype: " << ah.getSubtype() << '\n';
            std::cout << "    Rect: ";
            print_rect(std::cout, ah.getRect());
            std::cout << '\n';
            std::string state = ah.getAppearanceState();
            if (!state.empty()) {
                std::cout << "    Appearance state: " << state << '\n';
            }
            std::cout << "    Appearance stream (/N): " << ah.getAppearanceStream("/N").unparse()
                      << '\n';
            std::cout << "    Appearance stream (/N, /3): "
                      << ah.getAppearanceStream("/N", "/3").unparse() << '\n';
        }
    }
}

static void
test_44(QPDF& pdf, char const* arg2)
{
    // Set form fields.
    for (auto& field: QPDFAcroFormDocumentHelper(pdf).getFormFields()) {
        QPDFObjectHandle ft = field.getInheritableFieldValue("/FT");
        if (ft.isName() && (ft.getName() == "/Tx")) {
            // \xc3\xb7 is utf-8 for U+00F7 (divided by)
            field.setV("3.14 \xc3\xb7 0");
            std::cout << "Set field value: " << field.getFullyQualifiedName() << " -> "
                      << field.getValueAsString() << '\n';
        }
    }
    QPDFWriter w(pdf, "a.pdf");
    w.setQDFMode(true);
    w.setStaticID(true);
    w.setSuppressOriginalObjectIDs(true);
    w.write();
}

static void
test_45(QPDF& pdf, char const* arg2)
{
    // Decode obfuscated files. This is here to help test with
    // files that trigger anti-virus warnings. See comments in
    // specific-bugs.test for details.
    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.write();
    if (!pdf.getWarnings().empty()) {
        exit(3);
    }
}

static void
test_46(QPDF& pdf, char const* arg2)
{
    // Test number tree. This test is crafted to work with
    // number-tree.pdf
    QPDFObjectHandle qtest = pdf.getTrailer().getKey("/QTest");
    QPDFNumberTreeObjectHelper ntoh(qtest, pdf);
    for (auto& iter: ntoh) {
        std::cout << iter.first << " " << iter.second.getStringValue() << '\n';
    }
    QPDFNumberTreeObjectHelper::idx_map ntoh_map = ntoh.getAsMap();
    for (auto& iter: ntoh_map) {
        std::cout << iter.first << " " << iter.second.getStringValue() << '\n';
    }
    assert(1 == ntoh.getMin());
    assert(29 == ntoh.getMax());
    assert(ntoh.hasIndex(6));
    assert(!ntoh.hasIndex(500));
    QPDFObjectHandle oh;
    assert(!ntoh.findObject(4, oh));
    assert(ntoh.findObject(3, oh));
    assert("three" == oh.getStringValue());
    QPDFNumberTreeObjectHelper::numtree_number offset = 0;
    assert(!ntoh.findObjectAtOrBelow(0, oh, offset));
    assert(ntoh.findObjectAtOrBelow(8, oh, offset));
    assert("six" == oh.getStringValue());
    assert(2 == offset);

    auto new1 = QPDFNumberTreeObjectHelper::newEmpty(pdf);
    auto iter1 = new1.begin();
    assert(iter1 == new1.end());
    ++iter1;
    assert(iter1 == new1.end());
    --iter1;
    assert(iter1 == new1.end());
    new1.insert(1, QPDFObjectHandle::newString("1"));
    ++iter1;
    assert((*iter1).first == 1); // exercise operator* explicitly
    auto& iter1_val = *iter1;
    --iter1;
    assert(iter1 == new1.end());
    --iter1;
    assert(iter1->first == 1);
    assert(iter1_val.first == 1);
    new1.insert(2, QPDFObjectHandle::newString("2"));
    ++iter1;
    assert(iter1->first == 2);
    assert(iter1_val.first == 2);
    ++iter1;
    assert(iter1 == new1.end());
    assert(!iter1_val.second);
    ++iter1;
    assert(iter1->first == 1);
    --iter1;
    assert(iter1 == new1.end());
    --iter1;
    assert(iter1->first == 2);

    std::cout << "insertAfter" << '\n';
    auto new2 = QPDFNumberTreeObjectHelper::newEmpty(pdf);
    auto iter2 = new2.begin();
    assert(iter2 == new2.end());
    iter2.insertAfter(3, QPDFObjectHandle::newString("3!"));
    assert(iter2->first == 3);
    iter2.insertAfter(4, QPDFObjectHandle::newString("4!"));
    assert(iter2->first == 4);
    for (auto& i: new2) {
        std::cout << i.first << " " << i.second.unparse() << '\n';
    }

    std::cout << "/Bad1" << '\n';
    auto bad1 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Bad1"), pdf);
    assert(bad1.begin() == bad1.end());
    assert(bad1.last() == bad1.end());

    std::cout << "/Bad2" << '\n';
    auto bad2 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Bad2"), pdf);
    for (auto& i: bad2) {
        std::cout << i.first << " " << i.second.unparse() << '\n';
    }

    std::vector<std::string> empties = {"/Empty1", "/Empty2"};
    for (auto const& k: empties) {
        std::cout << k << '\n';
        auto empty = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey(k), pdf);
        assert(empty.begin() == empty.end());
        assert(empty.last() == empty.end());
        auto i = empty.insert(5, QPDFObjectHandle::newString("5"));
        assert(i->first == 5);
        assert(i->second.getStringValue() == "5");
        assert(empty.begin()->first == 5);
        assert(empty.last()->first == 5);
        assert(empty.begin()->second.getStringValue() == "5");
        i = empty.insert(5, QPDFObjectHandle::newString("5+"));
        assert(i->first == 5);
        assert(i->second.getStringValue() == "5+");
        assert(empty.begin()->second.getStringValue() == "5+");
        i = empty.insert(6, QPDFObjectHandle::newString("6"));
        assert(i->first == 6);
        assert(i->second.getStringValue() == "6");
        assert(empty.begin()->second.getStringValue() == "5+");
        assert(empty.last()->first == 6);
        assert(empty.last()->second.getStringValue() == "6");
    }
    std::cout << "Insert into invalid" << '\n';
    auto invalid1 = QPDFNumberTreeObjectHelper(QPDFObjectHandle::newDictionary(), pdf);
    try {
        invalid1.insert(1, QPDFObjectHandle::newNull());
    } catch (QPDFExc& e) {
        std::cout << e.what() << '\n';
    }

    std::cout << "/Bad3, no repair" << '\n';
    auto bad3_oh = pdf.getTrailer().getKey("/Bad3");
    auto bad3 = QPDFNumberTreeObjectHelper(bad3_oh, pdf, false);
    for (auto& i: bad3) {
        std::cout << i.first << " " << i.second.unparse() << '\n';
    }
    assert(!bad3_oh.getKey("/Kids").getArrayItem(0).isIndirect());

    std::cout << "/Bad3, repair" << '\n';
    bad3 = QPDFNumberTreeObjectHelper(bad3_oh, pdf, true);
    for (auto& i: bad3) {
        std::cout << i.first << " " << i.second.unparse() << '\n';
    }
    assert(bad3_oh.getKey("/Kids").getArrayItem(0).isIndirect());

    std::cout << "/Bad4 -- missing limits" << '\n';
    auto bad4 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Bad4"), pdf);
    bad4.insert(5, QPDFObjectHandle::newString("5"));
    for (auto& i: bad4) {
        std::cout << i.first << " " << i.second.unparse() << '\n';
    }

    std::cout << "/Bad5 -- limit errors" << '\n';
    auto bad5 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Bad5"), pdf);
    assert(bad5.find(10) == bad5.end());
}

static void
test_47(QPDF& pdf, char const* arg2)
{
    // Test page labels.
    auto& pldh = QPDFPageLabelDocumentHelper::get(pdf);
    long long npages = pdf.getRoot().getKey("/Pages").getKey("/Count").getIntValue();
    std::vector<QPDFObjectHandle> labels;
    pldh.getLabelsForPageRange(0, npages - 1, 1, labels);
    assert(labels.size() % 2 == 0);
    for (size_t i = 0; i < labels.size(); i += 2) {
        std::cout << labels.at(i).getIntValue() << " " << labels.at(i + 1).unparse() << '\n';
    }
}

static void
test_48(QPDF& pdf, char const* arg2)
{
    // Test name tree. This test is crafted to work with
    // name-tree.pdf
    QPDFObjectHandle qtest = pdf.getTrailer().getKey("/QTest");
    QPDFNameTreeObjectHelper ntoh(qtest, pdf);
    for (auto& iter: ntoh) {
        std::cout << iter.first << " -> " << iter.second.getStringValue() << '\n';
    }
    std::map<std::string, QPDFObjectHandle> ntoh_map = ntoh.getAsMap();
    for (auto& iter: ntoh_map) {
        std::cout << iter.first << " -> " << iter.second.getStringValue() << '\n';
    }
    assert(ntoh.hasName("11 elephant"));
    assert(ntoh.hasName("07 sev\xe2\x80\xa2n"));
    assert(!ntoh.hasName("potato"));
    QPDFObjectHandle oh;
    assert(!ntoh.findObject("potato", oh));
    assert(ntoh.findObject("07 sev\xe2\x80\xa2n", oh));
    assert("seven!" == oh.getStringValue());
    auto last = ntoh.last();
    assert(last->first == "29 twenty-nine");
    assert(last->second.getUTF8Value() == "twenty-nine!");

    auto new1 = QPDFNameTreeObjectHelper::newEmpty(pdf);
    auto iter1 = new1.begin();
    assert(iter1 == new1.end());
    ++iter1;
    assert(iter1 == new1.end());
    --iter1;
    assert(iter1 == new1.end());
    new1.insert("1", QPDFObjectHandle::newString("1"));
    ++iter1;
    assert(iter1->first == "1");
    auto& iter1_val = *iter1;
    --iter1;
    assert(iter1 == new1.end());
    --iter1;
    assert(iter1->first == "1");
    assert(iter1_val.first == "1");
    new1.insert("2", QPDFObjectHandle::newString("2"));
    ++iter1;
    assert(iter1->first == "2");
    assert(iter1_val.first == "2");
    ++iter1;
    assert(iter1 == new1.end());
    assert(!iter1_val.second);
    ++iter1;
    assert(iter1->first == "1");
    --iter1;
    assert(iter1 == new1.end());
    --iter1;
    assert(iter1->first == "2");

    std::cout << "insertAfter" << '\n';
    auto new2 = QPDFNameTreeObjectHelper::newEmpty(pdf);
    auto iter2 = new2.begin();
    assert(iter2 == new2.end());
    iter2.insertAfter("3", QPDFObjectHandle::newString("3!"));
    assert(iter2->first == "3");
    iter2.insertAfter("4", QPDFObjectHandle::newString("4!"));
    assert(iter2->first == "4");
    for (auto& i: new2) {
        std::cout << i.first << " " << i.second.unparse() << '\n';
    }

    std::vector<std::string> empties = {"/Empty1", "/Empty2"};
    for (auto const& k: empties) {
        std::cout << k << '\n';
        auto empty = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey(k), pdf);
        assert(empty.begin() == empty.end());
        assert(empty.last() == empty.end());
        auto i = empty.insert("five", QPDFObjectHandle::newString("5"));
        assert(i->first == "five");
        assert(i->second.getStringValue() == "5");
        assert(empty.begin()->first == "five");
        assert(empty.last()->first == "five");
        assert(empty.begin()->second.getStringValue() == "5");
        i = empty.insert("five", QPDFObjectHandle::newString("5+"));
        assert(i->first == "five");
        assert(i->second.getStringValue() == "5+");
        assert(empty.begin()->second.getStringValue() == "5+");
        i = empty.insert("six", QPDFObjectHandle::newString("6"));
        assert(i->first == "six");
        assert(i->second.getStringValue() == "6");
        assert(empty.begin()->second.getStringValue() == "5+");
        assert(empty.last()->first == "six");
        assert(empty.last()->second.getStringValue() == "6");
    }

    std::cout << "/Bad1 -- wrong key type" << '\n';
    auto bad1 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad1"), pdf);
    assert(bad1.find("G", true)->first == "A");
    for (auto const& i: bad1) {
        std::cout << i.first << '\n';
    }

    std::cout << "/Bad2 -- invalid kid" << '\n';
    auto bad2 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad2"), pdf);
    assert(bad2.find("G", true)->first == "B");
    for (auto const& i: bad2) {
        std::cout << i.first << '\n';
    }

    std::cout << "/Bad3 -- invalid kid" << '\n';
    auto bad3 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad3"), pdf);
    assert(bad3.find("G", true) == bad3.end());

    std::cout << "/Bad4 -- invalid kid" << '\n';
    auto bad4 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad4"), pdf);
    assert(bad4.find("F", true)->first == "C");
    for (auto const& i: bad4) {
        std::cout << i.first << '\n';
    }

    std::cout << "/Bad5 -- loop in find" << '\n';
    auto bad5 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad5"), pdf);
    assert(bad5.find("F", true)->first == "D");

    std::cout << "/Bad6 -- bad limits" << '\n';
    auto bad6 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad6"), pdf);
    assert(bad6.insert("H", QPDFObjectHandle::newNull())->first == "H");
}

static void
test_49(QPDF& pdf, char const* arg2)
{
    // Outlines
    QPDFOutlineDocumentHelper odh(pdf);
    int pageno = 0;
    for (auto& page: QPDFPageDocumentHelper(pdf).getAllPages()) {
        auto outlines = odh.getOutlinesForPage(page.getObjectHandle().getObjGen());
        for (auto& ol: outlines) {
            std::cout << "page " << pageno << ": " << ol.getTitle() << " -> "
                      << ol.getDest().unparseResolved() << '\n';
        }
        ++pageno;
    }
}

static void
test_50(QPDF& pdf, char const* arg2)
{
    // Test dictionary merge. This test is crafted to work with
    // merge-dict.pdf
    QPDFObjectHandle d1 = pdf.getTrailer().getKey("/Dict1");
    QPDFObjectHandle d2 = pdf.getTrailer().getKey("/Dict2");
    d1.mergeResources(d2);
    std::cout << d1.getJSON(JSON::LATEST).unparse() << '\n';
    // Top-level type mismatch
    d1.mergeResources(d2.getKey("/k1"));
    for (auto const& name: d1.getResourceNames()) {
        std::cout << name << '\n';
    }
}

static void
test_51(QPDF& pdf, char const* arg2)
{
    // Test radio button and checkbox field setting. The input
    // files must have radios button called r1 and r2 and
    // checkboxes called checkbox1 and checkbox2. The files
    // button-set*.pdf are designed for this test case.
    QPDFObjectHandle acroform = pdf.getRoot().getKey("/AcroForm");
    QPDFObjectHandle fields = acroform.getKey("/Fields");
    int nitems = fields.getArrayNItems();
    for (int i = 0; i < nitems; ++i) {
        QPDFObjectHandle field = fields.getArrayItem(i);
        QPDFObjectHandle T = field.getKey("/T");
        if (!T.isString()) {
            continue;
        }
        std::string Tval = T.getUTF8Value();
        if (Tval == "r1") {
            std::cout << "setting r1 via parent\n";
            QPDFFormFieldObjectHelper foh(field);
            foh.setV(QPDFObjectHandle::newName("/2"));
        } else if (Tval == "r2") {
            std::cout << "setting r2 via child\n";
            field = field.getKey("/Kids").getArrayItem(1);
            QPDFFormFieldObjectHelper foh(field);
            foh.setV(QPDFObjectHandle::newName("/3"));
        } else if (Tval == "checkbox1") {
            std::cout << "turning checkbox1 on\n";
            QPDFFormFieldObjectHelper foh(field);
            // The value that eventually gets set is based on what's allowed in /N and may not match
            // this value.
            foh.setV(QPDFObjectHandle::newName("/Sure"));
        } else if (Tval == "checkbox2") {
            std::cout << "turning checkbox2 off\n";
            QPDFFormFieldObjectHelper foh(field);
            foh.setV(QPDFObjectHandle::newName("/Off"));
        }
    }
    QPDFWriter w(pdf, "a.pdf");
    w.setQDFMode(true);
    w.setStaticID(true);
    w.write();
}

static void
test_52(QPDF& pdf, char const* arg2)
{
    // This test just sets a field value for appearance stream
    // generating testing.
    QPDFObjectHandle acroform = pdf.getRoot().getKey("/AcroForm");
    QPDFObjectHandle fields = acroform.getKey("/Fields");
    int nitems = fields.getArrayNItems();
    for (int i = 0; i < nitems; ++i) {
        QPDFObjectHandle field = fields.getArrayItem(i);
        QPDFObjectHandle T = field.getKey("/T");
        if (!T.isString()) {
            continue;
        }
        std::string Tval = T.getUTF8Value();
        if (Tval == "list1") {
            std::cout << "setting list1 value\n";
            QPDFFormFieldObjectHelper foh(field);
            foh.setV(QPDFObjectHandle::newString(arg2));
        }
    }
    QPDFWriter w(pdf, "a.pdf");
    w.write();
}

static void
test_53(QPDF& pdf, char const* arg2)
{
    // Test get all objects and dangling ref handling
    QPDFObjectHandle root = pdf.getRoot();
    auto new_obj = pdf.makeIndirectObject(QPDFObjectHandle::newString("potato"));
    root.replaceKey("/Q1", new_obj);
    std::cout << "new object: " << new_obj.unparse() << '\n';
    std::cout << "all objects" << '\n';
    for (auto& obj: pdf.getAllObjects()) {
        std::cout << obj.unparse() << '\n';
    }

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setPreserveUnreferencedObjects(true);
    w.write();
}

static void
test_54(QPDF& pdf, char const* arg2)
{
    // Test getFinalVersion. This must be invoked with a file
    // whose final version is not 1.5.
    QPDFWriter w(pdf, "a.pdf");
    assert(pdf.getPDFVersion() != "1.5");
    w.setObjectStreamMode(qpdf_o_generate);
    if (w.getFinalVersion() != "1.5") {
        std::cout << "oops: " << w.getFinalVersion() << '\n';
    }
}

static void
test_55(QPDF& pdf, char const* arg2)
{
    // Form XObjects
    std::vector<QPDFPageObjectHelper> pages = QPDFPageDocumentHelper(pdf).getAllPages();
    QPDFObjectHandle qtest = QPDFObjectHandle::newArray();
    for (auto& ph: pages) {
        qtest.appendItem(ph.getFormXObjectForPage());
        qtest.appendItem(ph.getFormXObjectForPage(false));
    }
    pdf.getTrailer().replaceKey("/QTest", qtest);
    QPDFWriter w(pdf, "a.pdf");
    w.setQDFMode(true);
    w.setStaticID(true);
    w.write();
}

static void
test_56_59(
    QPDF& pdf, char const* arg2, bool handle_from_transformation, bool invert_to_transformation)
{
    // red pages are from pdf, blue pages are from pdf2
    // red pages always have stated rotation absolutely
    // 56: blue pages are overlaid exactly on top of red pages
    // 57: blue pages have stated rotation relative to red pages
    // 58: blue pages have no rotation (absolutely upright)
    // 59: blue pages have stated rotation absolutely

    // Placing form XObjects
    assert(arg2);
    QPDF pdf2;
    pdf2.processFile(arg2);

    std::vector<QPDFPageObjectHelper> pages1 = QPDFPageDocumentHelper(pdf).getAllPages();
    std::vector<QPDFPageObjectHelper> pages2 = QPDFPageDocumentHelper(pdf2).getAllPages();
    size_t npages = (pages1.size() < pages2.size() ? pages1.size() : pages2.size());
    for (size_t i = 0; i < npages; ++i) {
        QPDFPageObjectHelper& ph1 = pages1.at(i);
        QPDFPageObjectHelper& ph2 = pages2.at(i);
        QPDFObjectHandle fo =
            pdf.copyForeignObject(ph2.getFormXObjectForPage(handle_from_transformation));
        int min_suffix = 1;
        QPDFObjectHandle resources = ph1.getAttribute("/Resources", true);
        std::string name = resources.getUniqueResourceName("/Fx", min_suffix);
        std::string content = ph1.placeFormXObject(
            fo, name, ph1.getTrimBox().getArrayAsRectangle(), invert_to_transformation);
        if (!content.empty()) {
            resources.mergeResources(QPDFObjectHandle::parse("<< /XObject << >> >>"));
            resources.getKey("/XObject").replaceKey(name, fo);
            ph1.addPageContents(QPDFObjectHandle::newStream(&pdf, "q\n"), true);
            ph1.addPageContents(QPDFObjectHandle::newStream(&pdf, "\nQ\n" + content), false);
        }
    }
    QPDFWriter w(pdf, "a.pdf");
    w.setQDFMode(true);
    w.setStaticID(true);
    w.write();
}

static void
test_56(QPDF& pdf, char const* arg2)
{
    test_56_59(pdf, arg2, false, false);
}

static void
test_57(QPDF& pdf, char const* arg2)
{
    test_56_59(pdf, arg2, true, false);
}

static void
test_58(QPDF& pdf, char const* arg2)
{
    test_56_59(pdf, arg2, false, true);
}

static void
test_59(QPDF& pdf, char const* arg2)
{
    test_56_59(pdf, arg2, true, true);
}

static void
test_60(QPDF& pdf, char const* arg2)
{
    // Boundary condition testing for getUniqueResourceName;
    // additional testing of mergeResources with conflict
    // detection
    QPDFObjectHandle r1 = QPDFObjectHandle::newDictionary();
    int min_suffix = 1;
    for (int i = 1; i < 3; ++i) {
        std::string name = r1.getUniqueResourceName("/Quack", min_suffix);
        r1.mergeResources(QPDFObjectHandle::parse("<< /Z << >> >>"));
        r1.getKey("/Z").replaceKey(name, QPDFObjectHandle::newString("moo"));
    }
    auto make_resource =
        [&](QPDFObjectHandle& dict, std::string const& key, std::string const& str) {
            auto o1 = QPDFObjectHandle::newArray();
            o1.appendItem(QPDFObjectHandle::newString(str));
            dict.replaceKey(key, pdf.makeIndirectObject(o1));
        };

    auto z = r1.getKey("/Z");
    r1.replaceKey("/Y", QPDFObjectHandle::newDictionary());
    auto y = r1.getKey("/Y");
    make_resource(z, "/F1", "r1.Z.F1");
    make_resource(z, "/F2", "r1.Z.F2");
    make_resource(y, "/F2", "r1.Y.F2");
    make_resource(y, "/F3", "r1.Y.F3");
    QPDFObjectHandle r2 = QPDFObjectHandle::parse("<< /Z << >> /Y << >> >>");
    z = r2.getKey("/Z");
    y = r2.getKey("/Y");
    make_resource(z, "/F2", "r2.Z.F2");
    make_resource(y, "/F3", "r2.Y.F3");
    make_resource(y, "/F4", "r2.Y.F4");
    // Add a direct object
    y.replaceKey("/F5", QPDFObjectHandle::newString("direct r2.Y.F5"));

    std::map<std::string, std::map<std::string, std::string>> conflicts;
    auto show_conflicts = [&](std::string const& msg) {
        std::cout << msg << '\n';
        for (auto const& i1: conflicts) {
            std::cout << i1.first << ":" << '\n';
            for (auto const& i2: i1.second) {
                std::cout << "  " << i2.first << " -> " << i2.second << '\n';
            }
        }
    };

    r1.mergeResources(r2, &conflicts);
    show_conflicts("first merge");
    auto r3 = r1.shallowCopy();
    // Merge again. The direct object gets recopied. Everything
    // else is the same.
    r1.mergeResources(r2, &conflicts);
    show_conflicts("second merge");

    // Make all resources in r2 direct. Then merge two more times.
    // We should get the one previously direct object copied one
    // time as an indirect object.
    r2.makeResourcesIndirect(pdf);
    r1.mergeResources(r2, &conflicts);
    show_conflicts("third merge");
    r1.mergeResources(r2, &conflicts);
    show_conflicts("fourth merge");

    // The only differences between /QTest and /QTest3 should be
    // the direct objects merged from r2.
    auto trailer = pdf.getTrailer();
    trailer.replaceKey("/QTest1", r1);
    trailer.replaceKey("/QTest2", r2);
    trailer.replaceKey("/QTest3", r3);
    QPDFWriter w(pdf, "a.pdf");
    w.setQDFMode(true);
    w.setStaticID(true);
    w.write();
}

static void
test_61(QPDF& pdf, char const* arg2)
{
    // Test to make sure type information is passed across shared
    // library boundaries. This includes exception handling, dynamic
    // cast, and subclassing.
    pdf.setAttemptRecovery(false);
    pdf.setSuppressWarnings(true);
    try {
        pdf.processMemoryFile("empty", "", 0);
    } catch (QPDFExc const&) {
        std::cout << "Caught QPDFExc as expected" << '\n';
    }
    try {
        QUtil::safe_fopen("/does/not/exist", "r");
    } catch (QPDFSystemError const&) {
        std::cout << "Caught QPDFSystemError as expected" << '\n';
    }
    try {
        QUtil::int_to_string_base(0, 12);
    } catch (std::logic_error const&) {
        std::cout << "Caught logic_error as expected" << '\n';
    }
    try {
        QUtil::toUTF8(0xffffffff);
    } catch (std::runtime_error const&) {
        std::cout << "Caught runtime_error as expected" << '\n';
    }

    // Spot check RTTI for dynamic cast. We intend to have pipelines
    // and input sources be testable, but adding comprehensive tests
    // for everything doesn't add value as it wouldn't catch
    // forgetting QPDF_DLL_CLASS on a new subclass.
    BufferInputSource b("x", "y");
    InputSource* is = &b;
    assert(dynamic_cast<BufferInputSource*>(is) != nullptr);
    Pl_Discard pd;
    Pipeline* p = &pd;
    assert(dynamic_cast<Pl_Discard*>(p) != nullptr);

    // For some reason, QPDFNameTreeObjectHelper's vtable seems to
    // like to not make it into the shared library with mingw. Try to
    // make sure this is really fixed.
    QPDFNameTreeObjectHelper* n = new ExtendNameTree(QPDFObjectHandle::newNull(), pdf);
    delete n;
}

static void
test_62(QPDF& pdf, char const* arg2)
{
    // Was test int size checks - Moved to libtests/objects.
    // Test Pipeline methods
    std::string out;
    Pl_String pl("", nullptr, out);
    unsigned short us = 1;
    unsigned int ui = 2;
    unsigned long long ull = 3;
    long l = 4;
    short s = 5;
    pl << us << ui << ull << l << s;
    assert(out == "12345");
}

static void
test_63(QPDF& pdf, char const* arg2)
{
    QPDFWriter w(pdf);
    // Exercise setting encryption parameters before setting the
    // output filename. The previous bug does not happen if static
    // or deterministic ID is used because the filename is not
    // used as part of the input data for ID generation in those
    // cases.
    w.setR6EncryptionParameters("u", "o", true, true, true, true, true, true, qpdf_r3p_full, true);
    w.setOutputFilename("a.pdf");
    w.write();
}

static void
test_64_67(QPDF& pdf, char const* arg2, bool allow_shrink, bool allow_expand)
{
    // Overlay file2 on file1.
    // 64: allow neither shrink nor shrink
    // 65: allow shrink but not expand
    // 66: allow expand but not shrink
    // 67: allow both shrink and expand

    // Placing form XObjects: expand, shrink
    assert(arg2);
    QPDF pdf2;
    pdf2.processFile(arg2);

    std::vector<QPDFPageObjectHelper> pages1 = QPDFPageDocumentHelper(pdf).getAllPages();
    std::vector<QPDFPageObjectHelper> pages2 = QPDFPageDocumentHelper(pdf2).getAllPages();
    size_t npages = (pages1.size() < pages2.size() ? pages1.size() : pages2.size());
    for (size_t i = 0; i < npages; ++i) {
        QPDFPageObjectHelper& ph1 = pages1.at(i);
        QPDFPageObjectHelper& ph2 = pages2.at(i);
        QPDFObjectHandle fo = pdf.copyForeignObject(ph2.getFormXObjectForPage());
        int min_suffix = 1;
        QPDFObjectHandle resources = ph1.getAttribute("/Resources", true);
        std::string name = resources.getUniqueResourceName("/Fx", min_suffix);
        std::string content = ph1.placeFormXObject(
            fo, name, ph1.getTrimBox().getArrayAsRectangle(), false, allow_shrink, allow_expand);
        if (!content.empty()) {
            resources.mergeResources(QPDFObjectHandle::parse("<< /XObject << >> >>"));
            resources.getKey("/XObject").replaceKey(name, fo);
            ph1.addPageContents(QPDFObjectHandle::newStream(&pdf, "q\n"), true);
            ph1.addPageContents(QPDFObjectHandle::newStream(&pdf, "\nQ\n" + content), false);
        }
    }
    QPDFWriter w(pdf, "a.pdf");
    w.setQDFMode(true);
    w.setStaticID(true);
    w.write();
}

static void
test_64(QPDF& pdf, char const* arg2)
{
    test_64_67(pdf, arg2, false, false);
}

static void
test_65(QPDF& pdf, char const* arg2)
{
    test_64_67(pdf, arg2, true, false);
}

static void
test_66(QPDF& pdf, char const* arg2)
{
    test_64_67(pdf, arg2, false, true);
}

static void
test_67(QPDF& pdf, char const* arg2)
{
    test_64_67(pdf, arg2, true, true);
}

static void
test_68(QPDF& pdf, char const* arg2)
{
    QPDFObjectHandle root = pdf.getRoot();
    QPDFObjectHandle qstream = root.getKey("/QStream");
    try {
        qstream.getStreamData();
        std::cout << "oops -- didn't throw" << '\n';
    } catch (std::exception& e) {
        std::cout << "get unfilterable stream: " << e.what() << '\n';
    }
    std::shared_ptr<Buffer> b1 = qstream.getStreamData(qpdf_dl_all);
    if ((b1->getSize() > 10) && (memcmp(b1->getBuffer(), "wwwwwwwww", 9) == 0)) {
        std::cout << "filtered stream data okay" << '\n';
    }
    std::shared_ptr<Buffer> b2 = qstream.getRawStreamData();
    if ((b2->getSize() > 10) &&
        (memcmp(b2->getBuffer(), "\xff\xd8\xff\xe0\x00\x10\x4a\x46\x49\x46", 10) == 0)) {
        std::cout << "raw stream data okay" << '\n';
    }
}

static void
test_69(QPDF& pdf, char const* arg2)
{
    pdf.setImmediateCopyFrom(true);
    auto pages = pdf.getAllPages();
    for (size_t i = 0; i < pages.size(); ++i) {
        QPDF out;
        out.emptyPDF();
        out.addPage(pages.at(i), false);
        std::string outname = std::string("auto-") + QUtil::uint_to_string(i) + ".pdf";
        QPDFWriter w(out, outname.c_str());
        w.setStaticID(true);
        w.write();
    }
}

static void
test_70(QPDF& pdf, char const* arg2)
{
    auto trailer = pdf.getTrailer();
    trailer.getKey("/S1").setFilterOnWrite(false);
    trailer.getKey("/S2").setFilterOnWrite(false);
    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setDecodeLevel(qpdf_dl_specialized);
    w.write();
}

static void
test_71(QPDF& pdf, char const* arg2)
{
    auto show = [](QPDFObjectHandle& obj, QPDFObjectHandle& xobj_dict, std::string const& key) {
        std::cout << xobj_dict.unparse() << " -> " << key << " -> " << obj.unparse() << '\n';
    };
    auto page = QPDFPageDocumentHelper(pdf).getAllPages().at(0);
    std::cout << "--- recursive, all ---" << '\n';
    page.forEachXObject(true, show);
    std::cout << "--- non-recursive, all ---" << '\n';
    page.forEachXObject(false, show);
    std::cout << "--- recursive, images ---" << '\n';
    page.forEachImage(true, show);
    std::cout << "--- non-recursive, images ---" << '\n';
    page.forEachImage(false, show);
    std::cout << "--- recursive, form XObjects ---" << '\n';
    page.forEachFormXObject(true, show);
    std::cout << "--- non-recursive, form XObjects ---" << '\n';
    page.forEachFormXObject(false, show);
    auto fx1 = QPDFPageObjectHelper(
        page.getObjectHandle().getKey("/Resources").getKey("/XObject").getKey("/Fx1"));
    std::cout << "--- recursive, all, from fx1 ---" << '\n';
    fx1.forEachXObject(true, show);
    std::cout << "--- non-recursive, all, from fx1 ---" << '\n';
    fx1.forEachXObject(false, show);
    std::cout << "--- get images, page ---" << '\n';
    for (auto& i: page.getImages()) {
        std::cout << i.first << " -> " << i.second.unparse() << '\n';
    }
    std::cout << "--- get images, fx ---" << '\n';
    for (auto& i: fx1.getImages()) {
        std::cout << i.first << " -> " << i.second.unparse() << '\n';
    }
    std::cout << "--- get form XObjects, page ---" << '\n';
    for (auto& i: page.getFormXObjects()) {
        std::cout << i.first << " -> " << i.second.unparse() << '\n';
    }
    std::cout << "--- get form XObjects, fx ---" << '\n';
    for (auto& i: fx1.getFormXObjects()) {
        std::cout << i.first << " -> " << i.second.unparse() << '\n';
    }
}

static void
test_72(QPDF& pdf, char const* arg2)
{
    // Call some QPDFPageObjectHelper methods on form XObjects.
    auto page = QPDFPageDocumentHelper(pdf).getAllPages().at(0);
    auto fx1 = QPDFPageObjectHelper(
        page.getObjectHandle().getKey("/Resources").getKey("/XObject").getKey("/Fx1"));
    std::cout << "--- parseContents ---" << '\n';
    ParserCallbacks cb;
    fx1.parseContents(&cb);
    // Do this once with addContentTokenFilter and once with
    // addTokenFilter to show that they are the same and to ensure
    // that addTokenFilter is directly exercised in testing.
    for (int i = 0; i < 2; i++) {
        Pl_Buffer b("buffer");
        if (i == 0) {
            fx1.addContentTokenFilter(
                std::shared_ptr<QPDFObjectHandle::TokenFilter>(new TokenFilter()));
        } else {
            fx1.getObjectHandle().addTokenFilter(
                std::shared_ptr<QPDFObjectHandle::TokenFilter>(new TokenFilter()));
        }
        fx1.pipeContents(&b);
        std::unique_ptr<Buffer> buf(b.getBuffer());
        std::string s(reinterpret_cast<char const*>(buf->getBuffer()), buf->getSize());
        assert(s.find("/bye") != std::string::npos);
    }
}

static void
test_73(QPDF& pdf, char const* arg2)
{
    try {
        QPDF pdf2;
        pdf2.getRoot();
    } catch (std::exception& e) {
        std::cerr << "getRoot: " << e.what() << '\n';
    }

    pdf.closeInputSource();
    pdf.getObject(4, 0).unparseResolved();
}

static void
test_74(QPDF& pdf, char const* arg2)
{
    // This test is crafted to work with split-nntree.pdf
    std::cout << "/Split1" << '\n';
    auto split1 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Split1"), pdf);
    split1.setSplitThreshold(4);
    auto check_split1 = [&split1](int k) {
        auto i = split1.insert(k, QPDFObjectHandle::newString(QUtil::int_to_string(k)));
        assert(i->first == k);
    };
    check_split1(15);
    check_split1(35);
    check_split1(125);
    for (auto const& i: split1) {
        std::cout << i.first << '\n';
    }

    std::cout << "/Split2" << '\n';
    auto split2 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Split2"), pdf);
    split2.setSplitThreshold(4);
    auto check_split2 = [](QPDFNameTreeObjectHelper& noh, std::string const& k) {
        auto i = noh.insert(k, QPDFObjectHandle::newUnicodeString(k));
        assert(i->first == k);
    };
    check_split2(split2, "C");
    for (auto const& i: split2) {
        std::cout << i.first << '\n';
    }

    std::cout << "/Split3" << '\n';
    auto split3 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Split3"), pdf);
    split3.setSplitThreshold(4);
    check_split2(split3, "P");
    check_split2(split3, "\xcf\x80");
    for (auto& i: split3) {
        std::cout << i.first << " " << i.second.unparse() << '\n';
    }

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setQDFMode(true);
    w.write();
}

static void
test_75(QPDF& pdf, char const* arg2)
{
    // This test is crafted to work with erase-nntree.pdf
    auto erase1 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Erase1"), pdf);
    QPDFObjectHandle value;
    assert(!erase1.remove("1X"));
    assert(erase1.remove("1C", &value));
    assert(value.getUTF8Value() == "c");
    auto iter1 = erase1.find("1B");
    iter1.remove();
    assert(iter1->first == "1D");
    iter1.remove();
    assert(iter1 == erase1.end());
    --iter1;
    assert(iter1->first == "1A");
    iter1.remove();
    assert(iter1 == erase1.end());

    auto erase2_oh = pdf.getTrailer().getKey("/Erase2");
    auto erase2 = QPDFNumberTreeObjectHelper(erase2_oh, pdf);
    auto iter2 = erase2.find(250);
    iter2.remove();
    assert(iter2 == erase2.end());
    --iter2;
    assert(iter2->first == 240);
    auto k1 = erase2_oh.getKey("/Kids").getArrayItem(1);
    auto l1 = k1.getKey("/Limits");
    assert(l1.getArrayItem(0).getIntValue() == 230);
    assert(l1.getArrayItem(1).getIntValue() == 240);
    iter2 = erase2.find(210);
    iter2.remove();
    assert(iter2->first == 220);
    k1 = erase2_oh.getKey("/Kids").getArrayItem(0);
    l1 = k1.getKey("/Limits");
    assert(l1.getArrayItem(0).getIntValue() == 220);
    assert(l1.getArrayItem(1).getIntValue() == 220);
    k1 = k1.getKey("/Kids");
    assert(k1.getArrayNItems() == 1);

    auto erase3 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Erase3"), pdf);
    iter2 = erase3.find(320);
    iter2.remove();
    assert(iter2 == erase3.end());
    erase3.remove(310);
    assert(erase3.begin() == erase3.end());

    auto erase4 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Erase4"), pdf);
    iter2 = erase4.find(420);
    iter2.remove();
    assert(iter2->first == 430);

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setQDFMode(true);
    w.write();
}

static void
test_76(QPDF& pdf, char const* arg2)
{
    // Embedded files. arg2 is a file to attach. Hard-code the
    // mime type and file name for test purposes.
    auto& efdh = QPDFEmbeddedFileDocumentHelper::get(pdf);
    auto fs1 = QPDFFileSpecObjectHelper::createFileSpec(pdf, "att1.txt", arg2);
    fs1.setDescription("some text");
    auto efs1 = QPDFEFStreamObjectHelper(fs1.getEmbeddedFileStream());
    efs1.setSubtype("text/plain")
        .setCreationDate("D:20210207191121-05'00'")
        .setModDate("D:20210208001122Z");
    efdh.replaceEmbeddedFile("att1", fs1);
    auto efs2 = QPDFEFStreamObjectHelper::createEFStream(pdf, "from string");
    efs2.setSubtype("text/plain");
    Pl_Buffer p("buffer");
    // exercise Pipeline::operator<<(std::string const&)
    p << std::string("from buffer");
    p.finish();
    auto efs3 = QPDFEFStreamObjectHelper::createEFStream(pdf, p.getBufferSharedPointer());
    efs3.setSubtype("text/plain");
    efdh.replaceEmbeddedFile(
        "att2", QPDFFileSpecObjectHelper::createFileSpec(pdf, "att2.txt", efs2));
    auto fs3 = QPDFFileSpecObjectHelper::createFileSpec(pdf, "att3.txt", efs3);
    efdh.replaceEmbeddedFile("att3", fs3);
    fs3.setFilename("\xcf\x80.txt");
    assert(fs3.getFilename() == "\xcf\x80.txt");
    fs3.setFilename("\xcf\x80.txt", "att3.txt");

    assert(efs1.getCreationDate() == "D:20210207191121-05'00'");
    assert(efs1.getModDate() == "D:20210208001122Z");
    assert(efs2.getSize() == 11);
    assert(efs2.getSubtype() == "text/plain");
    assert(QUtil::hex_encode(efs2.getChecksum()) == "2fce9c8228e360ba9b04a1bd1bf63d6b");

    for (auto const& iter: efdh.getEmbeddedFiles()) {
        std::cout << iter.first << " -> " << iter.second->getFilename() << '\n';
    }
    assert(efdh.getEmbeddedFile("att1")->getFilename() == "att1.txt");
    assert(!efdh.getEmbeddedFile("potato"));

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setQDFMode(true);
    w.write();
}

static void
test_77(QPDF& pdf, char const* arg2)
{
    QPDFEmbeddedFileDocumentHelper efdh(pdf);
    assert(efdh.removeEmbeddedFile("att2"));
    assert(!efdh.removeEmbeddedFile("att2"));

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setQDFMode(true);
    w.write();
}

static void
test_78(QPDF& pdf, char const* arg2)
{
    // Test functional versions of replaceStreamData()

    auto f1 = [](Pipeline* p) {
        p->writeCStr("potato");
        p->finish();
    };
    auto f2 = [](Pipeline* p, bool suppress_warnings, bool will_retry) {
        std::cerr << "f2" << '\n';
        if (will_retry) {
            std::cerr << "failing" << '\n';
            return false;
        }
        if (!suppress_warnings) {
            std::cerr << "warning" << '\n';
        }
        p->writeCStr("salad");
        p->finish();
        std::cerr << "f2 done" << '\n';
        return true;
    };

    auto null = QPDFObjectHandle::newNull();
    auto s1 = QPDFObjectHandle::newStream(&pdf);
    s1.replaceStreamData(f1, null, null);
    auto s2 = QPDFObjectHandle::newStream(&pdf);
    s2.replaceStreamData(f2, null, null);
    pdf.getTrailer().replaceKey("/Streams", QPDFObjectHandle::newArray({s1, s2}));
    std::cout << "piping with warning suppression" << '\n';
    Pl_Discard d;
    s2.pipeStreamData(&d, nullptr, 0, qpdf_dl_all, true, false);

    std::cout << "writing" << '\n';
    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setQDFMode(true);
    w.write();
}

static void
test_79(QPDF& pdf, char const* arg2)
{
    // Exercise stream copier

    // Copy streams. Modify the original and make sure the copy is
    // unaffected.
    auto copies = QPDFObjectHandle::newArray();
    pdf.getTrailer().replaceKey("/Copies", copies);
    auto null = QPDFObjectHandle::newNull();

    // Get a regular stream from the file
    auto p1 = pdf.getAllPages().at(0);
    auto s1 = p1.getKey("/Contents");

    // Create a stream from a string
    auto s2 = QPDFObjectHandle::newStream(&pdf, "from string");
    // Add direct and indirect objects to the dictionary
    s2.getDict().replaceKey(
        "/Stuff",
        QPDFObjectHandle::parse(
            &pdf,
            "<< /Direct 3 /Indirect " +
                pdf.makeIndirectObject(QPDFObjectHandle::newInteger(16059)).unparse() + ">>"));
    s2.getDict().replaceKey("/Other", QPDFObjectHandle::newString("other stuff"));

    // Use a provider
    Pl_Buffer b("buffer");
    b.writeCStr("from buffer");
    b.finish();
    auto bp = b.getBufferSharedPointer();
    auto s3 = QPDFObjectHandle::newStream(&pdf, bp);

    std::vector<QPDFObjectHandle> streams = {s1, s2, s3};
    pdf.getTrailer().replaceKey("/Originals", QPDFObjectHandle::newArray(streams));

    int i = 0;
    for (auto orig: streams) {
        ++i;
        auto istr = QUtil::int_to_string(i);
        auto orig_data = orig.getStreamData();
        auto copy = orig.copyStream();
        copy.getDict().replaceKey("/Other", QPDFObjectHandle::newString("other: " + istr));
        orig.replaceStreamData("something new " + istr, null, null);
        auto copy_data = copy.getStreamData();
        assert(orig_data->getSize() == copy_data->getSize());
        assert(memcmp(orig_data->getBuffer(), copy_data->getBuffer(), orig_data->getSize()) == 0);
        copies.appendItem(copy);
    }

    QPDFWriter w(pdf, "a.pdf");
    w.setStaticID(true);
    w.setQDFMode(true);
    w.write();
}

static void
test_80(QPDF& pdf, char const* arg2)
{
    // Exercise transform/copy annotations without passing in
    // QPDFAcroFormDocumentHelper pointers. The case of passing
    // them in is sufficiently exercised by testing through the
    // qpdf CLI.

    // The main file is a file that has lots of annotations. Arg2
    // is a file to copy annotations to.

    QPDFMatrix m;
    m.translate(306, 396);
    m.scale(0.4, 0.4);
    auto page1 = pdf.getAllPages().at(0);
    auto old_annots = page1.getKey("/Annots");
    // Transform annotations and copy them back to the same page.
    std::vector<QPDFObjectHandle> new_annots;
    std::vector<QPDFObjectHandle> new_fields;
    std::set<QPDFObjGen> old_fields;
    QPDFAcroFormDocumentHelper afdh(pdf);
    // Use defaults for from_qpdf and from_afdh.
    afdh.transformAnnotations(old_annots, new_annots, new_fields, old_fields, m);
    for (auto const& annot: new_annots) {
        old_annots.appendItem(annot);
    }
    afdh.addAndRenameFormFields(new_fields);

    m = QPDFMatrix();
    m.translate(612, 0);
    m.scale(-1, 1);
    QPDF pdf2;
    pdf2.processFile(arg2);
    auto page2 = QPDFPageDocumentHelper(pdf2).getAllPages().at(0);
    page2.copyAnnotations(page1, m);

    QPDFWriter w1(pdf, "a.pdf");
    w1.setStaticID(true);
    w1.setQDFMode(true);
    w1.write();

    QPDFWriter w2(pdf2, "b.pdf");
    w2.setStaticID(true);
    w2.setQDFMode(true);
    w2.write();
}

static void
test_81(QPDF& pdf, char const* arg2)
{
    // Exercise that type errors get their own special type
    try {
        QPDFObjectHandle::newNull().getIntValue();
        assert(false);
    } catch (QPDFExc& e) {
        assert(e.getErrorCode() == qpdf_e_object);
    }
}

static void
test_82(QPDF& pdf, char const* arg2)
{
    // Exercise compound test methods QPDFObjectHandle::isNameAndEquals,
    // isDictionaryOfType and isStreamOfType
    auto name = QPDFObjectHandle::newName("/Marvin");
    auto str = QPDFObjectHandle::newString("/Marvin");
    assert(name.isNameAndEquals("/Marvin"));
    assert(!name.isNameAndEquals("Marvin"));
    assert(!str.isNameAndEquals("/Marvin"));
    auto dict = QPDFObjectHandle::parse("<</A 1 /Type /Test /Subtype /Marvin>>");
    assert(dict.isDictionaryOfType("/Test", ""));
    assert(dict.isDictionaryOfType("/Test"));
    assert(dict.isDictionaryOfType("/Test", "/Marvin"));
    assert(dict.isDictionaryOfType("", "/Marvin"));
    assert(dict.isDictionaryOfType("", ""));
    assert(!dict.isDictionaryOfType("/Test2", ""));
    assert(!dict.isDictionaryOfType("/Test2", "/Marvin"));
    assert(!dict.isDictionaryOfType("/Test", "/M"));
    assert(!name.isDictionaryOfType("", ""));
    dict = QPDFObjectHandle::parse("<</A 1 /Type null /Subtype /Marvin>>");
    assert(!dict.isDictionaryOfType("/Test"));
    dict = QPDFObjectHandle::parse("<</A 1 /Type (Test) /Subtype /Marvin>>");
    assert(!dict.isDictionaryOfType("Test"));
    dict = QPDFObjectHandle::parse("<</A 1 /Type /Test /Subtype (Marvin)>>");
    assert(!dict.isDictionaryOfType("Test"));
    dict = QPDFObjectHandle::parse("<</A 1 /Subtype /Marvin>>");
    assert(!dict.isDictionaryOfType("/Test", "Marvin"));
    auto stream = pdf.getObjectByID(1, 0);
    assert(stream.isStreamOfType("/ObjStm"));
    assert(!stream.isStreamOfType("/Test"));
    assert(!pdf.getObjectByID(2, 0).isStreamOfType("/Pages"));
    /* cSpell: ignore Blaah Blaaah Blaaaah */
    auto array = QPDFObjectHandle::parse("[/Blah /Blaah /Blaaah]");
    assert(array.isOrHasName("/Blah"));
    assert(array.isOrHasName("/Blaaah"));
    assert(!array.isOrHasName("/Blaaaah"));
    assert(array.getArrayItem(0).isOrHasName("/Blah"));
    assert(!array.getArrayItem(1).isOrHasName("/Blah"));
    array = QPDFObjectHandle::parse("[]");
    assert(!array.isOrHasName("/Blah"));
    assert(!str.isOrHasName("/Marvin"));
}

static void
test_83(QPDF& pdf, char const* arg2)
{
    // Test QPDFJob json with partial = false. For testing with
    // partial = true, we just use qpdf --job-json-file.

    QPDFJob j;
    std::shared_ptr<char> file_buf;
    size_t size;
    QUtil::read_file_into_memory(arg2, file_buf, size);
    try {
        std::cout << "calling initializeFromJson" << '\n';
        j.initializeFromJson(std::string(file_buf.get(), size));
        std::cout << "called initializeFromJson" << '\n';
    } catch (QPDFUsage& e) {
        std::cerr << "usage: " << e.what() << '\n';
    } catch (std::exception& e) {
        std::cerr << "exception: " << e.what() << '\n';
    }
}

static void
test_84(QPDF& pdf, char const* arg2)
{
    // Test QPDFJob API

    std::cout << "normal" << '\n';
    {
        QPDFJob j;
        j.config()
            ->inputFile("minimal.pdf")
            ->outputFile("a.pdf")
            ->qdf()
            ->deterministicId()
            ->objectStreams("preserve")
            ->progress()
            ->checkConfiguration();
        j.run();
        assert(j.getExitCode() == 0);
        assert(!j.hasWarnings());
        assert(j.getEncryptionStatus() == 0);
    }

    std::cout << "custom progress reporter" << '\n';
    {
        QPDFJob j;
        j.registerProgressReporter(
            [](int p) { std::cout << "custom write progress: " << p << "%" << '\n'; });
        j.config()
            ->inputFile("minimal.pdf")
            ->outputFile("a.pdf")
            ->qdf()
            ->deterministicId()
            ->objectStreams("preserve")
            ->progress()
            ->checkConfiguration();
        j.run();
        assert(j.getExitCode() == 0);
        assert(!j.hasWarnings());
        assert(j.getEncryptionStatus() == 0);
    }

    std::cout << "error caught by check" << '\n';
    try {
        QPDFJob j;
        j.config()->outputFile("a.pdf")->qdf();
        std::cout << "finished config" << '\n';
        j.checkConfiguration();
        assert(false);
    } catch (QPDFUsage& e) {
        std::cout << "usage: " << e.what() << '\n';
    }

    std::cout << "error caught by run" << '\n';
    try {
        QPDFJob j;
        j.config()->outputFile("a.pdf")->qdf();
        std::cout << "finished config" << '\n';
        j.run();
        assert(false);
    } catch (QPDFUsage& e) {
        std::cout << "usage: " << e.what() << '\n';
    }

    std::cout << "output capture" << '\n';
    std::ostringstream cout;
    std::ostringstream cerr;
    {
        QPDFJob j;
#ifdef _MSC_VER
# pragma warning(disable : 4996)
#endif
#if (defined(__GNUC__) || defined(__clang__))
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
        j.setOutputStreams(&cout, &cerr);
#if (defined(__GNUC__) || defined(__clang__))
# pragma GCC diagnostic pop
#endif
        j.config()->inputFile("bad2.pdf")->showObject("4,0")->checkConfiguration();
        std::cout << "calling run" << '\n';
        j.run();
        std::cout << "captured stdout" << '\n';
        std::cout << cout.str();
        std::cout << "captured stderr" << '\n';
        std::cout << cerr.str();
    }
}

static void
test_85(QPDF& pdf, char const* arg2)
{
    // Test QPDFObjectHandle::getValueAs... accessors

    auto oh_b = QPDFObjectHandle::newBool(false);
    auto oh_i = QPDFObjectHandle::newInteger(1);
    auto oh_i_maxplus = QPDFObjectHandle::newInteger(QIntC::to_longlong(INT_MAX) + 1LL);
    auto oh_i_umaxplus = QPDFObjectHandle::newInteger(QIntC::to_longlong(UINT_MAX) + 1LL);
    auto oh_i_minminus = QPDFObjectHandle::newInteger(QIntC::to_longlong(INT_MIN) - 1LL);
    auto oh_i_neg = QPDFObjectHandle::newInteger(-1);
    auto oh_r = QPDFObjectHandle::newReal("42.0");
    auto oh_n = QPDFObjectHandle::newName("/Test");
    auto oh_s = QPDFObjectHandle::newString("/Test");
    auto oh_o = QPDFObjectHandle::newOperator("/Test");
    auto oh_ii = QPDFObjectHandle::newInlineImage("/Test");

    bool b = true;
    assert(oh_b.getValueAsBool(b));
    assert(!b);
    assert(!oh_i.getValueAsBool(b));
    assert(!b);
    long long li = 0LL;
    assert(oh_i.getValueAsInt(li));
    assert(li == 1LL);
    assert(!oh_b.getValueAsInt(li));
    assert(li == 1LL);
    int i = 0;
    assert(oh_i.getValueAsInt(i));
    assert(i == 1);
    assert(!oh_b.getValueAsInt(i));
    assert(i == 1);
    assert(oh_i_maxplus.getValueAsInt(i));
    assert(i == INT_MAX);
    assert(oh_i_minminus.getValueAsInt(i));
    assert(i == INT_MIN);
    unsigned long long uli = 0U;
    assert(oh_i.getValueAsUInt(uli));
    assert(uli == 1u);
    assert(!oh_b.getValueAsUInt(uli));
    assert(uli == 1u);
    assert(oh_i_neg.getValueAsUInt(uli));
    assert(uli == 0u);
    unsigned int ui = 0U;
    assert(oh_i.getValueAsUInt(ui));
    assert(ui == 1u);
    assert(!oh_b.getValueAsUInt(ui));
    assert(ui == 1u);
    assert(oh_i_neg.getValueAsUInt(ui));
    assert(ui == 0u);
    assert(oh_i_umaxplus.getValueAsUInt(ui));
    assert(ui == UINT_MAX);
    std::string s = "0";
    assert(oh_r.getValueAsReal(s));
    assert(s == "42.0");
    assert(!oh_i.getValueAsReal(s));
    assert(s == "42.0");
    double num = 0.0;
    assert(oh_i.getValueAsNumber(num));
    assert(((num - 1.0) < 1e-6) && (num - 1.0 > -1e-6));
    assert(oh_r.getValueAsNumber(num));
    assert(((num - 42.0) < 1e-6) && (num - 42.0 > -1e-6));
    assert(!oh_b.getValueAsNumber(num));
    assert(((num - 42.0) < 1e-6) && (num - 42.0 > -1e-6));
    s = "";
    assert(oh_n.getValueAsName(s));
    assert(s == "/Test");
    assert(!oh_r.getValueAsName(s));
    assert(s == "/Test");
    s = "";
    assert(oh_s.getValueAsUTF8(s));
    assert(s == "/Test");
    assert(!oh_r.getValueAsUTF8(s));
    assert(s == "/Test");
    s = "";
    assert(oh_s.getValueAsUTF8(s));
    assert(s == "/Test");
    assert(!oh_r.getValueAsUTF8(s));
    assert(s == "/Test");
    s = "";
    assert(oh_o.getValueAsOperator(s));
    assert(s == "/Test");
    assert(!oh_r.getValueAsOperator(s));
    assert(s == "/Test");
    s = "";
    assert(oh_ii.getValueAsInlineImage(s));
    assert(s == "/Test");
    assert(!oh_r.getValueAsInlineImage(s));
    assert(s == "/Test");
}

static void
test_86(QPDF& pdf, char const* arg2)
{
    // Test symmetry between newUnicodeString and getUTF8Value for
    // strings that can't be encoded as PDFDoc but don't contain any
    // high code points.

    std::string utf8_val("\x1f");
    std::string utf16_val("\xfe\xff\x00\x1f", 4);
    std::string result;
    assert(QUtil::utf8_to_ascii(utf8_val, result, '?'));
    assert(result == utf8_val);
    assert(!QUtil::utf8_to_pdf_doc(utf8_val, result, '?'));
    assert(result == "?");
    assert(QUtil::utf8_to_utf16(utf8_val) == utf16_val);
    assert(QUtil::utf16_to_utf8(utf16_val) == utf8_val);
    auto h = QPDFObjectHandle::newUnicodeString(utf8_val);
    assert(h.getStringValue() == utf16_val);
    assert(h.getUTF8Value() == utf8_val);
}

static void
test_87(QPDF& pdf, char const* arg2)
{
    // Explicitly demonstrate null dictionary values being the same as
    // missing keys.
    auto dict = "<< /A 1 /B null >>"_qpdf;
    assert(dict.unparse() == "<< /A 1 >>");
    assert(dict.getKeys() == std::set<std::string>({"/A"}));
    dict.replaceKey("/A", QPDFObjectHandle::newNull());
    assert(dict.unparse() == "<< >>");
    assert(dict.getKeys().empty());
    dict = QPDFObjectHandle::newDictionary({
        {"/A", "2"_qpdf},
        {"/B", QPDFObjectHandle::newNull()},
    });
    assert(dict.unparse() == "<< /A 2 >>");
    assert(dict.getKeys() == std::set<std::string>({"/A"}));
    assert(dict.getJSON(JSON::LATEST).unparse() == "{\n  \"/A\": 2\n}");
}

static void
test_88(QPDF& pdf, char const* arg2)
{
    // Exercise mutate and get methods added for qpdf 11.
    auto dict = QPDFObjectHandle::newDictionary();
    dict.replaceKey("/One", QPDFObjectHandle::newInteger(1));
    dict.replaceKey("/Two", QPDFObjectHandle::newInteger(2));
    auto three = dict.replaceKeyAndGetNew("/Three", QPDFObjectHandle::newArray());
    three.appendItem("(a)"_qpdf);
    three.appendItem("(b)"_qpdf);
    auto newdict = three.appendItemAndGetNew(QPDFObjectHandle::newDictionary());
    newdict.replaceKey("/Z", "/Y"_qpdf);
    newdict.replaceKey("/X", "/W"_qpdf);
    dict.replaceKey("/Quack", "[1 2 3]"_qpdf);
    auto quack = dict.replaceKeyAndGetOld("/Quack", "/Moo"_qpdf);
    assert(quack.unparse() == "[ 1 2 3 ]");
    auto nothing = dict.replaceKeyAndGetOld("/NotThere", QPDFObjectHandle::newNull());
    assert(nothing.isNull());
    assert(dict.unparse() == R"(
      <<
        /One 1
        /Quack /Moo
        /Two 2
        /Three [ (a) (b) << /Z /Y /X /W >> ]
      >>
    )"_qpdf.unparse());
    auto arr = dict.getKey("/Three");
    arr.insertItem(0, QPDFObjectHandle::newString("0"));
    arr.insertItem(0, QPDFObjectHandle::newString("00"));
    assert(arr.unparse() == "[ (00) (0) (a) (b) << /Z /Y /X /W >> ]"_qpdf.unparse());
    auto new_dict = arr.insertItemAndGetNew(1, "<< /P /Q /R /S >>"_qpdf);
    arr.eraseItem(2);
    arr.eraseItem(0);
    assert(arr.unparse() == "[ << /P /Q /R /S >> (a) (b) << /Z /Y /X /W >> ]"_qpdf.unparse());

    // new_dict shares internals with the one in the array. It has
    // always been this way, and there is code that relies on this
    // behavior. Maybe it would be different if I could start over
    // again...
    new_dict.removeKey("/R");
    new_dict.replaceKey("/T", "/U"_qpdf);
    assert(arr.unparse() == "[ << /P /Q /T /U >> (a) (b) << /Z /Y /X /W >> ]"_qpdf.unparse());
    auto s = arr.eraseItemAndGetOld(1);
    assert(s.unparse() == "(a)");
    assert(arr.unparse() == "[ << /P /Q /T /U >> (b) << /Z /Y /X /W >> ]"_qpdf.unparse());

    assert(new_dict.removeKeyAndGetOld("/M").isNull());
    assert(new_dict.removeKeyAndGetOld("/P").unparse() == "/Q");
    assert(new_dict.unparse() == "<< /T /U >>"_qpdf.unparse());

    // Test errors
    auto arr2 = pdf.getRoot().replaceKeyAndGetNew("/QTest", "[1 2]"_qpdf);
    arr2.setObjectDescription(&pdf, "test array");
    assert(arr2.eraseItemAndGetOld(50).isNull());
    assert(pdf.getRoot().eraseItemAndGetOld(0).isNull());
}

static void
test_89(QPDF& pdf, char const* arg2)
{
    // Generate object warning with json-input. Crafted to work with
    // manual-qpdf-json.json.
    auto null = QPDFObjectHandle::newNull();
    pdf.getTrailer().appendItem(null);
    pdf.getRoot().appendItem(null);
    pdf.getObjectByID(5, 0).replaceKey("/X", null);
    pdf.getObjectByID(5, 0).getArrayItem(0).replaceKey("/X", null);
}

static void
test_90(QPDF& pdf, char const* arg2)
{
    // Generate object warning with update-from-json. Crafted to work
    // with good13.pdf and various-updates.json. JSON file is arg2.
    pdf.updateFromJSON(arg2);
    pdf.getTrailer().appendItem(QPDFObjectHandle::newNull());
    pdf.getTrailer().getKey("/QTest").appendItem(QPDFObjectHandle::newNull());
    pdf.getTrailer().getKey("/QTest").getKey("/strings").getIntValue();
    // not from json
    pdf.getRoot().appendItem(QPDFObjectHandle::newNull());
}

static void
test_91(QPDF& pdf, char const* arg2)
{
    // Exercise the simpler version of writeJSON.
    Pl_StdioFile p("stdout", stdout);
    pdf.writeJSON(2, &p, qpdf_dl_none, qpdf_sj_inline, "", std::set<std::string>());
}

static void
test_92(QPDF& pdf, char const* arg2)
{
    // Exercise indirect objects owned by destroyed QPDF object.
    auto qpdf = QPDF::create();
    qpdf->processFile("minimal.pdf");
    auto root = qpdf->getRoot();
    assert(root.getOwningQPDF() == qpdf.get());
    assert(root.isIndirect());
    assert(root.isDictionary());
    auto page1 = root.getKey("/Pages").getKey("/Kids").getArrayItem(0);
    assert(page1.getOwningQPDF() == qpdf.get());
    assert(page1.isIndirect());
    assert(page1.isDictionary());
    auto resources = page1.getKey("/Resources");
    assert(resources.getOwningQPDF() == qpdf.get());
    assert(resources.isDictionary());
    assert(!resources.isIndirect());
    auto contents = page1.getKey("/Contents");
    assert(!contents.isScalar());
    auto contents_dict = contents.getDict();
    qpdf = nullptr;
    auto check = [](QPDFObjectHandle& oh) {
        assert(oh.getOwningQPDF() == nullptr);
        assert(!oh.isIndirect());
    };
    // All objects should no longer have an owning QPDF or be indirect.
    check(root);
    check(page1);
    check(resources);
    check(contents);
    check(contents_dict);
    // Objects that were originally indirect should be destroyed.
    // Otherwise, they should have retained their old values but just
    // lost their connection to the owning QPDF.
    assert(root.isDestroyed());
    assert(!root.isScalar());
    assert(page1.isDestroyed());
    assert(contents.isDestroyed());
    assert(resources.isDictionary());
    assert(contents_dict.isDictionary());
    try {
        root.unparse();
        assert(false);
    } catch (std::logic_error&) {
        // Expected
    }
}

static void
test_93(QPDF& pdf, char const* arg2)
{
    // Test QPDFObjectHandle equality. Two QPDFObjectHandle objects
    // are equal if they point to the same underlying object.

    auto trailer = pdf.getTrailer();
    auto root1 = trailer.getKey("/Root");
    auto root2 = pdf.getRoot();
    assert(root1.isSameObjectAs(root2));
    auto oh1 = "<< /One /Two >>"_qpdf;
    auto oh2 = oh1;
    assert(oh1.isSameObjectAs(oh2));
    auto oh3 = "<< /One /Two >>"_qpdf;
    assert(!oh1.isSameObjectAs(oh3));
    oh2.replaceKey("/One", "/Three"_qpdf);
    assert(oh1.isSameObjectAs(oh2));
    assert(oh2.unparse() == "<< /One /Three >>");
    assert(!oh1.isIndirect());
    auto oh4 = pdf.makeIndirectObject(oh1);
    assert(oh1.isSameObjectAs(oh4));
    assert(oh1.isIndirect());
    assert(oh4.isIndirect());
    trailer.replaceKey("/Potato", oh1);
    assert(trailer.getKey("/Potato").isSameObjectAs(oh2));
}

static void
test_94(QPDF& pdf, char const* arg2)
{
    // Exercise methods to get page boxes. This test is built for
    // boxes2.pdf.

    // /MediaBox is present in the pages tree root.
    // Each page has the following boxes present directly:
    // 1. none
    // 2. crop
    // 3. media, crop
    // 4. media, crop, trim, bleed; crop is indirect
    // 5. trim, art

    auto pages_root = pdf.getRoot().getKey("/Pages");
    auto root_media = pages_root.getKey("/MediaBox");
    auto root_media_unparse = root_media.unparse();
    auto pages = QPDFPageDocumentHelper(pdf).getAllPages();
    assert(pages.size() == 5);
    auto& p1 = pages[0];
    auto& p2 = pages[1];
    auto& p3 = pages[2];
    auto& p4 = pages[3];
    auto& p5 = pages[4];

    assert(p1.getObjectHandle().getKey("/MediaBox").isNull());
    // MediaBox not present, so get inherited one
    assert(p1.getMediaBox(false).isSameObjectAs(root_media));
    // Other boxesBox not present, so fall back to MediaBox
    assert(p1.getCropBox(false, false).isSameObjectAs(root_media));
    assert(p1.getBleedBox(false, false).isSameObjectAs(root_media));
    assert(p1.getTrimBox(false, false).isSameObjectAs(root_media));
    assert(p1.getArtBox(false, false).isSameObjectAs(root_media));
    // Make copy of artbox
    auto p1_new_art = p1.getArtBox(false, true);
    assert(p1_new_art.unparse() == root_media_unparse);
    assert(!p1_new_art.isSameObjectAs(root_media));
    // This also copied cropbox
    auto p1_new_crop = p1.getCropBox(false, false);
    assert(!p1_new_crop.isSameObjectAs(root_media));
    assert(!p1_new_crop.isSameObjectAs(p1_new_art));
    assert(p1_new_crop.unparse() == root_media_unparse);
    // But it didn't copy Media
    assert(p1.getMediaBox(false).isSameObjectAs(root_media));
    // Now fall back to new crop
    assert(p1.getTrimBox(false, false).isSameObjectAs(p1_new_crop));
    // Request copy. The value returned has the same structure but is
    // a different object.
    auto p1_effective_media = p1.getMediaBox(true);
    assert(p1_effective_media.unparse() == root_media_unparse);
    assert(!p1_effective_media.isSameObjectAs(root_media));

    // copy_on_fallback didn't have to copy media to crop
    assert(p2.getMediaBox(false).isSameObjectAs(root_media));
    auto p2_crop = p2.getCropBox(false, false);
    auto p2_new_trim = p2.getTrimBox(false, true);
    assert(p2_new_trim.unparse() == p2_crop.unparse());
    assert(!p2_new_trim.isSameObjectAs(p2_crop));
    assert(p2.getMediaBox(false).isSameObjectAs(root_media));

    // We didn't need to copy anything
    auto p3_media = p3.getMediaBox(false);
    auto p3_crop = p3.getCropBox(false, false);
    assert(p3.getMediaBox(true).isSameObjectAs(p3_media));
    assert(p3.getCropBox(true, true).isSameObjectAs(p3_crop));

    // We didn't have to copy for bleed but we did for art
    auto p4_orig_crop = p4.getObjectHandle().getKey("/CropBox");
    auto p4_crop = p4.getCropBox(false, false);
    assert(p4_orig_crop.isSameObjectAs(p4_crop));
    auto p4_bleed1 = p4.getBleedBox(false, false);
    auto p4_bleed2 = p4.getBleedBox(false, true);
    assert(!p4_bleed1.isSameObjectAs(p4_crop));
    assert(p4_bleed1.isSameObjectAs(p4_bleed2));
    auto p4_art1 = p4.getArtBox(false, false);
    assert(p4_art1.isSameObjectAs(p4_crop));
    auto p4_art2 = p4.getArtBox(false, true);
    assert(!p4_art2.isSameObjectAs(p4_crop));
    auto p4_new_crop = p4.getCropBox(true, false);
    assert(!p4_new_crop.isSameObjectAs(p4_orig_crop));
    assert(p4_orig_crop.isIndirect());
    assert(!p4_new_crop.isIndirect());
    assert(p4_new_crop.unparse() == p4_orig_crop.unparseResolved());

    // Exercise copying for inheritance and fallback
    assert(p5.getMediaBox(false).isSameObjectAs(root_media));
    assert(p5.getCropBox(false, false).isSameObjectAs(root_media));
    assert(p5.getBleedBox(false, false).isSameObjectAs(root_media));
    auto p5_new_bleed = p5.getBleedBox(true, true);
    auto p5_new_media = p5.getMediaBox(false);
    auto p5_new_crop = p5.getCropBox(false, false);
    assert(!p5_new_media.isSameObjectAs(root_media));
    assert(!p5_new_crop.isSameObjectAs(root_media));
    assert(!p5_new_crop.isSameObjectAs(p5_new_media));
    assert(!p5_new_bleed.isSameObjectAs(root_media));
    assert(!p5_new_bleed.isSameObjectAs(p5_new_media));
    assert(!p5_new_bleed.isSameObjectAs(p5_new_crop));
    assert(p5_new_media.unparse() == root_media_unparse);
    assert(p5_new_crop.unparse() == root_media_unparse);
    assert(p5_new_bleed.unparse() == root_media_unparse);
}

static void
test_95(QPDF& pdf, char const* arg2)
{
    // Test QPDFObjectHandle::isScalar

    auto oh_b = QPDFObjectHandle::newBool(false);
    auto oh_i = QPDFObjectHandle::newInteger(1);
    auto oh_r = QPDFObjectHandle::newReal("42.0");
    auto oh_n = QPDFObjectHandle::newName("/Test");
    auto oh_s = QPDFObjectHandle::newString("/Test");
    auto oh_o = QPDFObjectHandle::newOperator("/Test");
    auto oh_ii = QPDFObjectHandle::newInlineImage("/Test");
    auto oh_a = QPDFObjectHandle::newArray();
    auto oh_d = QPDFObjectHandle::newDictionary();

    assert(oh_b.isScalar());
    assert(oh_i.isScalar());
    assert(oh_r.isScalar());
    assert(oh_n.isScalar());
    assert(oh_s.isScalar());
    assert(!oh_o.isScalar());
    assert(!oh_ii.isScalar());
    assert(!oh_a.isScalar());
    assert(!oh_d.isScalar());
}

static void
test_96(QPDF& pdf, char const* arg2)
{
    // Test edge cases with quoted characters and string parsing.

    auto s = R"((\48\418\121\4))"_qpdf;
    assert(s.unparseBinary() == "<043821385104>");
    s = R"((\48\418\121\41))"_qpdf;
    assert(s.unparseBinary() == "<043821385121>");
    s = R"(<a>)"_qpdf;
    assert(s.unparseBinary() == "<a0>");
    s = R"(<abc>)"_qpdf;
    assert(s.unparseBinary() == "<abc0>");
}

static void
test_97(QPDF& pdf, char const* arg2)
{
    // Shallow array copy. This test uses many-nulls.pdf.
    auto nulls = pdf.getTrailer().getKey("/Nulls").getArrayItem(0);
    assert(nulls.isArray() && nulls.getArrayNItems() > 10000);
    auto nulls2 = nulls.shallowCopy();
    assert(nulls.unparse() == nulls2.unparse());
}

static void
test_98(QPDF& pdf, char const* arg2)
{
    // Test methods no longer used by qpdf as a result of QPDFObjectHandle::writeJSON. This test is
    // built for minimal.pdf.

    // Test QPDFObjectHandle::getJSON.
    for (int i = 1; i < 7; ++i) {
        auto oh = pdf.getObject(i, 0);
        Pl_Buffer bf1{"write", nullptr};
        Pl_Buffer bf2{"get", nullptr};
        oh.writeJSON(JSON::LATEST, &bf1, true, 7);
        bf1.finish();
        oh.getJSON(JSON::LATEST, true).write(&bf2, 7);
        bf2.finish();
        assert(bf1.getString() == bf2.getString());
    }

    // Test QPDFObjectHandle::getStreamJSON.
    pdf.getObject(4, 0).getDict().replaceKey("/Test", "42"_qpdf);
    assert(
        pdf.getObject(4, 0)
            .getStreamJSON(JSON::LATEST, qpdf_sj_inline, qpdf_dl_generalized, nullptr, "")
            .unparse() ==
        "{\n"
        "  \"data\": \"QlQKICAvRjEgMjQgVGYKICA3MiA3MjAgVGQKICAoUG90YXRvKSBUagpFVAo=\",\n"
        "  \"dict\": {\n"
        "    \"/Test\": 42\n"
        "  }\n"
        "}");
}

static void
test_99(QPDF& pdf, char const* arg2)
{
    // Designed for no-space-compressed-object.pdf
    QPDFObjectHandle qtest = pdf.getRoot().getKey("/QTest");
    for (int i = 0; i < qtest.getArrayNItems(); ++i) {
        std::cout << qtest.getArrayItem(i).unparseResolved() << '\n';
    }
}

static void
test_100(QPDF& pdf, char const* arg2)
{
    // Designed for compressed-metadata.pdf
    auto is_cleartext = [](QPDFObjectHandle& metadata, bool raw) {
        std::string buf;
        Pl_String bufpl("buffer", nullptr, buf);
        metadata.pipeStreamData(&bufpl, 0, raw ? qpdf_dl_none : qpdf_dl_generalized);
        return buf.substr(0, 9) == "<?xpacket";
    };
    auto is_cleartext_in_file = [](std::string const& raw_bytes,
                                   QPDFObjectHandle& metadata) -> bool {
        auto buf = metadata.getRawStreamData();
        auto offset = metadata.getParsedOffset();
        auto from_file = raw_bytes.substr(QIntC::to_size(offset), 10);
        assert(buf->getSize() > 10);
        auto from_buf = std::string(reinterpret_cast<char*>(buf->getBuffer()), from_file.size());
        return from_buf == from_file;
    };

    {
        QPDFWriter w(pdf, "a.pdf");
        w.setR6EncryptionParameters(
            "", "", true, true, true, true, true, true, qpdf_r3p_full, false);
        w.write();
    }
    {
        QPDF encrypted;
        encrypted.processFile("a.pdf");
        auto raw_bytes = QUtil::read_file_into_string("a.pdf");
        auto root = encrypted.getRoot();
        auto root_metadata = root.getKey("/Metadata");
        if (!root_metadata.isStream()) {
            throw std::logic_error("test 100 run on file with no metadata");
        }
        assert(is_cleartext_in_file(raw_bytes, root_metadata));
        assert(is_cleartext(root_metadata, true));
        auto n_pages = QIntC::to_size(root.getKey("/Pages").getKey("/Count").getIntValue());
        auto page = encrypted.getAllPages().at(n_pages - 1);
        auto page_metadata = page.getKey("/Metadata");
        if (!page_metadata.isStream()) {
            throw std::logic_error("test 100 run on file with no metadata on last page");
        }
        // It's encrypted in the file, but you can recover the data, so it is properly decrypted.
        assert(!is_cleartext_in_file(raw_bytes, page_metadata));
        assert(!is_cleartext(page_metadata, true));
        assert(is_cleartext(page_metadata, false));

        // Now copy these metadata objects to the file and write it out again.
        auto copied_root_metadata = pdf.copyForeignObject(root_metadata);
        auto copied_page_metadata = pdf.copyForeignObject(page_metadata);
        pdf.getRoot().replaceKey("/CopiedRootMetadata", copied_root_metadata);
        pdf.getRoot().replaceKey("/CopiedPageMetadata", copied_root_metadata);
        QPDFWriter w(pdf, "b.pdf");
        w.setR6EncryptionParameters(
            "", "", true, true, true, true, true, true, qpdf_r3p_full, false);
        w.write();
    }
    auto raw_bytes = QUtil::read_file_into_string("b.pdf");
    QPDF updated;
    updated.processFile("b.pdf");
    auto root = updated.getRoot();
    auto root_metadata = root.getKey("/Metadata");
    auto n_pages = QIntC::to_size(root.getKey("/Pages").getKey("/Count").getIntValue());
    auto page = updated.getAllPages().at(n_pages - 1);
    auto page_metadata = page.getKey("/Metadata");
    auto copied_root = root.getKey("/CopiedRootMetadata");
    auto copied_page = root.getKey("/CopiedPageMetadata");
    // The ultimate root is still clear-text in file
    assert(is_cleartext_in_file(raw_bytes, root_metadata));
    assert(is_cleartext(root_metadata, true));
    // Everything else is compressed and encrypted in the file (not handled as special case).
    for (auto o: {page_metadata, copied_root, copied_page}) {
        assert(!is_cleartext_in_file(raw_bytes, o));
        assert(!is_cleartext(o, true));
        assert(is_cleartext(o, false));
    }
}

static void
test_101(QPDF& pdf, char const* arg2)
{
    // Test inspection mode
    QPDF qpdf;
    assert(!qpdf::global::options::inspection_mode());
    qpdf::global::options::inspection_mode(true);
    assert(qpdf::global::options::inspection_mode());
    qpdf::global::options::inspection_mode(false);
    // Setting inspection mode is irreversible
    assert(qpdf::global::options::inspection_mode());
    qpdf.processFile("inspect.pdf");
    for (auto& oh: qpdf.getAllObjects()) {
        std::cout << oh.getObjGen().unparse(' ') << '\n';
        std::cout << oh.unparseResolved() << '\n';
    }

    auto test_helper_throws = [&qpdf](auto helper_func) {
        bool thrown = false;
        try {
            helper_func(qpdf);
        } catch (std::logic_error&) {
            thrown = true;
        }
        assert(thrown);
    };

    test_helper_throws([](QPDF& q) { (void)QPDFAcroFormDocumentHelper::get(q); });
    test_helper_throws([](QPDF& q) { (void)QPDFEmbeddedFileDocumentHelper::get(q); });
    test_helper_throws([](QPDF& q) { (void)QPDFOutlineDocumentHelper::get(q); });
    test_helper_throws([](QPDF& q) { (void)QPDFPageDocumentHelper::get(q); });
    test_helper_throws([](QPDF& q) { (void)QPDFPageLabelDocumentHelper::get(q); });
}

static void
test_102(QPDF& pdf, char const* arg2)
{
    // Test using a copy of a QPDFJob object after the original is destroyed

    auto j = std::make_unique<QPDFJob>();
    j->initializeFromJson(
        R"({"inputFile": "minimal.pdf", "outputFile": "a.pdf",  "qdf": "", "staticId": ""})");
    QPDFJob j2 = *j;
    j = nullptr;
    auto q = j2.createQPDF();
    j2.writeQPDF(*q);
}

void
runtest(int n, char const* filename1, char const* arg2)
{
    // Most tests here are crafted to work on specific files.  Look at
    // the test suite to see how the test is invoked to find the file
    // that the test is supposed to operate on.

    std::set<int> ignore_filename = {61, 62, 81, 83, 84, 85, 86, 87, 92, 95, 96, 101, 102};

    if (n == 0) {
        // Throw in some random test cases that don't fit anywhere
        // else.  This is in addition to whatever else is going on in
        // test 0.

        // The code to trim user passwords looks for 0x28 (which is
        // "(") since it marks the beginning of the padding.  Exercise
        // the code to make sure it skips over 0x28 characters that
        // aren't part of padding.
        std::string password("1234567890123456789012(45678\x28\xbf\x4e\x5e");
        assert(password.length() == 32);
        QPDF::trim_user_password(password);
        assert(password == "1234567890123456789012(45678");

        QPDFObjectHandle uninitialized;
        assert(uninitialized.getTypeCode() == ::ot_uninitialized);
        assert(strcmp(uninitialized.getTypeName(), "uninitialized") == 0);
    }

    QPDF pdf;
    std::shared_ptr<char> file_buf;
    FILE* filep = nullptr;
    if (n == 0) {
        pdf.setAttemptRecovery(false);
    }
    if (((n == 35) || (n == 36)) && (arg2 != nullptr)) {
        // arg2 is password
        pdf.processFile(filename1, arg2);
    } else if (n == 45) {
        // Decode obfuscated files. To obfuscated, run the input file
        // through this perl script, and save the result to
        // filename.obfuscated. This pretends that the input was
        // called filename.pdf and that that file contained the
        // deobfuscated version.

        // undef $/;
        // my @str = split('', <STDIN>);
        // for (my $i = 0; $i < scalar(@str); ++$i)
        // {
        //     $str[$i] = chr(ord($str[$i]) ^ 0xcc);
        // }
        // print(join('', @str));

        std::string filename(std::string(filename1) + ".obfuscated");
        size_t size = 0;
        QUtil::read_file_into_memory(filename.c_str(), file_buf, size);
        char* p = file_buf.get();
        for (size_t i = 0; i < size; ++i) {
            p[i] = static_cast<char>(p[i] ^ 0xcc);
        }
        pdf.processMemoryFile((std::string(filename1) + ".pdf").c_str(), p, size);
    } else if (ignore_filename.contains(n)) {
        // Ignore filename argument entirely
    } else if (n == 89) {
        pdf.createFromJSON(filename1);
    } else if (n % 2 == 0) {
        if (n % 4 == 0) {
            QTC::TC("qpdf", "exercise processFile(name)");
            pdf.processFile(filename1);
        } else {
            QTC::TC("qpdf", "exercise processFile(FILE*)");
            filep = QUtil::safe_fopen(filename1, "rb");
            pdf.processFile(filename1, filep, false);
        }
    } else {
        QTC::TC("qpdf", "exercise processMemoryFile");
        size_t size = 0;
        QUtil::read_file_into_memory(filename1, file_buf, size);
        pdf.processMemoryFile(filename1, file_buf.get(), size);
    }

    std::map<int, void (*)(QPDF&, char const*)> test_functions = {
        {0, test_0_1},   {1, test_0_1},   {2, test_2},    {3, test_3},   {4, test_4},
        {5, test_5},     {6, test_6},     {7, test_7},    {8, test_8},   {9, test_9},
        {10, test_10},   {11, test_11},   {12, test_12},  {13, test_13}, {14, test_14},
        {15, test_15},   {16, test_16},   {17, test_17},  {18, test_18}, {19, test_19},
        {20, test_20},   {21, test_21},   {22, test_22},  {23, test_23}, {24, test_24},
        {25, test_25},   {26, test_26},   {27, test_27},  {28, test_28}, {29, test_29},
        {30, test_30},   {31, test_31},   {32, test_32},  {33, test_33}, {34, test_34},
        {35, test_35},   {36, test_36},   {37, test_37},  {38, test_38}, {39, test_39},
        {40, test_40},   {41, test_41},   {42, test_42},  {43, test_43}, {44, test_44},
        {45, test_45},   {46, test_46},   {47, test_47},  {48, test_48}, {49, test_49},
        {50, test_50},   {51, test_51},   {52, test_52},  {53, test_53}, {54, test_54},
        {55, test_55},   {56, test_56},   {57, test_57},  {58, test_58}, {59, test_59},
        {60, test_60},   {61, test_61},   {62, test_62},  {63, test_63}, {64, test_64},
        {65, test_65},   {66, test_66},   {67, test_67},  {68, test_68}, {69, test_69},
        {70, test_70},   {71, test_71},   {72, test_72},  {73, test_73}, {74, test_74},
        {75, test_75},   {76, test_76},   {77, test_77},  {78, test_78}, {79, test_79},
        {80, test_80},   {81, test_81},   {82, test_82},  {83, test_83}, {84, test_84},
        {85, test_85},   {86, test_86},   {87, test_87},  {88, test_88}, {89, test_89},
        {90, test_90},   {91, test_91},   {92, test_92},  {93, test_93}, {94, test_94},
        {95, test_95},   {96, test_96},   {97, test_97},  {98, test_98}, {99, test_99},
        {100, test_100}, {101, test_101}, {102, test_102}};

    auto fn = test_functions.find(n);
    if (fn == test_functions.end()) {
        throw std::runtime_error(std::string("invalid test ") + QUtil::int_to_string(n));
    }
    (fn->second)(pdf, arg2);

    if (filep) {
        fclose(filep);
    }
    std::cout << "test " << n << " done" << '\n';
}

int
main(int argc, char* argv[])
{
    QUtil::setLineBuf(stdout);
    if ((whoami = strrchr(argv[0], '/')) == nullptr) {
        whoami = argv[0];
    } else {
        ++whoami;
    }

    if ((argc < 3) || (argc > 4)) {
        usage();
    }

    try {
        int n = QUtil::string_to_int(argv[1]);
        char const* filename1 = argv[2];
        char const* arg2 = argv[3];
        runtest(n, filename1, arg2);
    } catch (std::exception& e) {
        std::cerr << e.what() << '\n';
        exit(2);
    }

    return 0;
}