This file is indexed.

/usr/share/perl5/PDF/Reuse.pm is in libpdf-reuse-perl 0.35-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
package PDF::Reuse;

use 5.006;
use strict;
use warnings;

require    Exporter;                  
require    Digest::MD5;
use autouse 'Carp' => qw(carp
                         cluck
                         croak);

use Compress::Zlib qw(compress inflateInit);

use autouse 'Data::Dumper'   => qw(Dumper);
use AutoLoader qw(AUTOLOAD);

our $VERSION = '0.35';
our @ISA     = qw(Exporter);
our @EXPORT  = qw(prFile
                  prPage
                  prId
                  prIdType
                  prInitVars
                  prEnd
                  prExtract
                  prForm
                  prImage
                  prJpeg
                  prDoc
                  prDocForm
                  prFont
                  prFontSize
                  prGraphState
                  prGetLogBuffer
                  prAdd
                  prBar
                  prText
                  prDocDir
                  prLogDir
                  prLog
                  prVers
                  prCid
                  prJs
                  prInit
                  prField
                  prTouchUp
                  prCompress
                  prMbox
                  prBookmark
                  prStrWidth
                  prLink
                  prTTFont
                  prSinglePage);

our ($utfil, $slutNod, $formCont, $imSeq, $duplicateInits, $page, $sidObjNr, $sida,
    $interActive, $NamesSaved, $AARootSaved, $AAPageSaved, $root,
    $AcroFormSaved, $id, $ldir, $checkId, $formNr, $imageNr, 
    $filnamn, $interAktivSida, $taInterAkt, $type, $runfil, $checkCs,
    $confuseObj, $compress, $pos, $fontNr, $objNr, $docProxy,
    $defGState, $gSNr, $pattern, $shading, $colorSpace, $totalCount);
 
our (@kids, @counts, @formBox, @objekt, @parents, @aktuellFont, @skapa,
    @jsfiler, @inits, @bookmarks, @annots);
 
our ( %old, %oldObject, %resurser, %form, %image, %objRef, %nyaFunk, %fontSource, 
     %sidFont, %sidXObject, %sidExtGState, %font, %intAct, %fields, %script, 
     %initScript, %sidPattern, %sidShading, %sidColorSpace, %knownToFile,
     %processed, %embedded, %dummy, %behandlad, %unZipped, %links, %prefs);

our $stream  = '';
our $idTyp   = '';
our $ddir    = '';
our $log     = '';

#########################
# Konstanter för objekt
#########################

use constant   oNR        => 0;
use constant   oPOS       => 1;
use constant   oSTREAMP   => 2;
use constant   oKIDS      => 3;
use constant   oFORM      => 4;   
use constant   oIMAGENR   => 5;  
use constant   oWIDTH     => 6;  
use constant   oHEIGHT    => 7;  
use constant   oTYPE      => 8;
use constant   oNAME      => 9;

###################################
# Konstanter för formulär
###################################

use constant   fOBJ       => 0;
use constant   fRESOURCE  => 1;   
use constant   fBBOX      => 2;
use constant   fIMAGES    => 3;
use constant   fMAIN      => 4;
use constant   fKIDS      => 5;
use constant   fNOKIDS    => 6;
use constant   fID        => 7;
use constant   fVALID     => 8;

####################################
# Konstanter för images
####################################

use constant   imWIDTH     => 0;   
use constant   imHEIGHT    => 1; 
use constant   imXPOS      => 2;
use constant   imYPOS      => 3;
use constant   imXSCALE    => 4;
use constant   imYSCALE    => 5;
use constant   imIMAGENO   => 6;

#####################################
# Konstanter för interaktiva objekt
#####################################

use constant   iNAMES     => 1;
use constant   iACROFORM  => 2;
use constant   iAAROOT    => 3;
use constant   iANNOTS    => 4;
use constant   iSTARTSIDA => 5;
use constant   iAAPAGE    => 6;

#####################################
# Konstanter för fonter
#####################################
   
use constant   foREFOBJ     => 0;
use constant   foINTNAMN    => 1;
use constant   foEXTNAMN    => 2;
use constant   foORIGINALNR => 3;
use constant   foSOURCE     => 4;
use constant   foTYP        => 5;
use constant   foFONTOBJ    => 6;

##########
# Övrigt
##########

use constant IS_MODPERL => $ENV{MOD_PERL}; # For mod_perl 1.
                                           # For mod_perl 2 pass $r to prFile()
our $touchUp  = 1;

our %stdFont = 
       ('Times-Roman'           => 'Times-Roman',
        'Times-Bold'            => 'Times-Bold',
        'Times-Italic'          => 'Times-Italic',
        'Times-BoldItalic'      => 'Times-BoldItalic',
        'Courier'               => 'Courier',
        'Courier-Bold'          => 'Courier-Bold',
        'Courier-Oblique'       => 'Courier-Oblique',
        'Courier-BoldOblique'   => 'Courier-BoldOblique',
        'Helvetica'             => 'Helvetica',
        'Helvetica-Bold'        => 'Helvetica-Bold',
        'Helvetica-Oblique'     => 'Helvetica-Oblique',
        'Helvetica-BoldOblique' => 'Helvetica-BoldOblique',
        'Symbol'                => 'Symbol',
        'ZapfDingbats'          => 'ZapfDingbats', 
        'TR'  => 'Times-Roman',
        'TB'  => 'Times-Bold',
        'TI'  => 'Times-Italic',
        'TBI' => 'Times-BoldItalic',
        'C'   => 'Courier',
        'CB'  => 'Courier-Bold',
        'CO'  => 'Courier-Oblique',
        'CBO' => 'Courier-BoldOblique',
        'H'   => 'Helvetica',
        'HB'  => 'Helvetica-Bold',
        'HO'  => 'Helvetica-Oblique',
        'HBO' => 'Helvetica-BoldOblique',
        'S'   => 'Symbol',
        'Z'   => 'ZapfDingbats');

our $genLowerX    = 0;
our $genLowerY    = 0;
our $genUpperX    = 595,
our $genUpperY    = 842;
our $genFont      = 'Helvetica';
our $fontSize     = 12;

keys(%resurser)  = 10;

sub prFont
{   my $nyFont = shift;
    my ($intnamn, $extnamn, $objektnr, $oldIntNamn, $oldExtNamn);
    
    if (! $pos)
    {  errLog("No output file, you have to call prFile first");
    }
    $oldIntNamn = $aktuellFont[foINTNAMN];
    $oldExtNamn = $aktuellFont[foEXTNAMN]; 
    if ($nyFont)
    {  ($intnamn, $extnamn, $objektnr) = findFont($nyFont);
    }
    else
    {   $intnamn = $aktuellFont[foINTNAMN];
        $extnamn = $aktuellFont[foEXTNAMN];
    }
    if ($runfil)
    {  $log .= "Font~$nyFont\n";
    }
    if (wantarray)
    {  return ($intnamn, $extnamn, $oldIntNamn, $oldExtNamn, \%font);
    }
    else
    {  return $intnamn;
    }
}

sub prFontSize
{   my $fSize = shift || 12;
    my $oldFontSize = $fontSize;
    if ($fSize =~ m'\d+\.?\d*'o)
    { $fontSize = $fSize;
      if ($runfil)
      {  $log .= "FontSize~$fontSize\n";
      }
    }
    if (! $pos)
    {  errLog("No output file, you have to call prFile first");
    }

    return ($fontSize, $oldFontSize);    
}
    
sub prFile
{  if ($pos)
   {  prEnd();
      close UTFIL;
   }
   %prefs = ();
   my $param = shift;
   if (ref($param) eq 'HASH')
   {  $filnamn  = '-';
      for (keys %{$param})
      {   my $key = lc($_);
          if ($key eq 'name')
          {  $filnamn = $param->{$_}; }
          elsif (($key eq 'hidetoolbar')
          ||     ($key eq 'hidemenubar')
          ||     ($key eq 'hidewindowui')
          ||     ($key eq 'fitwindow')
          ||     ($key eq 'centerwindow'))
          {  $prefs{$key} = $param->{$_};
          }
      }    
   }
   else
   {  $filnamn  = $param || '-';
      $prefs{hidetoolbar}  = $_[1]  if defined $_[1];
      $prefs{hidemenubar}  = $_[2]  if defined $_[2];
      $prefs{hidewindowui} = $_[3]  if defined $_[3];
      $prefs{fitwindow}    = $_[4]  if defined $_[4];
      $prefs{centerwindow} = $_[5]  if defined $_[5];
   }
   my $kortNamn;
   if ($filnamn ne '-')
   {   my $ri  = rindex($filnamn,'/');
       if ($ri > 0)
       {  $kortNamn = substr($filnamn, ($ri + 1));
          $utfil = $ddir ? $ddir . $kortNamn : $filnamn; 
       }
       else
       {  $utfil = $ddir ? $ddir . $filnamn : $filnamn;
       }
       $ri = rindex($utfil,'/');
       if ($ri > 0)
       {   my $dirdel = substr($utfil,0,$ri);
           if (! -e $dirdel)
           {  mkdir $dirdel || errLog("Couldn't create dir $dirdel, $!");
           }
       }
       else
       {  $ri = rindex($utfil,'\\');
          if ($ri > 0)
          {   my $dirdel = substr($utfil,0,$ri);
              if (! -e $dirdel)
              {  mkdir $dirdel || errLog("Couldn't create dir $dirdel, $!");
              }
          }
       }
   }
   else
   {   $utfil = $filnamn;
   }

   my $utfil_ref = ref $utfil;
   if ($utfil_ref and ($utfil_ref eq 'Apache2::RequestRec') or
                      ($utfil_ref eq 'Apache::RequestRec') ) # mod_perl 2
   { tie *UTFIL, $utfil;
   }
   elsif (IS_MODPERL && $utfil eq '-')     # mod_perl 1
   { tie *UTFIL, 'Apache';
   }
   else
   { open (UTFIL, ">$utfil") || errLog("Couldn't open file $utfil, $!");
   }
   binmode UTFIL;
   my $utrad = "\%PDF-1.4\n\%\â\ã\Ï\Ó\n";
   
   $pos   = syswrite UTFIL, $utrad; 

   if (defined $ldir)
   {   if ($utfil eq '-')
       {   $kortNamn = 'stdout';
       }
       if ($kortNamn)
       {  $runfil = $ldir . $kortNamn  . '.dat';
       }
       else
       {  $runfil = $ldir . $filnamn  . '.dat';
       }
       open (RUNFIL, ">>$runfil") || errLog("Couldn't open loggfile $runfil, $!");
       $log .= "Vers~$VERSION\n";        
   }

   
   @parents     = ();
   @kids        = ();
   @counts      = ();
   @objekt      = ();
   $objNr       = 2; # Reserverat objekt 1 för root och 2 för initial sidnod
   $parents[0]  = 2;
   $page        = 0;
   $formNr      = 0;
   $imageNr     = 0;
   $fontNr      = 0;
   $gSNr        = 0;
   $pattern     = 0;
   $shading     = 0;
   $colorSpace  = 0;
   $sida        = 0;
   %font        = ();
   %resurser    = ();
   %fields      = ();
   @jsfiler     = ();
   @inits       = ();
   %nyaFunk     = ();
   %objRef      = ();
   %knownToFile = ();
   @aktuellFont = ();
   %old         = ();
   %behandlad   = ();
   @bookmarks   = ();
   %links       = ();
   undef $defGState;
   undef $interActive;
   undef $NamesSaved;
   undef $AARootSaved;
   undef $AcroFormSaved;
   $checkId    = '';
   undef $duplicateInits;
   undef $confuseObj;
   $fontSize  = 12;
   $genLowerX = 0;
   $genLowerY = 0;
   $genUpperX = 595,
   $genUpperY = 842;
   
   prPage(1);
   $stream = ' ';                
   if ($runfil)
   {  $filnamn = prep($filnamn);
      $log .= "File~$filnamn";
      $log .= (exists $prefs{hidetoolbar}) ? "~$prefs{hidetoolbar}" : '~';
      $log .= (exists $prefs{hidemenubar}) ? "~$prefs{hidemenubar}" : '~';
      $log .= (exists $prefs{hidewindowui}) ? "~$prefs{hidewindowui}" : '~';
      $log .= (exists $prefs{fitwindow}) ? "~$prefs{fitwindow}" : '~';
      $log .= (exists $prefs{centerwindow}) ? "~$prefs{centerwindow}" : "~\n";
   }
   1;
}


sub prPage
{  my $noLogg = shift;
   if ((defined $stream) && (length($stream) > 0))
   { skrivSida();
   }
    
   $page++;
   $objNr++;
   $sidObjNr = $objNr;
   
   #
   # Resurserna nollställs
   #
  
   %sidXObject    = ();
   %sidExtGState  = ();
   %sidFont       = ();
   %sidPattern    = ();
   %sidShading    = ();
   %sidColorSpace = ();
   @annots        = ();
   
   undef $interAktivSida;
   undef $checkCs;
   if (($runfil) && (! $noLogg))
   {  $log .= "Page~\n";
       print RUNFIL $log;
       $log = '';
   }
   if (! $pos)
   {  errLog("No output file, you have to call prFile first");
   }
   1;
    
}

sub prText
{ my $xPos  = shift;
  my $yPos  = shift;
  my $TxT   = shift;
  my $align = shift || 'left';
  my $rot   = shift || '0';
  
  my $width = 0;
  my $x_align_offset = 0;
  
  if (! defined $TxT)
  {  $TxT = '';
  } 

  if (($xPos !~ m'\-?[\d\.]+'o) || (! defined $xPos))
  { errLog("Illegal x-position for text: $xPos");
  } 
  if (($yPos !~ m'\-?[\d\.]+'o) || (! defined $yPos))
  { errLog("Illegal y-position for text: $yPos");
  }

  if ($runfil)
  {   my $Texten   = prep($TxT);
      $log .= "Text~$xPos~$yPos~$Texten~$align~$rot\n";
  } 

  if (length($stream) < 3)
  {  $stream = "0 0 0 rg\n 0 g\nf\n";
  }
 

  if (! $aktuellFont[foINTNAMN])
  {  findFont();
  }
  my $Font        = $aktuellFont[foINTNAMN];        # Namn i strömmen
  $sidFont{$Font} = $aktuellFont[foREFOBJ];
  my $fontname    = $aktuellFont[foEXTNAMN];
  my $ttfont      = $font{$fontname} ? $font{$fontname}[foFONTOBJ] : undef;
  
  
  # define what the offset for alignment is 
  
  if ((wantarray) 
  || ($align ne 'left'))
  {  $width = prStrWidth($TxT, $aktuellFont[foEXTNAMN], $fontSize);
     if($align eq 'right')
     {  $x_align_offset = - $width;
     }
     elsif ($align eq 'center')
     {  $x_align_offset = -$width / 2;               
     }
  }
  
  $TxT =~ s|\(|\\(|gos;
  $TxT =~ s|\)|\\)|gos;
  
  
  unless($rot)
  {  $stream .= "\nBT /$Font $fontSize Tf ";
     if($ttfont)
     {   $TxT = $ttfont->encode_text($TxT);
         $stream .= $xPos+$x_align_offset . " $yPos Td $TxT Tj ET\n";
     }
     elsif (!$aktuellFont[foTYP])
     {   $stream .= $xPos+$x_align_offset . " $yPos Td \($TxT\) Tj ET\n";
     }
     else
     {   my $text;
         $TxT =~ s/\\(\d\d\d)/chr(oct($1))/eg;
         for (unpack ('C*', $TxT)) 
         {  $text .= sprintf("%04x", ($_ - 29));	
         }
         $stream .= $xPos+$x_align_offset . " $yPos Td \<$text\> Tj ET\n";
     }
  } 
  else 
  {  if ($rot =~ m'q(\d)'oi)
      {  if ($1 eq '1')
         {  $rot = 270;
         }
         elsif ($1 eq '2')
         {  $rot = 180;
         }
         else
         {  $rot = 90;
         }
      }
  
     my $radian = sprintf("%.6f", $rot / 57.2957795);    # approx. 
     my $Cos    = sprintf("%.6f", cos($radian));
     my $Sin    = sprintf("%.6f", sin($radian));
     my $negSin = $Sin * -1;
  
     my $encText = $ttfont ? $ttfont->encode_text($TxT) : "\($TxT\)";
     $stream .=   "\nq\n"		                    # enter a new stack frame
                # . "/Gs0 gs\n"	                            # reset graphic mode
                . "$Cos $Sin $negSin $Cos $xPos $yPos cm\n" # rotation/translation in the CM
                . "\nBT /$Font $fontSize Tf " 
                . "$x_align_offset 0 Td $encText Tj ET\n"   # text @ 0,0
                . "Q\n";                                    # close the stack frame
  }
  if (! $pos)
  {  errLog("No output file, you have to call prFile first");
  }
    
      
  if (wantarray)
  {  # return a new "cursor" position...
  
     if($rot==0)
     {  if($align eq 'left')
        {   return ($xPos, $xPos + $width);
        }
        elsif($align eq 'center')
        { return ($xPos - $x_align_offset, $xPos + $x_align_offset);
        }
        elsif($align eq 'right')
        {   return ($xPos - $width, $xPos);
        }
  
     } 
     else 
     {   # todo
         # we could some trigonometry to return an x/y point
         return 1;
     }
  }
  else
  {  return 1;
  }
   
}


sub prAdd
{  my $contents = shift;
   $stream .= "\n$contents\n";
   if ($runfil)
   {   $contents = prep($contents);
       $log .= "Add~$contents\n";
   }
   $checkCs = 1;
   if (! $pos)
   {  errLog("No output file, you have to call prFile first");
   }
   1;
}

########################## 
# Ett grafiskt "formulär" 
##########################

sub prForm
{ my ($sidnr, $adjust, $effect, $tolerant, $infil, $x, $y, $size, $xsize,
      $ysize, $rotate);
  my $param = shift;
  if (ref($param) eq 'HASH')
  {  $infil    = $param->{'file'};
     $sidnr    = $param->{'page'} || 1;
     $adjust   = $param->{'adjust'} || '';
     $effect   = $param->{'effect'} || 'print';
     $tolerant = $param->{'tolerant'} || '';
     $x        = $param->{'x'} || 0;
     $y        = $param->{'y'} || 0;
     $rotate   = $param->{'rotate'} || 0;
     $size     = $param->{'size'} || 1;
     $xsize    = $param->{'xsize'} || 1;
     $ysize    = $param->{'ysize'} || 1;
  }
  else
  {  $infil    = $param;
     $sidnr    = shift || 1;
     $adjust   = shift || '';
     $effect   = shift || 'print';
     $tolerant = shift || '';
     $x        = shift || 0;
     $y        = shift || 0;
     $rotate   = shift || 0;
     $size     = shift || 1;
     $xsize    = shift || 1;
     $ysize    = shift || 1;
  }
  
  my $refNr;
  my $namn;
  $type = 'form';  
  my $fSource = $infil . '_' . $sidnr;
  if (! exists $form{$fSource})
  {  $formNr++;
     $namn = 'Fm' . $formNr;
     $knownToFile{$fSource} = $namn;
     my $action;
     if ($effect eq 'load')
     {  $action = 'load'
     }
     else
     {  $action = 'print'
     }     
     $refNr         = getPage($infil, $sidnr, $action);
     if ($refNr)
     {  $objRef{$namn} = $refNr; 
     }
     else
     {  if ($tolerant)
        {  if ((defined $refNr) && ($refNr eq '0'))   # Sidnumret existerar inte, men ok
           {   $namn = '0';
           }
           else
           {   undef $namn;   # Sidan kan inte användas som form
           }
        }
        elsif (! defined $refNr)
        {  my $mess = "$fSource can't be used as a form. See the documentation\n"
                    . "under prForm how to concatenate streams\n";
           errLog($mess);
        }
        else
        {  errLog("File : $infil  Page: $sidnr  doesn't exist");
        }
     }
  }
  else
  {  if (exists $knownToFile{$fSource})
     {  $namn = $knownToFile{$fSource};
     }
     else
     {  $formNr++;
        $namn = 'Fm' . $formNr;
        $knownToFile{$fSource} = $namn;
     }
     if (exists $objRef{$namn})
     {  $refNr = $objRef{$namn};
     }
     else
     {  if (! $form{$fSource}[fVALID])
        {  my $mess = "$fSource can't be used as a form. See the documentation\n"
                    . "under prForm how to concatenate streams\n";
           if ($tolerant)
           {  cluck $mess;
              undef $namn;
           }
           else
           {  errLog($mess);
           }
        }
        elsif ($effect ne 'load')
        {  $refNr         =  byggForm($infil, $sidnr);
           $objRef{$namn} =  $refNr;
        }
     }
  }
  my @BBox = @{$form{$fSource}[fBBOX]} if ($refNr);
  if (($effect eq 'print') && ($form{$fSource}[fVALID]) && ($refNr))
  {   if (! defined $defGState)
      { prDefaultGrState();
      }
  
      if ($adjust)
      {   $stream .= "q\n";
          $stream .= fillTheForm(@BBox, $adjust);
          $stream .= "\n/Gs0 gs\n";
          $stream .= "/$namn Do\n";
          $stream .= "Q\n";
      }
      elsif (($x) || ($y) || ($rotate) || ($size != 1) 
                  || ($xsize != 1)     || ($ysize != 1))
      {   $stream .= "q\n";
          $stream .= calcMatrix($x, $y, $rotate, $size, 
                     $xsize, $ysize, $BBox[2], $BBox[3]);
          $stream .= "\n/Gs0 gs\n";
          $stream .= "/$namn Do\n";
          $stream .= "Q\n";
      }
      else
      {   $stream .= "\n/Gs0 gs\n";   
          $stream .= "/$namn Do\n";
          
      }
      $sidXObject{$namn}   = $refNr;
      $sidExtGState{'Gs0'} = $defGState;
  }
  if ($runfil)
  {  $infil = prep($infil);
     $log .= "Form~$infil~$sidnr~$adjust~$effect~$tolerant";
     $log .= "~$x~$y~$rotate~$size~$xsize~$ysize\n";
  }
  if (! $pos)
  {  errLog("No output file, you have to call prFile first");
  }
  if (($effect ne 'print') && ($effect ne 'add'))
  {  undef $namn;
  }
  if (wantarray)
  {  my $images = 0;
     if (exists $form{$fSource}[fIMAGES])
     {  $images = scalar(@{$form{$fSource}[fIMAGES]});
     } 
     return ($namn, $BBox[0], $BBox[1], $BBox[2], 
             $BBox[3], $images);
  }
  else
  {  return $namn;
  }
}



##########################################################
sub prDefaultGrState
##########################################################
{  $objNr++;
   $defGState = $objNr;
   if (! $pos)
   {  errLog("No output file, you have to call prFile first");
   }

   $objekt[$objNr] = $pos;
   my $utrad = "$objNr 0 obj" . '<</Type/ExtGState/SA false/SM 0.02/TR2 /Default'
           . ">>endobj\n";
   $pos += syswrite UTFIL, $utrad;
   $objRef{'Gs0'} = $objNr;
   return ('Gs0', $defGState);
}

######################################################
# En font lokaliseras och fontobjektet skrivs ev. ut
######################################################

sub findFont()
{  no warnings;
   my $Font = shift || '';
      
   if (! (exists $fontSource{$Font}))        #  Fonten måste skapas
   {  if (exists $stdFont{$Font})
      {  $Font = $stdFont{$Font};}
      else
      {  $Font = $genFont; }                 # Helvetica sätts om inget annat finns
      if (! (exists $font{$Font}))
      {  $objNr++;
         $fontNr++;
         my $fontAbbr           = 'Ft' . $fontNr; 
         my $fontObjekt         = "$objNr 0 obj<</Type/Font/Subtype/Type1" .
                               "/BaseFont/$Font/Encoding/WinAnsiEncoding>>endobj\n";
         $font{$Font}[foINTNAMN]      = $fontAbbr; 
         $font{$Font}[foREFOBJ]       = $objNr;
         $objRef{$fontAbbr}           = $objNr;
         $fontSource{$Font}[foSOURCE] = 'Standard';
         $objekt[$objNr]              = $pos;
         $pos += syswrite UTFIL, $fontObjekt;
      }
   }
   else
   {  if (defined $font{$Font}[foREFOBJ])       # Finns redan i filen
      {  ; }
      else
      {  if ($fontSource{$Font}[foSOURCE] eq 'Standard')
         {   $objNr++;
             $fontNr++;
             my $fontAbbr           = 'Ft' . $fontNr; 
             my $fontObjekt         = "$objNr 0 obj<</Type/Font/Subtype/Type1" .
                                      "/BaseFont/$Font/Encoding/WinAnsiEncoding>>endobj\n";
             $font{$Font}[foINTNAMN]    = $fontAbbr; 
             $font{$Font}[foREFOBJ]     = $objNr;
             $objRef{$fontAbbr}         = $objNr;
             $objekt[$objNr]            = $pos;
             $pos += syswrite UTFIL, $fontObjekt;
         }
         else
         {  my $fSource = $fontSource{$Font}[foSOURCE];
            my $ri      = rindex($fSource, '_');
            my $Source  = substr($fSource, 0, $ri);
            my $Page    = substr($fSource, ($ri + 1));
            
            if (! $fontSource{$Font}[foORIGINALNR])
            {  errLog("Couldn't find $Font, aborts");
            }
            else
            {  my $namn = extractObject($Source, $Page,
                                        $fontSource{$Font}[foORIGINALNR], 'Font');
            } 
         }
      }
   }

   $aktuellFont[foEXTNAMN]   = $Font;
   $aktuellFont[foREFOBJ]    = $font{$Font}[foREFOBJ];
   $aktuellFont[foINTNAMN]   = $font{$Font}[foINTNAMN];
   $aktuellFont[foTYP]       = $font{$Font}[foTYP];
   
   $sidFont{$aktuellFont[foINTNAMN]} = $aktuellFont[foREFOBJ];
   if (! $pos)
   {  errLog("No output file, you have to call prFile first");
   }

   return ($aktuellFont[foINTNAMN], $aktuellFont[foEXTNAMN], $aktuellFont[foREFOBJ]);  
}

sub skrivSida
{  my ($compressFlag, $streamObjekt, @extObj);
   if ($checkCs)
   {  @extObj = ($stream =~ m'/(\S+)\s*'gso);
      checkContentStream(@extObj);
   }
   if (( $compress ) && ( length($stream)  > 99 ))
   {   my $output = compress($stream);
       if ((length($output) > 25) && (length($output) < (length($stream))))
       {  $stream = $output;
          $compressFlag = 1;
       }       
   }
      
   if (! $parents[0])
   { $objNr++;
     $parents[0] = $objNr;
   }
   my $parent = $parents[0];

   ##########################################   
   #  Interaktiva funktioner läggs ev. till
   ##########################################

   if ($interAktivSida)
   {  my ($infil, $sidnr) = split(/\s+/, $interActive);
      ($NamesSaved, $AARootSaved, $AAPageSaved, $AcroFormSaved) 
            = AcroFormsEtc($infil, $sidnr);     
   }

   ##########################
   # Skapa resursdictionary
   ##########################
   my $resursDict = "/ProcSet[/PDF/Text]";
   if (scalar %sidFont)
   {  $resursDict .= '/Font << ';
      my $i = 0;
      for (keys %sidFont)
      {  $resursDict .= "/$_ $sidFont{$_} 0 R";
      }
      
      $resursDict .= " >>";
   }
   if (scalar %sidXObject)
   {  $resursDict .= '/XObject<<';
      for (keys %sidXObject)
      {  $resursDict .= "/$_ $sidXObject{$_} 0 R";
      }
      $resursDict .= ">>";
   }
   if (scalar %sidExtGState)
   {  $resursDict .= '/ExtGState<<';
      for (keys %sidExtGState)
      {  $resursDict .= "\/$_ $sidExtGState{$_} 0 R";
      }
      $resursDict .= ">>";
   }
   if (scalar %sidPattern)
   {  $resursDict .= '/Pattern<<';
      for (keys %sidPattern)
      {  $resursDict .= "/$_ $sidPattern{$_} 0 R";
      }
      $resursDict .= ">>";
   }
   if (scalar %sidShading)
   {  $resursDict .= '/Shading<<';
      for (keys %sidShading)
      {  $resursDict .= "/$_ $sidShading{$_} 0 R";
      }
      $resursDict .= ">>";
   }
   if (scalar %sidColorSpace)
   {  $resursDict .= '/ColorSpace<<';
      for (keys %sidColorSpace)
      {  $resursDict .= "/$_ $sidColorSpace{$_} 0 R";
      }
      $resursDict .= ">>";
   }

      
   my $resursObjekt;
   
   if (exists $resurser{$resursDict})
   {  $resursObjekt = $resurser{$resursDict};  # Fanns ett identiskt,
   }                                           # använd det
   else
   {   $objNr++;
       if ( keys(%resurser) < 10)
       {  $resurser{$resursDict} = $objNr;  # Spara 10 första resursobjekten
       }
       $resursObjekt   = $objNr;
       $objekt[$objNr] = $pos;
       $resursDict     = "$objNr 0 obj<<$resursDict>>endobj\n";
       $pos += syswrite UTFIL, $resursDict ;
    }
    my $sidObjekt;

    if (! $touchUp)
    {   #
        # Contents objektet skapas
        #

        my $devX = "900";
        my $devY = "900";

        my $mellanObjekt = '<</Type/XObject/Subtype/Form/FormType 1';
        if (defined $resursObjekt)
        {  $mellanObjekt .= "/Resources $resursObjekt 0 R";
        }
        $mellanObjekt .= "/BBox \[$genLowerX $genLowerY $genUpperX $genUpperY\]" .
                     "/Matrix \[ 1 0 0 1 -$devX -$devY \]";

        my $langd = length($stream);
    
        $objNr++;
        $objekt[$objNr] = $pos;        
        if (! $compressFlag)
        {   $mellanObjekt  = "$objNr 0 obj\n$mellanObjekt/Length $langd>>stream\n" 
                           . $stream;
            $mellanObjekt .= "endstream\nendobj\n";
        }
        else
        {   $stream = "\n" . $stream . "\n";
            $langd++;
            $mellanObjekt  = "$objNr 0 obj\n$mellanObjekt/Filter/FlateDecode"
                           .  "/Length $langd>>stream" . $stream;
            $mellanObjekt .= "endstream\nendobj\n";
        }

        $pos += syswrite UTFIL, $mellanObjekt;
        $mellanObjekt = $objNr;

        if (! defined $confuseObj)
        {  $objNr++;
           $objekt[$objNr] = $pos;

           $stream = "\nq\n1 0 0 1 $devX $devY cm\n/Xwq Do\nq\n";
           $langd = length($stream);
           $confuseObj = $objNr;
           $stream = "$objNr 0 obj<</Length $langd>>stream\n" . "$stream";
           $stream .= "\nendstream\nendobj\n";
           $pos += syswrite UTFIL, $stream;
        }
        $sidObjekt = "$sidObjNr 0 obj\n<</Type/Page/Parent $parent 0 R/Contents $confuseObj 0 R"
                      . "/MediaBox \[$genLowerX $genLowerY $genUpperX $genUpperY\]"
                      . "/Resources <</ProcSet[/PDF/Text]/XObject<</Xwq $mellanObjekt 0 R>>>>";
    }
    else
    {   my $langd = length($stream);
    
        $objNr++;
        $objekt[$objNr] = $pos; 
        if (! $compressFlag)
        {  $streamObjekt  = "$objNr 0 obj<</Length $langd>>stream\n" . $stream;
           $streamObjekt .= "\nendstream\nendobj\n";
        }
        else
        {  $stream = "\n" . $stream . "\n";
           $langd++;

           $streamObjekt  = "$objNr 0 obj<</Filter/FlateDecode"
                             . "/Length $langd>>stream" . $stream;
           $streamObjekt .= "endstream\nendobj\n";
        }

        $pos += syswrite UTFIL, $streamObjekt;
        $streamObjekt = $objNr;
        ##################################
        # Så skapas och skrivs sidobjektet 
        ##################################

        $sidObjekt = "$sidObjNr 0 obj<</Type/Page/Parent $parent 0 R/Contents $streamObjekt 0 R"
                      . "/MediaBox \[$genLowerX $genLowerY $genUpperX $genUpperY\]"
                      . "/Resources $resursObjekt 0 R";
    }
    
    $stream = '';

    my $tSida = $sida + 1;
    if ((@annots) 
    || (defined @{$links{'-1'}}) 
    || (defined @{$links{$tSida}}))
    {  $sidObjekt .= '/Annots ' . mergeLinks() . ' 0 R';
    }
    if (defined $AAPageSaved)
    {  $sidObjekt .= "/AA $AAPageSaved";
       undef $AAPageSaved;
    }
    $sidObjekt .= ">>endobj\n";
    $objekt[$sidObjNr] = $pos;
    $pos += syswrite UTFIL, $sidObjekt;
    push @{$kids[0]}, $sidObjNr;
    $sida++;
    $counts[0]++;
    if ($counts[0] > 9)
    {  ordnaNoder(8); }
}


sub prEnd
{   if (! $pos)
    {  return;
    }
    if ($stream)
    { skrivSida(); }
    skrivUtNoder();

    if($docProxy)
    {  $docProxy->write_objects;
       undef $docProxy;             # Break circular refs
    }

    ###################
    # Skriv root 
    ###################

    if (! defined $objekt[$objNr])
    {  $objNr--;                   # reserverat sidobjektnr utnyttjades aldrig
    }
    
    my $utrad = "1 0 obj<</Type/Catalog/Pages $slutNod 0 R";
    if (defined $NamesSaved)
    {  $utrad .= "\/Names $NamesSaved 0 R\n"; 
    }
    elsif ((scalar %fields) || (scalar @jsfiler))
    {  $utrad .= "\/Names " . behandlaNames() . " 0 R\n";
    }
    if (defined $AARootSaved)
    {  $utrad .= "/AA $AARootSaved\n";
    } 
    if ((scalar @inits) || (scalar %fields))
    {  my $nyttANr = skrivKedja();
       $utrad .= "/OpenAction $nyttANr 0 R";
    }
     
    if (defined $AcroFormSaved)
    {  $utrad .= "/AcroForm $AcroFormSaved\n";
    } 
   
    if (scalar @bookmarks)
    {  my $outLine = ordnaBookmarks();
       $utrad .= "/Outlines $outLine 0 R/PageMode /UseOutlines\n";
    }
    if (scalar %prefs)
    {   $utrad .= '/ViewerPreferences << ';
        if (exists $prefs{hidetoolbar})
        {  $utrad .= ($prefs{hidetoolbar}) ? '/HideToolbar true' 
                                           : '/HideToolbar false'; 
        }
        if (exists $prefs{hidemenubar}) 
        {  $utrad .= ($prefs{hidemenubar}) ? '/HideMenubar true'
                                           : '/HideMenubar false';
        }
        if (exists $prefs{hidewindowui})
        {  $utrad .= ($prefs{hidewindowui}) ? '/HideWindowUI true' 
                                            : '/HideWindowUI false';
        }
        if (exists $prefs{fitwindow})
        {  $utrad .= ($prefs{fitwindow}) ? '/FitWindow true'
                                         : '/FitWindow false';
        }
        if (exists $prefs{centerwindow})
        {  $utrad .= ($prefs{centerwindow}) ? '/CenterWindow true'
                                            : '/CenterWindow false';
        }
        $utrad .= '>> ';
    }
 
    $utrad .= ">>endobj\n";

    $objekt[1] = $pos;
    $pos += syswrite UTFIL, $utrad;
    my $antal = $#objekt;
    my $startxref = $pos;
    my $xrefAntal = $antal + 1;
    $pos += syswrite UTFIL, "xref\n";
    $pos += syswrite UTFIL, "0 $xrefAntal\n";
    $pos += syswrite UTFIL, "0000000000 65535 f \n";
    
    for (my $i = 1; $i <= $antal; $i++)
    {  $utrad = sprintf "%.10d 00000 n \n", $objekt[$i];
       $pos += syswrite UTFIL, $utrad;
    }
    
    $utrad  = "trailer\n<<\n/Size $xrefAntal\n/Root 1 0 R\n";
    if ($idTyp ne 'None')
    {  my ($id1, $id2) = definieraId();
       $utrad .= "/ID [<$id1><$id2>]\n";
       $log  .= "IdType~rep\n";
       $log  .= "Id~$id1\n";
    }
    $utrad .= ">>\nstartxref\n$startxref\n";
    $pos += syswrite UTFIL, $utrad; 
    $pos += syswrite UTFIL, "%%EOF\n";
    close UTFIL;

    if ($runfil)
    {   if ($log)
        { print RUNFIL $log;
        }
        close RUNFIL;
    }
    $log    = '';
    $runfil = '';
    $pos    = 0;
    1;   
}
    
sub ordnaNoder
{  my $antBarn = shift;
   my $i       = 0;
   my $j       = 1;
   my $vektor;
      
   while  ($antBarn < $#{$kids[$i]})
   {  # 
      # Skriv ut aktuell förälder
      # flytta till nästa nivå
      #
      $vektor = '[';
      
      for (@{$kids[$i]})
      {  $vektor .= "$_ 0 R "; }
      $vektor .= ']';

      if (! $parents[$j])
      {  $objNr++;
         $parents[$j] = $objNr;
      }
      
      my $nodObjekt;
      $nodObjekt = "$parents[$i] 0 obj<</Type/Pages/Parent $parents[$j] 0 R\n/Kids $vektor\n/Count $counts[$i]>>endobj\n";
      
      $objekt[$parents[$i]] = $pos;
      $pos += syswrite UTFIL, $nodObjekt;
      $counts[$j] += $counts[$i];
      $counts[$i]  = 0;
      $kids[$i]    = [];
      push @{$kids[$j]}, $parents[$i];
      undef $parents[$i];
      $i++;
      $j++;
   }
}
          
sub skrivUtNoder
{  no warnings;
   my ($i, $j, $vektor, $nodObjekt);
   my $si = -1;
   #
   # Hitta slutnoden
   #
   for (@parents)
   { $slutNod = $_; 
     $si++;
   }
   
   for ($i = 0; $parents[$i] ne $slutNod; $i++)
   {  if (defined $parents[$i])  # Bara definierat om det finns kids
      {  $vektor = '[';
         for (@{$kids[$i]})
         {  $vektor .= "$_ 0 R "; }
         $vektor .= ']';
         ########################################
         # Hitta förälder till aktuell förälder
         ########################################
         my $nod;
         for ($j = $i + 1; (! $nod); $j++)
         {  if ($parents[$j])
            {  $nod = $parents[$j];
               $counts[$j] += $counts[$i];
               push @{$kids[$j]}, $parents[$i];
            }
         }
      
         $nodObjekt = "$parents[$i] 0 obj<</Type/Pages/Parent $nod 0 R\n/Kids $vektor/Count $counts[$i]>>endobj\n";
      
         $objekt[$parents[$i]] = $pos;
         $pos += syswrite UTFIL, $nodObjekt;
      }
   }
   #####################################
   #  Så ordnas och skrivs slutnoden ut
   #####################################
   $vektor = '[';
   for (@{$kids[$si]})
   {  $vektor .= "$_ 0 R "; }
   $vektor .= ']';
   $nodObjekt  = "$slutNod 0 obj<</Type/Pages/Kids $vektor/Count $counts[$si]";
   # $nodObjekt .= "/MediaBox \[$genLowerX $genLowerY $genUpperX $genUpperY\]";
   $nodObjekt .= " >>endobj\n";
   $objekt[$slutNod] = $pos;
   $pos += syswrite UTFIL, $nodObjekt;
          
}

sub findGet
{  my ($fil, $cid) = @_;
   $fil =~ s|\s+$||o;
   my ($req, $extFil, $tempFil, $fil2, $tStamp, $res);
   
   if (-e $fil)
   {  $tStamp = (stat($fil))[9];
      if ($cid)
      { 
        if ($cid eq $tStamp)
        {  return ($fil, $cid);
        }
      }
      else
      {  return ($fil, $tStamp);
      }
   }
   if ($cid)
   {  $fil2 = $fil . $cid;
      if (-e $fil2)
      {  return ($fil2, $cid);
      }
   }
   errLog("The file $fil can't be found, aborts");  
}
   
sub definieraId
{  if ($idTyp eq 'rep')
   {  if (! defined $id)
      {  errLog("Can't replicate the id if is missing, aborting"); 
      }
      my $tempId = $id;
      undef $id;
      return ($tempId, $tempId);
   }
   elsif ($idTyp eq 'add')
   {  $id++;
      return ($id, $id);
   }
   else   
   {  my $str = time();
      $str .= $filnamn . $pos;
      $str  = Digest::MD5::md5_hex($str);      
      return ($str, $str);
   }     
}

sub prStrWidth 
{  require PDF::Reuse::Util;
   my $string   = shift;
   my $Font     = shift;
   my $FontSize = shift || $fontSize;
   my $w = 0;

   if(my($width) = ttfStrWidth($string, $Font, $FontSize))
   {  return $width;
   }
    
   if (! $Font)
   {  if (! $aktuellFont[foEXTNAMN])
      {  findFont();
      }
      $Font = $aktuellFont[foEXTNAMN];
   }

   if (! exists $PDF::Reuse::Util::font_widths{$Font})
   {  if (exists $stdFont{$Font})
      {  $Font = $stdFont{$Font};
      }
      if (! exists $PDF::Reuse::Util::font_widths{$Font})
      {   $Font = 'Helvetica';
      }
   }
  
   if (ref($PDF::Reuse::Util::font_widths{$Font}) eq 'ARRAY')
   {   my @font_table = @{ $PDF::Reuse::Util::font_widths{$Font} };
       if (defined $string) {
           for (unpack ("C*", $string)) 
           {  $w += $font_table[$_];	
           }
       }
   }
   else
   {   $w = length($string) * $PDF::Reuse::Util::font_widths{$Font};
   }
   $w = $w / 1000 * $FontSize;
  
   return $w;
}

sub prTTFont
{  return prFont() if ! @_;
   my($selector, $fontname) = @_;

   # Have we loaded this font already?
   my $ttfont = findTTFont($selector);
   if (! $ttfont  and  $font{$selector} )
   {  return prFont($selector);
   }
   $fontname = $ttfont->fontname if $ttfont;

   # Create a new TTFont object if we haven't loaded this one before
   if (! $ttfont)
   {  $docProxy ||= PDF::Reuse::DocProxy->new(
         next_obj => sub { ++$objNr },
         prObj    => \&prObj,
      );

      my $ttfont = PDF::Reuse::TTFont->new(
         filename => $selector,
         fontname => $fontname,
         fontAbbr => 'Ft' . ++$fontNr,
         docProxy => $docProxy,
      );
      $fontname = $ttfont->fontname;

      $font{$fontname}[foINTNAMN]      = $ttfont->fontAbbr; 
      $font{$fontname}[foREFOBJ]       = $ttfont->obj_num;
      $font{$fontname}[foFONTOBJ]      = $ttfont;
      $objRef{$ttfont->fontAbbr}       = $ttfont->obj_num;
      $fontSource{$fontname}[foSOURCE] = 'Standard';
   }

   my $oldIntNamn = $aktuellFont[foINTNAMN];
   my $oldExtNamn = $aktuellFont[foEXTNAMN]; 

   $aktuellFont[foEXTNAMN]   = $fontname;
   $aktuellFont[foREFOBJ]    = $font{$fontname}[foREFOBJ];
   $aktuellFont[foINTNAMN]   = $font{$fontname}[foINTNAMN];
   $aktuellFont[foTYP]       = $font{$fontname}[foTYP];

   $sidFont{$aktuellFont[foINTNAMN]} = $aktuellFont[foREFOBJ];

   if (wantarray)
   { return ($aktuellFont[foINTNAMN], $aktuellFont[foEXTNAMN], $oldIntNamn, $oldExtNamn, \%font);
   }
   else
   { return $aktuellFont[foINTNAMN];
   }
}


sub prObj
{  my($objNr, $data) = @_;

   $objekt[$objNr] = $pos;
   $pos += syswrite UTFIL, $data;
}


sub findTTFont
{  my $selector = shift || $aktuellFont[foEXTNAMN];

   return $font{$selector}[foFONTOBJ] if $font{$selector};
   foreach my $name (keys %font)
   {  if (  $font{$name}[foINTNAMN] eq $selector 
         or $font{$name}[foFONTOBJ] && $font{$name}[foFONTOBJ]->filename eq $selector
      ) 
      {  return $font{$name}[foFONTOBJ];
      }
   }
   return;
}


sub ttfStrWidth
{  my($string, $selector, $fontsize) = @_;

   my $ttfont = findTTFont($selector) or return;
   return $ttfont->text_width($string, $fontsize);
}


# This 'glue' package emulates the bits of the Text::PDF::File API that are
# needed by Text::PDF::TTFont0 (below) and ties them in to the PDF::Reuse API.

package PDF::Reuse::DocProxy;

sub new
{  my $class = shift;

   my $self = bless { ' version' => 3, @_, '>buffer'  => '', }, $class;
}


sub new_obj
{  my $self = shift;
   my $obj  = shift  or die 'No base for new_obj';

   my $num = $self->{next_obj}->();
   my $gen = 0;

   $self->{' objcache'}{$num, $gen} = $obj;
   $self->{' objects'}{$obj->uid}   = [ $num, $gen ];
   return $obj;
}


sub object_number
{  my($self, $obj) = @_;
   my $num = $self->{' objects'}{$obj->uid} || return;
   return $num->[0];
}


sub print
{  my($self, $data) = @_;

   if(my($tail, $rest) = $data =~ m{\A(.*?\nendobj\n)(.*)\z}s)
   {  my($obj_num) = $self->{'>buffer'} =~ /(\d+)/;
      # Pass serialised object back to PDF::Reuse
      $self->{prObj}->($obj_num, $self->{'>buffer'} . $tail);
      $self->{'>buffer'} = $rest;
   }
   else
   {  $self->{'>buffer'} .= $data;
   }
}


sub printf
{  my($self, $format, @args) = @_;;
   $self->print(sprintf($format, @args));
}


sub out_obj
{  my($self, $obj) = @_;
   return $self->new_obj($obj) unless defined $self->{' objects'}{$obj->uid};
   push @{ $self->{'>todo'} }, $obj->uid;
}


sub tell
{  return length shift->{'>buffer'};
}


sub write_objects
{  my($self) = @_;

   $self->{'>done'} = {};
   $self->{'>todo'} = [ sort map { $_->uid } values %{ $self->{' objcache'} } ];
   while(my $id = shift @{ $self->{'>todo'} }) {
      next if $self->{'>done'}{$id};
      my($num, $gen) = @{ $self->{' objects'}{$id} };
      $self->printf("%d %d obj\n", $num, $gen);
      $self->{' objcache'}{$num, $gen}->outobjdeep($self, $self);
      $self->print("\nendobj\n");
      $self->{'>done'}{$id}++;
   }
}


# This is a wrapper around Text::PDF::TTFont0, which provides support for
# embedding TrueType fonts

package PDF::Reuse::TTFont;

sub new
{  my $class = shift;

   require Text::PDF::TTFont0;

   my $self = bless { 'subset'   => 1, @_, }, $class;

   $self->{ttfont} = Text::PDF::TTFont0->new(
      $self->{docProxy}, 
      $self->{filename},
      $self->{fontAbbr},
      -subset => $self->{subset},
   );
   $self->{ttfont}->{' subvec'} = '';

   $self->{obj_num} = $self->{docProxy}->object_number($self->{ttfont});

   $self->{fontname} ||= $self->find_name();

   return $self;
}

sub filename  { return $_[0]->{filename};     }
sub fontname  { return $_[0]->{fontname};     }
sub obj_num   { return $_[0]->{obj_num};      }
sub fontAbbr  { return $_[0]->{fontAbbr};     }
sub docProxy  { return $_[0]->{docProxy};     }

sub find_name
{  my $self = shift;
   my($filebase) = $self->filename =~ m{.*[\\/](.*)\.};
   my $font = $self->{ttfont}->{' font'} or return $filebase;
   my $obj  = $font->{'name'}            or return $filebase;
   my $name = $obj->read->find_name(4)   or return $filebase;
   $name =~ s{\W}{}g;
   return $name;
}

sub encode_text
{  my($self, $text) = @_;
   $text =~ s|\\\(|(|gos;
   $text =~ s|\\\)|)|gos;
   return $self->{ttfont}->out_text($text);
}

sub text_width
{  my($self, $text, $size) = @_;
   return $self->{ttfont}->width($text) * $size;
}


package PDF::Reuse;  # Applies to the autoloaded methods below (?)

1;

__END__

=head1 NAME

PDF::Reuse - Reuse and mass produce PDF documents   

=head1 SYNOPSIS

=for SYNOPSIS.pl begin

   use PDF::Reuse;                     
   prFile('myFile.pdf');
   prText(100, 500, 'Hello World !');
   prEnd();

=for end

=head1 DESCRIPTION

This module could be used when you want to mass produce similar (but not identical)
PDF documents and reuse templates, JavaScripts and some other components. It is
functional to be fast, and to give your programs capacity to produce many pages
per second and very big PDF documents if necessary.

The module produces PDF-1.4 files. Some features of PDF-1.5, like "object streams"
and "cross reference streams", are supported, but only at an experimental level. More
testing is needed. (If you get problems with a new document from Acrobat 6 or higher, try to 
save it or recreate it as a PDF-1.4 document first, before using it together with 
this module.) 

=over 2

=item Templates

Use your favorite program, probably a commercial visual tool, to produce single 
PDF-files to be used as templates, and then use this module to B<mass produce> files 
from them. 

(If you want small PDF-files or want special graphics, you can use this module also,
but visual tools are often most practical.)

=item Lists

The module uses "XObjects" extensively. This is a format that makes it possible
create big lists, which are compact at the same time.


=item PDF-operators

The module gives you a good possibility to program at a "low level" with the basic
graphic operators of PDF, if that is what you want to do. You can build your
own libraries of low level routines, with PDF-directives "controlled" by Perl.

=item Archive-format

If you want, you get your new documents logged in a format suitable for archiving 
or transfer.


PDF::Reuse::Tutorial might show you best what you can do with this module.

=item JavaScript

You can attach JavaScripts to your PDF-files.

You can have libraries of JavaScripts. No cutting or pasting, and those who include 
the scripts in documents only need to know how to initiate them. (Of course those
who write the scripts have to know Acrobat JavaScript well.)

=back

=head2 Remarks about JavaScript

Some of the functions handling JavaScript have to be rewritten for Acrobat 7.

There are many limitations with Acrobat JavaScript, and the rules often change.
So what works for one version of Acrobat/Reader, might not work for another.
Another complication is this:
When documents are downloaded via the net by Acrobat, they are most often
converted (!) and necessary JavaScripts are lost.


=head1 FUNCTIONS

All functions which are successful return specified values or 1.

The module doesn't make any attempt to import anything from encrypted files.

=head1 Overview

To write a program with PDF::Reuse, you need these components:

=begin html

<style>
 pre span.comment {
  color:AA0000 ;
  font-style: italic;
}
</style>


<TABLE  border=1 cellpadding="7">
  <THEAD bgcolor="lightblue">
    <TH title="Mandatory">First</TH>
    <TH title="Slightly deprecated functions for your output">Perhaps*</TH>
    <TH title="Mandatory">Always</TH>
    <TH title="If you want to add someting">Any or None</TH>
    <TH title="Often you need to indicate that you need a new page and possibly from where">Probably**</TH>
    <TH title="Mandatory">Finally</TH>
  </THEAD>
  <TR valign="top" bgcolor="lightgreen">
    <TD title="To include the module"><B>use PDF::Reuse</B></TD>
    <TD></TD>
    <TD title="Finish an old document and direct output for a new document"><B>prFile</B></TD>
    <TD title="To add new contents, JavaScript, links and so on..">prInitVars<BR>
        prExtract<BR>
        prForm<BR>
        prInit<BR>
        prField<BR>
        prImage<BR>
        prJpeg<BR>
        prFont<BR>
        prFontSize<BR>
        prTTFont<BR>
        prGraphState<BR>
        prAdd<BR>
        prText<BR>
        prJs<BR>
        prCompress<BR>
        prMbox<BR>
        prBookmark<BR>
        prStrWidth<BR>
        prLink</TD>
     <TD title="These functions collect available contents and create the pages">prDoc<BR>
         prPage<BR>
         prSinglePage</TD>
     <TD title="To finish last document and clean up"><B>prEnd</B></TD>
   <TR valign="top" bgcolor="lightyellow">
     <TD></TD>
     <TD>prDocDir*<BR>
         prLogDir*</TD>
     <TD></TD>
     <TD>prDocForm*<BR>
        prGetLogBuffer*<BR>
        prBar*<BR>
        prLog*<BR>
        prTouchUp*<BR>
	prVers*<BR>
        prCid*<BR>
        prId*<BR>
        prIdType*<BR></TD>
      <TD></TD>
      <TD></TD>
    </TR>
    <TR bgcolor="lightgrey">
      <TD colspan=6> * = internal/ deprecated function</TD>
    </TR>
    <TR bgcolor="lightgrey">
      <TD colspan=6> ** = not needed before prEnd or a new prFile<BR>
      In those cases prPage is automatically inserted </TD>
    </TR>
  </TABLE>



=end html

=head1 Mandatory Functions

=head2 prFile		- define output

Alternative 1:

   prFile ( $fileName );

Alternative 2 with parameters in an anonymous hash:

   prFile ( { Name         => $fileName,
              HideToolbar  => 1,            # 1 or 0
              HideMenubar  => 1,            # 1 or 0
              HideWindowUI => 1,            # 1 or 0
              FitWindow    => 1,            # 1 or 0
              CenterWindow => 1   } );      # 1 or 0

Alternative 3:

   prFile ( $r );  # For mod_perl 2 pass the request object

$fileName is optional, just like the rest of the parameters.
File to create. If another file is current when this function is called, the first
one is written and closed. Only one file is processed at a single moment. If
$fileName is undefined, output is written to STDOUT. 

HideToolbar, HideMenubar, HideWindowUI, FitWindow and CenterWindow control the
way the document is initially displayed. 

Look at any program in this documentation for examples. prInitVars() shows how
this function could be used together with a web server.

=head2 prEnd		- end/flush buffers 

   prEnd ()

When the processing is going to end, the buffers of the B<last> file has to be written to the disc.
If this function is not called, the page structure, xref part and so on will be 
lost.

Look at any program in this documentation for an example.

=head1 Optional Functions

=head2 prAdd		- add "low level" instructions 

    prAdd ( $string )

With this command you can add whatever you want to the current content stream.
No syntactical checks are made, but if you use an internal name, the module tries
to add the resource of the "name object" to the "Resources" of current page.
"Name objects" always begin with a '/'. 

(In this documentation I often use talk about an "internal name". It denotes a 
"name object". When PDF::Reuse creates these objects, it assigns Ft1, Ft2, Ft3 ...
for fonts, Ig1, Ig2, Ig3 for images, Fo1 .. for forms, Cs1 .. for Color spaces,
Pt1 .. for patterns, Sh1 .. for shading directories, Gs0 .. for graphic state
parameter dictionaries. These names are kept until the program finishes, 
and my ambition is also to keep the resources available in internal tables.)

This is a simple and very powerful function. You should study the examples and 
the "PDF-reference manual", if you want to use it.(When this text is written,
a possible link to download it is: 
http://partners.adobe.com/asn/developer/acrosdk/docs.html) 

This function is intended to give you detail control at a low level.

   use PDF::Reuse;
   use strict;

   prFile('myFile.pdf');
   my $string = "150 600 100 50 re\n";  # a rectangle 
   $string   .= "0 0 1 rg\n";           # blue (to fill)
   $string   .= "b\n";                  # fill and stroke
   prAdd($string);                       
   prEnd(); 


=head2 prBookmark		- define bookmarks 

   prBookmark($reference)

Defines a "bookmark". $reference refers to a hash or array of hashes which looks
something like this:
 
          {  text  => 'Document',
             act   => 'this.pageNum = 0; this.scroll(40, 500);',
             kids  => [ { text => 'Chapter 1',
                          act  => '1, 40, 600'
                        },
                        { text => 'Chapter 2',
                          act  => '10, 40, 600'
                        } 
                      ]
          }

Each hash can have these components:

        text    the text shown beside the bookmark
        act     the action to be triggered. Has to be a JavaScript action.
                (Three simple numbers are translated to page, x and y in the
                sentences: this.pageNum = page; this.scroll(x, y); )
        kids    will have a reference to another hash or array of hashes
        close   if this component is present, the bookmark will be closed
                when the document is opened
        color   3 numbers, RGB-colors e.g. '0.5 0.5 1' for light blue
        style   0, 1, 2, or 3. 0 = Normal, 1 = Italic, 2 = Bold, 3 = Bold Italic

Creating bookmarks for a document:

    use PDF::Reuse;
    use strict;

    my @pageMarks;

    prFile('myDoc.pdf');

    for (my $i = 0; $i < 100; $i++)
    {   prText(40, 600, 'Something is written');
        # ...
        my $page = $i + 1;
        my $bookMark = { text => "Page $page",
                         act  => "$i, 40, 700" };
        push @pageMarks, $bookMark;
        prPage();
    }
    prBookmark( { text  => 'Document',
                  close => 1,
                  kids  => \@pageMarks } );
    prEnd();


Traditionally bookmarks have mainly been used for navigation within a document,
but they can be used for many more things. You can e.g. use them to navigate within
your data. You can let your users go to external links also, so they can "drill down"
to other documents.

B<See "Remarks about JavaScript">

=head2 prCompress		- compress/zip added streams 

   prCompress (1)

'1' here is a directive to compress all B<new> streams of the current file. Streams
which are included with prForm, prDocForm, prDoc or prSinglePage are not changed. New 
JavaScripts are also created as streams and compressed, if they are at least 100
bytes long. The streams are compressed in memory, so probably there is a limit of
how big they can be.

prCompress(); is a directive not to compress. This is default.

See e.g. "Starting to reuse" in the tutorial for an example.

=head2 prDoc		- include pages from a document 

   prDoc ( $documentName, $firstPage, $lastPage )

or with the parameters in an anonymous hash:

   prDoc ( { file  => $documentName,
             first => $firstPage,
             last  => $lastPage } );

Returns number of extracted pages.

If "first" is not given, 1 is assumed. If "last" is not given, you don't have any upper
limit. N.B. The numbering of the pages differs from Acrobat JavaScript. In JavaScript
the first page has index 0. 

Adds pages from a document to the one you are creating.
N.B. From version 0.32 of this module:
If there are contents created with with prText, prImage,prAdd, prForm and so on,
prDoc tries to put the contents on the first extracted page
from the old document.  


If it is the first interactive
component ( prDoc() or prDocForm() ) the interactive functions are kept and also merged
with JavaScripts you have added, if any. But, if you specify a first page different than 1
or a last page, no JavaScript are extracted from the document, because then there is a
risk that an included JavaScript function might refer to something not included.

   use PDF::Reuse;
   use strict;

   prFile('myFile.pdf');                  # file to make
   prJs('customerResponse.js');           # include a JavaScript file
   prInit('nameAddress(12, 150, 600);');  # init a JavaScript function
   prForm('best.pdf');                    # page 1 from best.pdf
   prPage();
   prDoc('long.pdf');                     # a document with 11 pages
   prForm('best.pdf');                    # page 1 from best.pdf
   prText(150, 700, 'Customer Data');     # a line of text
   prEnd();

To extract pages 2-3 and 5-7 from a document and create a new document:

   use PDF::Reuse;
   use strict;
    
   prFile('new.pdf');
   prDoc( { file  => 'old.pdf',
            first => 2, 
            last  => 3 });
   prDoc( { file  => 'old.pdf',
            first => 5, 
            last  => 7 });
   prEnd();
   
   
To add a form, image and page number to each page of an 16 pages long document
(The document Battery.pdf is cropped so each page is fairly small)  You could also have
used prSinglePage, look at a very similar example under that function.

   use PDF::Reuse;
   use PDF::Reuse::Util;
   use strict;
     
   prFile('test.pdf');
     
     my $pageNumber = 0;
     
     for (my $page = 1; $page < 17; $page++)
     {   $pageNumber++;
         prForm(  { file =>'Words.pdf',
                    page => 5,
                    x    => 150,
                    y    => 150} );
                    
         prImage( { file =>'Media.pdf',
                    page => 6,
                    imageNo => 1,
                    x  => 450,
                    y  => 450 } );
         blackText();
         prText( 360, 250, $pageNumber);
         prDoc('Battery.pdf', $pageNumber, $pageNumber);
     }
   prEnd;


=head2 prDocDir		- set directory for produced documents 

   prDocDir ( $directoryName )

Sets directory for produced documents

   use PDF::Reuse;
   use strict;

   prDocDir('C:/temp/doc');
   prFile('myFile.pdf');         # writes to C:\temp\doc\myFile.pdf
   prForm('myFile.pdf');         # page 1 from ..\myFile.pdf
   prText(200, 600, 'New text');
   prEnd();

=head2 prDocForm		- use an interactive page as a form 

Alternative 1) You put your parameters in an anonymous hash (only B<file> is really 
necessary, the others get default values if not given).

   prDocForm ( { file     => $pdfFile,       # template file
                 page     => $page,          # page number (of imported template)
                 adjust   => $adjust,        # try to fill the media box
                 effect   => $effect,        # action to be taken
                 tolerant => $tolerant,      # continue even with an invalid form
                 x        => $x,             # $x points from the left
                 y        => $y,             # $y points from the bottom
                 rotate   => $degree,        # rotate 
                 size     => $size,          # multiply everything by $size
                 xsize    => $xsize,         # multiply horizontally by $xsize
                 ysize    => $ysize } )      # multiply vertically by $ysize
Ex.:
    my $internalName = prDocForm ( {file     => 'myFile.pdf',
                                    page     => 2 } );
              
Alternative 2) You put your parameters in this order

	prDocForm ( $pdfFile, [$page, $adjust, $effect, $tolerant, $x, $y, $degree,
            $size, $xsize, $ysize] )


Anyway the function returns in list context:  B<$intName, @BoundingBox, 
$numberOfImages>, in scalar context:  B<$internalName> of the form.

Look at prForm() for an explanation of the parameters.

N.B. Usually you shouldn't adjust or change size and proportions of an interactive
page. The graphic and interactive components are independent of each other and there 
is a great risk that any coordination is lost. 

This function redefines a page to an "XObject" (the graphic parts), then the 
page can be reused in a much better way. Unfortunately there is an important 
limitation here. "XObjects" can only have single streams. If the page consists
of many streams, you should concatenate them first. Adobe Acrobat can do that.
(If it is an important file, take a copy of it first. Sometimes the procedure fails.)
Open the document with Acrobat. Then choose the the "TouchUp Text" tool (icon or 
from the tools menu). Select a line of text somewhere on the page. Right-click the
mouse. Choose "Attributes".Change font size or anything else, and then you change
it back to the old value. Save the document.
If there was no text on the page, use some other "Touch Up" tool.


   use PDF::Reuse;
   use strict;

   prDocDir('C:/temp/doc');
   prFile('newForm.pdf');
   prField('Mr/Ms', 'Mr');
   prField('First_Name', 'Lars');
   prDocForm('myFile.pdf');
   prFontSize(24);
   prText(75, 790, 'This text is added');
   prEnd();

(You can use the output from the example in prJs() as input to this example.
Remember to save that file before closing it.)

B<See Remarks about JavaScript>

=head2 prExtract		- extract an object group 

   prExtract ( $pdfFile, $pageNo, $oldInternalName )

B<oldInternalName>, a "name"-object.  This is the internal name you find in the original file.
Returns a B<$newInternalName> which can be used for "low level" programming. You
have better look at graphObj_pl and modules it has generated for the tutorial,
e.g. thermometer.pm, to see how this function can be used.  

When you call this function, the necessary objects will be copied to your new
PDF-file, and you can refer to them with the new name you receive.


=head2 prField		- assign a value to an interactive field 

	prField ( $fieldName, $value )

B<$fieldName> is an interactive field in the document you are creating.
It has to be spelled exactly the same way here as it spelled in the document.
B<$value> is what you want to assigned to the field.
Put all your sentences with prField early in your script. After prFile and B<before>
prDoc or prDocForm and of course before prEnd. Each sentence with prField is 
translated to JavaScript and merged with old JavaScript  

See prDocForm() for an example

If you are going to assign a value to a field consisting of several lines, you
can write like this:

   my $string = "This is the first line \r second line \n 3:rd line";
   prField('fieldName', $string);

You can also let '$value' be a  snippet of JavaScript-code that assigns something
to the field. Then you have to put 'js:' first in "$value" like this:

   my $sentence = encrypt('This will be decrypted by "unPack"(JavaScript) ');
   prField('Interest_9', "js: unPack('$sentence')");

If you refer to a JavaScript function, it has to be included with prJs first. (The
JavaScript interpreter will simply not be aware of old functions in the PDF-document,
when the initiation is done.)


=head2 prFont		- set current font 

   prFont ( $fontName )

$fontName is an "external" font name. The parameter is optional. 
In list context returns B<$internalName, $externalName, $oldInternalName,
$oldExternalname> The first two variables refer to the current font, the two later
to the font before the change. In scalar context returns b<$internalName>

If a font wasn't found, Helvetica will be set.
These names are always recognized:
B<Times-Roman, Times-Bold, Times-Italic, Times-BoldItalic, Courier, Courier-Bold,
Courier-Oblique, Courier-BoldOblique, Helvetica, Helvetica-Bold, Helvetica-Oblique,
Helvetica-BoldOblique> or abbreviated 
B<TR, TB, TI, TBI, C, CB, CO, CBO, H, HB, HO, HBO>. 
(B<Symbol and ZapfDingbats> or abbreviated B<S, Z>, also belong to the predefined
fonts, but there is something with them that I really don't understand. You should
print them first on a page, and then use other fonts, otherwise they are not displayed.)

You can also use a font name from an included page. It has to be spelled exactly as
it is done there. Look in the file and search for "/BaseFont" and the font
name. But take care, e.g. the PDFMaker which converts to PDF from different 
Microsoft programs, only defines exactly those letters you can see on the page. You
can use the font, but perhaps some of your letters were not defined. 

In the distribution there is an utility program, 'reuseComponent_pl', which displays
included fonts in a PDF-file and prints some letters. Run it to see the name of the
font and if it is worth extracting.

   use PDF::Reuse;
   use strict;
   prFile('myFile.pdf');

   ####### One possibility #########

   prFont('Times-Roman');     # Just setting a font
   prFontSize(20);
   prText(180, 790, "This is a heading");

   ####### Another possibility #######

   my $font = prFont('C');    # Setting a font, getting an  
                              # internal name
   prAdd("BT /$font 12 Tf 25 760 Td (This is some other text)Tj ET"); 
   prEnd();

The example above shows you two ways of setting and using a font. One simple, and
one complicated with a possibility to detail control. 


=head2 prFontSize		- set current font size 

   prFontSize ( $size )

Returns B<$actualSize, $fontSizeBeforetheChange>. Without parameters
prFontSize() sets the size to 12 points, which is default. 

=head2 prForm		- use a page from an old document as a form/background 

Alternative 1) You put your parameters in an anonymous hash (only B<file> is really 
necessary, the others get default values if not given).

   prForm ( { file     => $pdfFile,       # template file
              page     => $page,          # page number (of imported template)
              adjust   => $adjust,        # try to fill the media box
              effect   => $effect,        # action to be taken
              tolerant => $tolerant,      # continue even with an invalid form
              x        => $x,             # $x points from the left
              y        => $y,             # $y points from the bottom
              rotate   => $degree,        # rotate 
              size     => $size,          # multiply everything by $size
              xsize    => $xsize,         # multiply horizontally by $xsize
              ysize    => $ysize } )      # multiply vertically by $ysize
Ex.:
    my $internalName = prForm ( {file     => 'myFile.pdf',
                                 page     => 2 } );
              
Alternative 2) You put your parameters in this order

	prForm ( $pdfFile, $page, $adjust, $effect, $tolerant, $x, $y, $degree,
            $size, $xsize, $ysize )


Anyway the function returns in list context:  B<$intName, @BoundingBox, 
$numberOfImages>, in scalar context:  B<$internalName> of the form. 

if B<page> is excluded 1 is assumed. 

B<adjust>, could be 1, 2 or 0/nothing. If it is 1, the program tries to adjust the
form to the current media box (paper size) and keeps the proportions unchanged.
If it is 2, the program tries to fill as much of the media box as possible, without 
regards to the original proportions.
If this parameter is given, "x", "y", "rotate", "size", "xsize" and "ysize"
will be ignored.

B<effect> can have 3 values: B<'print'>, which is default, loads the page in an internal
table, adds it to the document and prints it to the current page. B<'add'>, loads the
page and adds it to the document. (Now you can "manually" manage the way you want to
print it to different pages within the document.) B<'load'> just loads the page in an 
internal table. (You can now take I<parts> of a page like fonts and objects and manage
them, without adding all the page to the document.)You don't get any defined 
internal name of the form, if you let this parameter be 'load'.

B<tolerant> can be nothing or something. If it is undefined, you will get an error if your program tries to load
a page which the system cannot really handle, if it e.g. consists of many streams.
If it is set to something, you have to test the first return value $internalName to
know if the function was successful. Look at the program 'reuseComponent_pl' for an 
example of usage.

B<x> where to start along the x-axis   (cannot be combined with "adjust")

B<y> where to start along the y-axis   (cannot be combined with "adjust")

B<rotate> A degree 0-360 to rotate the form counter-clockwise. (cannot be combined
with "adjust") Often the form disappears out of the media box if degree >= 90.
Then you can move it back with the x and y-parameters. If degree == 90, you can 
add the width of the form to x, If degree == 180 add both width and height to x
and y, and if degree == 270 you can add the height to y.

B<rotate> can also by one of 'q1', 'q2' or 'q3'. Then the system rotates the form
clockwise 90, 180 or 270 degrees and tries to keep the form within the media box.

The rotation takes place after the form has been resized or moved.

   Ex. To rotate from portrait (595 x 842 pt) to landscape (842 x 595 pt)

   use PDF::Reuse;
   use strict;
   
   prFile('New_Report.pdf');
   prMbox(0, 0, 842, 595);           
   
   prForm({file   => 'cert1.pdf',
           rotate => 'q1' } );  
   prEnd();

The same rotation can be achieved like this:

   use PDF::Reuse;
   use strict;
   
   prFile('New_Report.pdf');
   prMbox(0, 0, 842, 595);
               
   prForm({file   => 'cert1.pdf',
           rotate => 270,
           y      => 595 } );  
   prEnd();

B<size> multiply every measure by this value (cannot be combined with "adjust") 

B<xsize> multiply horizontally by this value (cannot be combined with "adjust")

B<ysize> multiply vertically by $ysize (cannot be combined with "adjust")

This function redefines a page to an "XObject" (the graphic parts), then the 
page can be reused and referred to as a unit. Unfortunately there is an important 
limitation here. "XObjects" can only have single streams. If the page consists
of many streams, you should concatenate them first. Adobe Acrobat can do that.
(If it is an important file, take a copy of it first. Sometimes the procedure fails.)
Open the document with Acrobat. Then choose the "TouchUp Text" tool.
Select a line of text somewhere. Right-click the mouse. Choose "Attributes".
Change font size or anything else, and then you change it back to the old value.
Save the document. You could alternatively save the file as Postscript and redistill
it with the distiller or with Ghost script, but this is a little more risky. You 
might loose fonts or something else. An other alternative could be to use prSinglePage().


   use PDF::Reuse;
   use strict;

   prFile('myFile.pdf');
   prForm('best.pdf');    # Takes page No 1
   prText(75, 790, 'Dear Mr Gates');
   # ...
   prPage();
   prMbox(0, 0, 900, 960);
   my @vec = prForm(   { file => 'EUSA.pdf',
                         adjust => 1 } );
   prPage();
   prMbox();
   prText(35, 760, 'This is the final page');

   # More text ..

   #################################################################
   # We want to put a miniature of EUSA.pdf, 35 points from the left
   # 85 points up, and in the format 250 X 200 points
   #################################################################

   my $xScale = 250 / ($vec[3] - $vec[1]);
   my $yScale = 200 / ($vec[4] - $vec[2]);
   
   prForm ({ file => 'EUSA.pdf',
             xsize => $xScale,
             ysize => $yScale,
             x     => 35,
             y     => 85 });

   prEnd();

The first prForm(), in the code, is a simple and "normal" way of using the
the function. The second time it is used, the size of the imported page is
changed. It is adjusted to the media box which is current at that moment.
Also data about the form is taken, so you can control more in detail how it
will be displayed. 

=head2 prGetLogBuffer		- get the log buffer. 

prGetLogBuffer ()

returns a B<$buffer> of the log of the current page. (It could be used
e.g. to calculate a MD5-digest of what has been registered that far, instead of 
accumulating the single values) A log has to be active, see prLogDir() below

Look at "Using the template" and "Restoring a document from the log" in the
tutorial for examples of usage.

=head2 prGraphState		- define a graphic state parameter dictionary 

   prGraphState ( $string )

This is a "low level" function. Returns B<$internalName>. The B<$string> has to 
be a complete dictionary with initial "<<" and terminating ">>". No syntactical
checks are made. Perhaps you will never have to use this function.

   use PDF::Reuse;
   use strict;

   prFile('myFile.pdf');

   ###################################################
   # Draw a triangle with Gs0 (automatically defined)
   ###################################################

   my $str = "q\n";
   $str   .= "/Gs0 gs\n";
   $str   .= "150 700 m\n";
   $str   .= "225 800 l\n";
   $str   .= "300 700 l\n";
   $str   .= "150 700 l\n";
   $str   .= "S\n";
   $str   .= "Q\n";
   prAdd($str);

   ########################################################
   # Define a new graph. state param. dic. and draw a new
   # triangle further down 
   ########################################################

   $str = '<</Type/ExtGState/SA false/SM 0.02/TR2 /Default'
                      . '/LW 15/LJ 1/ML 1>>';
   my $gState = prGraphState($str);
   $str  = "q\n";
   $str .= "/$gState gs\n";
   $str .= "150 500 m\n";
   $str .= "225 600 l\n";
   $str .= "300 500 l\n";
   $str .= "150 500 l\n";
   $str .= "S\n";
   $str .= "Q\n";
   prAdd($str);
   
   prEnd();


=head2 prImage		- reuse an image from an old PDF document 

Alternative 1) You put your parameters in an anonymous hash (only B<file> is really 
necessary, the others get default values if not given).

   prImage( { file     => $pdfFile,       # template file
              page     => $page,          # page number
              imageNo  => $imageNo        # image number
              adjust   => $adjust,        # try to fill the media box
              effect   => $effect,        # action to be taken
              x        => $x,             # $x points from the left
              y        => $y,             # $y points from the bottom
              rotate   => $degree,        # rotate 
              size     => $size,          # multiply everything by $size
              xsize    => $xsize,         # multiply horizontally by $xsize
              ysize    => $ysize } )      # multiply vertically by $ysize
Ex.:
   prImage( { file    => 'myFile.pdf',
              page    => 10,
              imageNo => 2 } );
              
Alternative 2) You put your parameters in this order

	prImage ( $pdfFile, [$page, $imageNo, $effect, $adjust, $x, $y, $degree,
            $size, $xsize, $ysize] )

Returns in scalar context B<$internalName> As a list B<$internalName, $width, 
$height> 

Assumes that $pageNo and $imageNo are 1, if not specified. If $effect is given and
anything else then 'print', the image will be defined in the document,
but not shown at this moment.

For all other parameters, look at prForm().

   use PDF::Reuse;
   use strict;

   prFile('myFile.pdf'); 
   my @vec = prImage({ file  => 'best.pdf',
                       x     => 10,
                       y     => 400,
                       xsize => 0.9,
                       ysize => 0.8 } );
   prText(35, 760, 'This is some text');
   # ...
   prPage();
   my @vec2 = prImage( { file    => 'destiny.pdf',
                         page    => 1,
                         imageNo => 1,
                         effect  => 'add' } );
   prText(25, 760, "There shouldn't be any image on this page");
   prPage();
   ########################################################
   #  Now we make both images so that they could fit into
   #  a box 300 X 300 points, and they are displayed
   ########################################################

   prText(25, 800, 'This is the first image :');

   my $xScale = 300 / $vec[1];
   my $yScale = 300 / $vec[2];
   if ($xScale < $yScale)
   {  $yScale = $xScale;
   }
   else
   {  $xScale = $yScale;
   }
   prImage({ file   => 'best.pdf',
             x      => 25,
             y      => 450,
             xsize  => $xScale,
             ysize  => $yScale} );

   prText(25, 400, 'This is the second image :');

   $xScale = 300 / $vec2[1];
   $yScale = 300 / $vec2[2];
   if ($xScale < $yScale)
   {  $yScale = $xScale;
   }
   else
   {  $xScale = $yScale;
   }
   prImage({ file   => 'destiny.pdf',
             x      => 25,
             y      => 25,
             xsize  => $xScale,
             ysize  => $yScale} );

   prEnd();

On the first page an image is displayed in a simple way. While the second page
is processed, prImage(), loads an image, but it is not shown here. On the 3:rd
page, the two images are scaled and shown. 

In the distribution there is an utility program, 'reuseComponent_pl', which displays
included images in a PDF-file and their "names".

=head2 prInit		- add JavaScript to be executed at initiation 

   prInit ( $string, $duplicateCode )

B<$string> can be any JavaScript code, but you can only refer to functions included
with prJs. The JavaScript interpreter will not know other functions in the document.
Often you can add new things, but you can't remove or change interactive fields,
because the interpreter hasn't come that far, when initiation is done.

B<$duplicateCode> is undefined or anything. It duplicates the JavaScript code
which has been used at initiation, so you can look at it from within Acrobat and
debug it. It makes the document bigger. This parameter is B<deprecated>.

   use PDF::Reuse;
   use strict;
   
   prFile('myFile.pdf');
   prInit('app.alert("This is displayed when opening the document");');
      
   prEnd();


Remark: Avoid to use "return" in the code you use at initiation. If your user has
downloaded a page with Web Capture, and after that opens a PDF-document where a 
JavaScript is run at initiation and that JavaScript contains a return-statement,
a bug occurs. The JavaScript interpreter "exits" instead of returning, the execution
of the JavaScript might finish to early. This is a bug in Acrobat/Reader 5.


=head2 prInitVars		- initiate global variables and internal tables 

   prInitVars(1)

If you run programs with PDF::Reuse as persistent procedures, you probably need to
initiate global variables. If you have '1' or anything as parameter, internal tables for forms, images, fonts
and interactive functions are B<not> initiated. The module "learns" offset and sizes of
used objects, and can process them faster, but at the same time the size of the 
program grows.

   use PDF::Reuse;
   use strict;
   prInitVars();     # To initiate ALL global variables and tables
   # prInitVars(1);  # To make it faster, but more memory consuming

   $| = 1;
   print STDOUT "Content-Type: application/pdf \n\n";

   prFile();         # To send the document uncatalogued to STDOUT                

   prForm('best.pdf');
   prText(25, 790, 'Dear Mr. Anders Persson');
   # ...
   prEnd();

If you call this function without parameters all global variables, including the
internal tables, are initiated.


=head2 prJpeg		- import a jpeg-image 

   prJpeg ( $imageFile, $width, $height )

B<$imageFile> contains 1 single jpeg-image. B<$width> and B<$height>
also have to be specified. Returns the B<$internalName>

   use PDF::Reuse;
   use Image::Info qw(image_info dim);
   use strict;

   my $file = 'myImage.jpg';
   my $info = image_info($file);
   my ($width, $height) = dim($info);    # Get the dimensions

   prFile('myFile.pdf');
   my $intName = prJpeg("$file",         # Define the image 
                         $width,         # in the document
                         $height);

   my $str = "q\n";
   $str   .= "$width 0 0 $height 10 10 cm\n";
   $str   .= "/$intName Do\n";
   $str   .= "Q\n";
   prAdd($str);
   prEnd();

This is a little like an extra or reserve routine to add images to the document.
The most simple way is to use prImage()  

=head2 prJs		- add JavaScript 

   prJs ( $string|$fileName )

To add JavaScript to your new document. B<$string> has to consist only of
JavaScript functions: function a (..){ ... } function b (..) { ...} and so on
If B<$string> doesn't contain '{', B<$string> is interpreted as a filename.
In that case the file has to consist only of JavaScript functions.

B<See "Remarks about JavaScript">

=head2 prLink    - add a hyper link

   prLink( { page   => $pageNo,     # Starting with 1  !
             x      => $x,
             y      => $y,
             width  => $width,
             height => $height,
             URI    => $URI     } );

You can also call prLink like this:

   prLink($page, $x, $y, $width, $height, $URI);

You have to put prLink B<after prFile and before the sentences where its' page
is created>. The links are created at the page-breaks. If the page is already 
created, no new link will be inserted. 

Here is an example where the links of a 4 page document are preserved, and a link is
added at the end of the document. We assume that there is some suitable text at that
place (x = 400, y = 350):

   use strict;
   use PDF::Reuse;

   prFile('test.pdf');

   prLink( {page   => 4,
            x      => 400,
            y      => 350,
            width  => 105,
            height => 15,
            URI    => 'http://www.purelyInvented.com/info.html' } );

   prDoc('fourPages.pdf');

   prEnd();

( If you are creating each page of a document separately, you can also use 'hyperLink'
from PDF::Reuse::Util. Then you get an external text in Helvetica-Oblique, underlined
and in blue.

  use strict;
  use PDF::Reuse;
  use PDF::Reuse::Util;

  prFile('test.pdf');
  prForm('template.pdf', 5);
  my ($from, $pos) = prText(25, 700, 'To get more information  ');

  $pos = hyperLink( $pos, 700, 'Press this link',
                    'http://www.purelyInvented.com/info.html' );
  ($from, $pos) = prText( $pos, 700, ' And get connected');
  prEnd();

'hyperLink' has a few parameters: $x, $y, $textToBeShown, $hyperLink and
$fontSize (not shown in the example). It returns current x-position. )

=head2 prLog		- add a string to the log 

   prLog ( $string )

Adds whatever you want to the current log (a reference No, a commentary, a tag ?)
A log has to be active see prLogDir()

Look at "Using the template" and "Restoring the document from the log" in
the tutorial for an example.

=head2 prLogDir		- set directory for the log 

   prLogDir ( $directory )

Sets a directory for the logs and activates the logging. 
A little log file is created for each PDF-file. Normally it should be much, much
more compact then the PDF-file, and it should be possible to restore or verify 
a document with the help of it. (Of course you could compress or store the logs in a 
database to save even more space.) 

   use PDF::Reuse;
   use strict;

   prDocDir('C:/temp/doc');
   prLogDir('C:/run');

   prFile('myFile.pdf');
   prForm('best.pdf');
   prText(25, 790, 'Dear Mr. Anders Persson');
   # ...
   prEnd();

In this example a log file with the name 'myFile.pdf.dat' is created in the
directory 'C:\run'. If that directory doesn't exist, the system tries to create it.
(But, just as mkdir does, it only creates the last level in a directory tree.)

=head2 prMbox		- define the format (MediaBox) for a new page. 

   prMbox ( $lowerLeftX, $lowerLeftY, $upperRightX, $upperRightY )

If the function or the parameters are missing, they are set to 0, 0, 595, 842 points respectively.   
Only for new pages. Pages created with prDoc and prSinglePage keep their media boxes unchanged.

See prForm() for an example.


=head2 prPage		- create/insert a page

   prPage ($noLog)

Don't use the optional parameter, it is only used internally, not to clutter the log,
when automatic page breaks are made.


See prForm() for an example.

=head2 prSinglePage  - take single pages, one by one, from an old document

   prSinglePage($file, $pageNumber)

$pageNumber is optional. If not given, next page is assumed 
Returns number of remaining pages.
This function is a variant of prDoc for single pages, with the addition that it
has a counter of last page read, and total number of pages of the old document,
so it can be used to loop through a document.

   
To add a form, image and page number to each page of a document
(The document Battery.pdf is cropped so each page is fairly small)  You could also have
used prDoc, but only if you knew in advance the number of pages of the old document

   use PDF::Reuse;
   use PDF::Reuse::Util;
   use strict;
      
   prFile('test.pdf');
      
   my $pageNumber = 0;
   my $left = 1;            # Every valid PDF-document has at least 1 page,
                            # so that can be assumed  
    
   while ($left) 
   {   $pageNumber++;
       prForm(  { file =>'Words.pdf',
                  page => 5,
                  x    => 150,
                  y    => 150} );
                    
       prImage( { file    =>'Media.pdf',
                  page    => 6,
                  imageNo => 1,
                  x       => 450,
                  y       => 450 } );
       blackText();
       prText( 360, 250, $pageNumber);
       $left = prSinglePage('Battery.pdf');   
    } 
     
    prEnd;

prSinglePage creates a new page from an old document and adds new content (to the array of
streams of that page). Most often you can add new contents to the page like the example above,
and it works fine, but sometimes you get surprises. There can e.g. be instructions in the earlier
contents to make filling color white, and then you will probably not see added new text. That
is why PDF::Reuse::Util::blackText() is used in the example. There can be other instructions
like moving or rotating the user space. Also new contents can end up outside the crop-box.
Of course all new programs should be tested. If prSinglePage can't be used, try to use prForm
followed by prPage instead.


=head2 prStrWidth   - calculate the string width

   prStrWidth($string, $font, $fontSize)

Returns string width in points.
Should be used in conjunction with one of these predefined fonts of Acrobat/Reader:
Times-Roman, Times-Bold, Times-Italic, Times-BoldItalic, Courier, Courier-Bold, Courier-Oblique,
Courier-BoldOblique, Helvetica, Helvetica-Bold, Helvetica-Oblique,
Helvetica-BoldOblique or with a TrueType font embedded with prTTFont. If some other font is
given, Helvetica is used, and the returned value will at the best be approximate.

=head2 prText		- add a text-string 

   prText ( $x, $y, $string, $align, $rotation )

Puts B<$string> at position B<$x, $y>
Returns 1 in scalar context. Returns ($xFrom, $xTo) in list context. $xTo will not
be defined together with a rotation. prStrWidth() is used to calculate the length of the
strings, so only the predefined fonts together with Acrobat/Reader, or embedded TrueType
fonts will give reliable values for $xTo.      

$align can be 'left' (= default), 'center' or 'right'. The parameter is optional.

$rotation can be a degree 0 - 360, 'q1', 'q2' or 'q3'. Also optional.

Current font and font size are used. (If you use prAdd() before this function,
many other things could also influence the text.)

   use strict;
   use PDF::Reuse;

   prFile('test.pdf');

   #####################################
   # Use a "curser" ($pos) along a line
   #####################################

   my ($from, $pos) = prText(25, 800, 'First write this. ');
   ($from, $pos) = prText($pos, 800, 'Then write this. '); 
   prText($pos, 800, 'Finally write this.');

   #####################################
   # Right adjust and center sentences
   #####################################

   prText( 200, 750, 'A short sentence', 'right');
   prText( 200, 735, 'This is a longer sentence', 'right');
   prText( 200, 720, 'A word', 'right');

   prText( 200, 705, 'Centered around a point 200 points from the left', 'center');
   prText( 200, 690, 'The same center', 'center');
   prText( 200, 675, '->.<-', 'center');

   ############
   # Rotation
   ############

   prText( 200, 550, ' Rotate 0 degrees','', 0);
   prText( 200, 550, ' Rotate 60 degrees','', 60);
   prText( 200, 550, ' Rotate 120 degrees','', 120);
   prText( 200, 550, ' Rotate 180 degrees','', 180);
   prText( 200, 550, ' Rotate 240 degrees','', 240);
   prText( 200, 550, ' Rotate 300 degrees','', 300);

   prText( 400, 430, 'Rotate 90 degrees clock-wise','','q1');
   prText( 400, 430, 'Rotate 180 degrees clock-wise','', 'q2');
   prText( 400, 430, 'Rotate 270 degrees clock-wise','', 'q3');
   
   ##########################
   # Rotate and right adjust
   ##########################
   
   prText( 200, 230, 'Rotate 90 degrees clock-wise ra->','right','q1');
   prText( 200, 230, 'Rotate 180 degrees clock-wise ra->','right', 'q2');
   prText( 200, 230, 'Rotate 270 degrees clock-wise ra->','right', 'q3');
   
   prEnd();

=head2 prTTFont         - select and embed a TrueType font

  prTTFont ( "/path/to/font/file.ttf" )

This function is equivalent to C<prFont> except that rather than restricting
you to the list of core built-in fonts, it allows you to select an external
TrueType font file and have it embedded in your PDF document.  Using TrueType
fonts also enables the C<prText> function to accept UTF-8 strings, which allows
you to use characters outside the Mac-Roman/Win-ANSI character sets used by the
built-in fonts.

You can specify the same font path multiple times in one document and only one
copy will be embedded.  Alternatively, C<prTTFont> returns an identifier which
can be used to select the same font again:

  my $arial = prTTFont('/path/to/Arial.ttf');
  prFontSize(20);
  prText(20, 700, 'Some text in Arial');
  #
  # ... later ...
  #
  prPage();
  prTTFont($arial);
  prFontSize(12);
  prText(20, 700, 'Some more text in Arial');
  #
  #  to pass a UTF8 string to prText
  # 
  prText(20, 675, "T\x{113}n\x{101} koutou");  # T?n? Koutou 

In list context this function returns C<$internalName>, C<$externalName>,
C<$oldInternalName>, C<$oldExternalname>. The first two variables refer to the
current font, the last two refer to the font before the change. In scalar
context only C<$internalName> is returned.

Note: To use this function, you must have the L<Font::TTF> and L<Text::PDF>
modules installed.


=head1 INTERNAL OR DEPRECATED FUNCTIONS

=over 2

=item prBar		- define and paint bars for bar fonts 

   prBar ($x, $y, $string)

Prints a bar font pattern at the current page.
Returns $internalName for the font.
$x and $y are coordinates in points and $string should consist of the characters
'0', '1' and '2' (or 'G'). '0' is a white bar, '1' is a dark bar. '2' and 'G' are
dark, slightly longer bars, guard bars. 
You can use e.g. GD::Barcode or one module in that group to calculate the bar code
pattern. prBar "translates" the pattern to white and black bars.

   use PDF::Reuse;
   use GD::Barcode::Code39;
   use strict;

   prFile('myFile.pdf');
   my $oGdB = GD::Barcode::Code39->new('JOHN DOE');
   my $sPtn = $oGdB->barcode();
   prBar(100, 600, $sPtn);
   prEnd();

Internally the module uses a font for the bars, so you might want to change the font size before calling
this function. In that case, use prFontSize() .
If you call this function without arguments it defines the bar font but does
not write anything to the current page.

B<An easier and often better way to produce bar codes is to use PDF::Reuse::Barcode.> 
Look at that module!

=item prCid		- define time stamp/check id 

   prCid ( $timeStamp )

An internal function. Don't bother about it. It is used in automatic
routines when you want to restore a document. It gives modification time of
the next PDF-file or JavaScript.
See "Restoring a document from the log" in the tutorial for more about the
time stamp



=item prId		- define id-string of a PDF document 

   prId ( $string )

An internal function. Don't bother about it. It is used e.g. when a document is
restored and an id has to be set, not calculated.

=item prIdType		- define id-type 

   prIdType ( $string )

An internal function. Avoid using it. B<$string> could be "Rep" for replace or
"None" to avoid calculating an id.

Normally you don't use this function. Then an id is calculated with the help of
Digest::MD5::md5_hex and some data from the run.


=item prTouchUp		- make changes and reuse more difficult 

   prTouchUp (1);

By default and after you have issued prTouchUp(1), you can change the document
with the TouchUp tool from within Acrobat.
If you want to switch off this possibility, you use prTouchUp() without any 
parameter.  Then the user shouldn't be able to change anything graphic by mistake.
He has to do something premeditated and perhaps with a little effort.
He could still save it as Postscript and redistill, or he could remove or add single pages. 
(Here is a strong reason why the log files, and perhaps also check sums, are needed.
It would be very difficult to forge a document unless the forger also has access to your
computer and knows how the check sums are calculated.)

B<Avoid to switch off the TouchUp tool for your templates.> It creates an
extra level within the PDF-documents . Use this function for your final documents.

See "Using the template" in the tutorial for an example.

This function works for pages created with prPage, but mot with prDoc and prSinglePage,
So it is more or less deprecated as these function have developed. 

(To encrypt your documents: use the batch utility within Acrobat)


=item prVers		- check version of log and program 

   prVers ( $versionNo )

To check version of this module in case a document has to be
restored.

=back

=head1 SEE ALSO

   PDF::Reuse::Tutorial
   PDF::Reuse::Barcode
   PDF::Reuse::OverlayChart

To program with PDF-operators, look at "The PDF-reference Manual" which probably
is possible to download from http://partners.adobe.com/asn/tech/pdf/specifications.jsp
Look especially at chapter 4 and 5, Graphics and Text, and the Operator summary.

Technical Note # 5186 contains the "Acrobat JavaScript Object Specification". I 
downloaded it from http://partners.adobe.com/asn/developer/technotes/acrobatpdf.html

If you are serious about producing PDF-files, you probably need Adobe Acrobat sooner
or later. It has a price tag. Other good programs are GhostScript and GSview. 
I got them via http://www.cs.wisc.edu/~ghost/index.html  Sometimes they can replace Acrobat.
A nice little detail is e.g. that GSview shows the x- and y-coordinates better then Acrobat. If you need to convert HTML-files to PDF, HTMLDOC is a possible tool. Download it from
http://www.easysw.com . A simple tool for vector graphics is Mayura Draw 2.04, download
it from http://www.mayura.com. It is free. I have used it to produce the graphic
OO-code in the tutorial. It produces postscript which the Acrobat Distiller (you get it together with Acrobat)
or Ghostscript can convert to PDF.(The commercial product, Mayura Draw 4.01 or something 
higher can produce PDF-files straight away)

If you want to import jpeg-images, you might need

   Image::Info

To get definitions for e.g. colors, take them from

   PDF::API2::Util 

=head1 LIMITATIONS

Meta data, info and many other features of the PDF-format have not been
implemented in this module. 

Many things can be added afterwards, after creating the files. If you e.g. need
files to be encrypted, you can use a standard batch routine within Adobe Acrobat.   

=head1 THANKS TO

Martin Langhoff, Matisse Enzer, Yunliang Yu and others who have contributed with code, suggestions and error
reports.

Grant McLean has implemented font embedding by grafting Font::TTF and
Text::PDF::TTFont0 onto the PDF::Reuse API. He has written the embedded packages PDF::Reuse::DocProxy
and PDF::Reuse::TTFont.

The functionality of prDoc and prSinglePage to include new contents was developed for a
specific task with support from the Electoral Enrolment Centre, Wellington, New Zealand

=head1 MAILING LIST

   http://groups.google.com/group/PDF-Reuse

=head1 AUTHOR

Lars Lundberg larslund@cpan.org

=head1 COPYRIGHT 

Copyright (C) 2003 - 2004 Lars Lundberg, Solidez HB.
Copyright (C) 2005 Karin Lundberg.
Copyright (C) 2006 - Lars Lundberg, Solidez HB.
This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

=head1 DISCLAIMER

You get this module free as it is, but nothing is guaranteed to work, whatever 
implicitly or explicitly stated in this document, and everything you do, 
you do at your own risk - I will not take responsibility 
for any damage, loss of money and/or health that may arise from the use of this module.

=cut

sub prSinglePage
{ my $infil      = shift;
  my $pageNumber = shift;
      
  if (! defined $pageNumber)
  {   $behandlad{$infil}->{pageNumber} = 0
        unless (defined $behandlad{$infil}->{pageNumber});
      $pageNumber = $behandlad{$infil}->{pageNumber} + 1;
  }    
    
  my ($sida, $Names, $AARoot, $AcroForm) = analysera($infil, $pageNumber, $pageNumber, 1);
  if (($Names) || ($AARoot) || ($AcroForm))
  { $NamesSaved     = $Names;
    $AARootSaved    = $AARoot;
    $AcroFormSaved  = $AcroForm;
    $interActive    = 1;
  }
  if (defined $sida)
  {  $behandlad{$infil}->{pageNumber} = $pageNumber;
  }
  if ($runfil)
  {   $infil = prep($infil);
      $log .= "prSinglePage~$infil~$pageNumber\n";
  }
  if (! $pos)
  {  errLog("No output file, you have to call prFile first");
  }
  return $sida;

}



sub prLink
{ my %link;
  my $param = shift;
  if (ref($param) eq 'HASH')
  {  $link{page}   = $param->{'page'} || -1;
     $link{x}      = $param->{'x'}    || 100;
     $link{y}      = $param->{'y'}    || 100;
     $link{width}  = $param->{width}  || 75;
     $link{height} = $param->{height} || 15;
     $link{v}      = $param->{URI};
     $link{s}      = $param->{s} || "URI";
  }
  else
  {  $link{page}   = $param || -1;
     $link{x}      = shift  || 100;
     $link{y}      = shift  || 100;
     $link{width}  = shift  || 75;
     $link{height} = shift  || 15;
     $link{v}      = shift;
     $link{s}      = shift  || "URI";
  }

  if (! $pos)
  {  errLog("No output file, you have to call prFile first");
  }

  if ($runfil)
  {  $log .= "Link~$link{page}~$link{x}~$link{y}~$link{width}~" 
          . "$link{height}~$link{v}~$link{s}\n";
  }
  
  if ($link{v})
  {  push @{$links{$link{page}}}, \%link;
  }
  1;
}

sub mergeLinks
{   my $tSida = $sida + 1;
    my $rad;
    my ($linkObject, $linkObjectNo);
    for my $link (@{$links{'-1'}}, @{$links{$tSida}} )
    {   my $x2 = $link->{x} + $link->{width};
        my $y2 = $link->{y} + $link->{height};
        if (exists $links{$link->{v}})
        {   $linkObjectNo = $links{$link->{v}};
        }
        else
        {   $objNr++;
            $objekt[$objNr] = $pos;
            my $v_n;
            my $v_v = '('.$link->{v}.')';
            if    ($link->{s} eq 'GoTo')       
            {   $v_n = "D";
            }
            elsif ($link->{s} eq 'GoToA')      
            {   $link->{s} = 'GoTo';
                $v_n       = 'D';
                $v_v       = $link->{v};
            }
            elsif ($link->{s} eq 'Launch')     {$v_n = 'F';}
            elsif ($link->{s} eq 'SubmitForm') {$v_n = 'F';}
            elsif ($link->{s} eq 'Named')      
            {   $v_n = 'N';
                $v_v = $link->{v};
            }
            elsif ($link->{s} eq 'JavaScript') {$v_n = "JS";}
            else                               
            {   $v_n = $link->{s};
            }
            $rad = "$objNr 0 obj<</S/$link->{s}/$v_n$v_v>>endobj\n";
            $linkObjectNo = $objNr;
            $links{$link->{v}} = $objNr;
            $pos += syswrite UTFIL, $rad;
        }
        $rad = "/Subtype/Link/Rect[$link->{x} $link->{y} "
             . "$x2 $y2]/A $linkObjectNo 0 R/Border[0 0 0]";
        if (exists $links{$rad})
        {   push @annots, $links{$rad};
        }
        else
        {   $objNr++;
            $objekt[$objNr] = $pos;
            $links{$rad} = $objNr;
            $rad = "$objNr 0 obj<<$rad>>endobj\n";
            $pos += syswrite UTFIL, $rad;
            push @annots, $objNr;
        }
    }
    @{$links{'-1'}}   = ();
    @{$links{$tSida}} = ();
    $objNr++;
    $objekt[$objNr] = $pos;
    $rad = "$objNr 0 obj[\n";
    for (@annots)
    {  $rad .= "$_ 0 R\n";
    }
    $rad .= "]endobj\n";
    $pos += syswrite UTFIL, $rad;
    @annots = ();
    return $objNr;
}


sub prBookmark
{   my $param = shift;
    if (! ref($param))
    {   $param = eval ($param);
    }
    if (! ref($param))
    {   return undef;
    }
    if (! $pos)
    {  errLog("No output file, you have to call prFile first");
    }
    if (ref($param) eq 'HASH')
    {   push @bookmarks, $param;
    }
    else
    {   push @bookmarks, (@$param);       
    }
    if ($runfil)
    {   local $Data::Dumper::Indent = 0;
        $param = Dumper($param);
        $param =~ s/^\$VAR1 = //;
        $param = prep($param);
        $log .= "Bookmark~$param\n";
    }
    return 1;
}

sub ordnaBookmarks
{   my ($first, $last, $me, $entry, $rad);
    $totalCount = 0;
    if (defined $objekt[$objNr])
    {  $objNr++;
    }
    $me = $objNr;
        
    my $number = $#bookmarks;
    for (my $i = 0; $i <= $number ; $i++)
    {   my %hash = %{$bookmarks[$i]};
        $objNr++;
        $hash{'this'} = $objNr;
        if ($i == 0)
        {   $first = $objNr;           
        }
        if ($i == $number)
        {   $last = $objNr;
        } 
        if ($i < $number)
        {  $hash{'next'} = $objNr + 1;
        }
        if ($i > 0)
        {  $hash{'previous'} = $objNr - 1;
        }
        $bookmarks[$i] = \%hash;
    } 
    
    for $entry (@bookmarks)
    {  my %hash = %{$entry};
       descend ($me, %hash);
    }

    $objekt[$me] = $pos;

    $rad = "$me 0 obj<<";
    $rad .= "/Type/Outlines";
    $rad .= "/Count $totalCount";
    if (defined $first)
    {  $rad .= "/First $first 0 R";
    }
    if (defined $last)
    {  $rad .= "/Last $last 0 R";
    }
    $rad .= ">>endobj\n";
    $pos += syswrite UTFIL, $rad;

    return $me;

}

sub descend
{   my ($parent, %entry) = @_;
    my ($first, $last, $count, $me, $rad, $jsObj);
    if (! exists $entry{'close'})
    {  $totalCount++; }
    $count = $totalCount;
    $me = $entry{'this'};
    if (exists $entry{'kids'})
    {   if (ref($entry{'kids'}) eq 'ARRAY')
        {   my @array = @{$entry{'kids'}};
            my $number = $#array;
            for (my $i = 0; $i <= $number ; $i++)
            {   $objNr++;
                $array[$i]->{'this'} = $objNr;
                if ($i == 0)
                {   $first = $objNr;           
                }
                if ($i == $number)
                {   $last = $objNr;
                } 

                if ($i < $number)
                {  $array[$i]->{'next'} = $objNr + 1;
                }
                if ($i > 0)
                {  $array[$i]->{'previous'} = $objNr - 1;
                }
                if (exists $entry{'close'})
                {  $array[$i]->{'close'} = 1;
                }
            } 

            for my $element (@array)
            {   descend($me, %{$element})
            }
        }
        else                                          # a hash
        {   my %hash = %{$entry{'kids'}};
            $objNr++;
            $hash{'this'} = $objNr;
            $first        = $objNr;           
            $last         = $objNr;
            descend($me, %hash)
        }
     }     

     if (exists $entry{'act'})
     {   my $code = $entry{'act'};
         if ($code =~ m/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*$/os)
         {  # $code = "this.pageNum = $1; this.scroll($2, $3);";
              $code = "this.pageNum = $1;".($3?" this.scroll($2, $3);":"");
         }
         $jsObj = skrivJS($code);         
     } 

     $objekt[$me] = $pos;
     $rad = "$me 0 obj<<";
     if (exists $entry{'text'})
     {   $rad .= "/Title ($entry{'text'})";
     }
     $rad .= "/Parent $parent 0 R";
     if (defined $jsObj)
     {  $rad .= "/A $jsObj 0 R";
     }
     if (exists $entry{'previous'})
     {  $rad .= "/Prev $entry{'previous'} 0 R";
     }
     if (exists $entry{'next'})
     {  $rad .= "/Next $entry{'next'} 0 R";
     }
     if (defined $first)
     {  $rad .= "/First $first 0 R";
     }
     if (defined $last)
     {  $rad .= "/Last $last 0 R";
     }
     if ($count != $totalCount)
     {   $count = $totalCount - $count;
         $rad .= "/Count $count";
     }
     if (exists $entry{'color'})
     {   $rad .= "/C [$entry{'color'}]";
     }
     if (exists $entry{'style'})
     {   $rad .= "/F $entry{'style'}";
     }

     $rad .= ">>endobj\n";
     $pos += syswrite UTFIL, $rad;
}  

sub prInitVars
{   my $exit = shift;
    $genLowerX    = 0;
    $genLowerY    = 0;
    $genUpperX    = 595,
    $genUpperY    = 842;
    $fontSize     = 12;
    ($utfil, $slutNod, $formCont, $imSeq, 
    $page, $sidObjNr, $interActive, $NamesSaved, $AARootSaved, $AAPageSaved,
    $root, $AcroFormSaved, $id, $ldir, $checkId, $formNr, $imageNr, 
    $filnamn, $interAktivSida, $taInterAkt, $type, $runfil, $checkCs,
    $confuseObj, $compress,$pos, $fontNr, $objNr,
    $defGState, $gSNr, $pattern, $shading, $colorSpace) = '';

    (@kids, @counts, @formBox, @objekt, @parents, @aktuellFont, @skapa,
     @jsfiler, @inits, @bookmarks, @annots) = ();

    ( %resurser,  %objRef, %nyaFunk,%oldObject, %unZipped, 
      %sidFont, %sidXObject, %sidExtGState, %font, %fields, %script,
      %initScript, %sidPattern, %sidShading, %sidColorSpace, %knownToFile,
      %processed, %dummy) = ();

     $stream = '';
     $idTyp  = '';
     $ddir   = '';
     $log    = '';

     if ($exit)
     {  return 1;
     }
   
     ( %form, %image, %fontSource, %intAct) = ();

     return 1;
}

####################
# Behandla en bild
####################

sub prImage
{ my $param = shift;
  my ($infil, $sidnr, $bildnr, $effect, $adjust, $x, $y, $size, $xsize,
      $ysize, $rotate);

  if (ref($param) eq 'HASH')
  {  $infil  = $param->{'file'};
     $sidnr  = $param->{'page'} || 1;
     $bildnr = $param->{'imageNo'} || 1;
     $effect = $param->{'effect'} || 'print';
     $adjust = $param->{'adjust'} || '';
     $x      = $param->{'x'} || 0;
     $y      = $param->{'y'} || 0;
     $rotate = $param->{'rotate'} || 0;
     $size   = $param->{'size'} || 1;
     $xsize  = $param->{'xsize'} || 1;
     $ysize  = $param->{'ysize'} || 1;
  }
  else
  {  $infil  = $param;
     $sidnr  = shift || 1;
     $bildnr = shift || 1;
     $effect = shift || 'print';
     $adjust = shift || '';
     $x      = shift || 0;
     $y      = shift || 0;
     $rotate = shift || 0;
     $size   = shift || 1;
     $xsize  = shift || 1;
     $ysize  = shift || 1;
  }

  my ($refNr, $inamn, $bildIndex, $xc, $yc, $xs, $ys);
  $type = 'image';
  
  $bildIndex = $bildnr - 1;
  my $fSource = $infil . '_' . $sidnr;
  my $iSource = $fSource . '_' . $bildnr;
  if (! exists $image{$iSource})
  {  $imageNr++;
     $inamn = 'Ig' . $imageNr;
     $knownToFile{'Ig:' . $iSource} = $inamn;
     $image{$iSource}[imXPOS]   = 0;
     $image{$iSource}[imYPOS]   = 0;
     $image{$iSource}[imXSCALE] = 1;
     $image{$iSource}[imYSCALE] = 1;
     if (! exists $form{$fSource} )
     {  $refNr = getPage($infil, $sidnr, '');
        if ($refNr)
        {  $formNr++;
           my $namn = 'Fm' . $formNr;
           $knownToFile{$fSource} = $namn;
        }
        elsif ((defined $refNr) && ($refNr eq '0'))
        {  errLog("File: $infil  Page: $sidnr can't be found");
        }          
     }
     my $in = $form{$fSource}[fIMAGES][$bildIndex];
     $image{$iSource}[imWIDTH]  = $form{$fSource}->[fOBJ]->{$in}->[oWIDTH];
     $image{$iSource}[imHEIGHT] = $form{$fSource}->[fOBJ]->{$in}->[oHEIGHT];
     $image{$iSource}[imIMAGENO] = $form{$fSource}[fIMAGES][$bildIndex];
  }
  if (exists $knownToFile{'Ig:' . $iSource})
  {   $inamn = $knownToFile{'Ig:' . $iSource};
  }
  else
  {   $imageNr++;
      $inamn = 'Ig' . $imageNr;
      $knownToFile{'Ig:' . $iSource} = $inamn;
  }
  if (! exists $objRef{$inamn})         
  {  $refNr = getImage($infil,  $sidnr, 
                       $bildnr, $image{$iSource}[imIMAGENO]);
     $objRef{$inamn} = $refNr;
  }
  else
  {   $refNr = $objRef{$inamn};
  }
     
  my @iData = @{$image{$iSource}};

  if (($effect eq 'print') && ($refNr))
  {  if (! defined  $defGState)
     { prDefaultGrState();}
     $stream .= "\n/Gs0 gs\n";
     $stream .= "q\n";
     
     if ($adjust)
     {  $stream .= fillTheForm(0, 0, $iData[imWIDTH], $iData[imHEIGHT],$adjust);        
     }
     else
     {   my $tX     = ($x + $iData[imXPOS]);
         my $tY     = ($y + $iData[imYPOS]);
         $stream .= calcMatrix($tX, $tY, $rotate, $size, 
                               $xsize, $ysize, $iData[imWIDTH], $iData[imHEIGHT]);
     }
     $stream .= "$iData[imWIDTH] 0 0 $iData[imHEIGHT] 0 0 cm\n";
     $stream .= "/$inamn Do\n";
     $sidXObject{$inamn} = $refNr;
     $stream .= "Q\n";
     $sidExtGState{'Gs0'} = $defGState;
  }
  if ($runfil)
  {  $infil = prep($infil);
     $log .= "Image~$infil~$sidnr~$bildnr~$effect~$adjust";
     $log .= "$x~$y~$size~$xsize~$ysize~$rotate\n";
  }
  if (! $pos)
  {  errLog("No output file, you have to call prFile first");
  }

  if (wantarray)
  {   return ($inamn, $iData[imWIDTH], $iData[imHEIGHT]);
  }
  else
  {   return $inamn;
  }
}



sub prMbox
{  my $lx = shift || 0;
   my $ly = shift || 0;
   my $ux = shift || 595;
   my $uy = shift || 842;
   
   if ((defined $lx) && ($lx =~ m'^[\d\-\.]+$'o))
   { $genLowerX = $lx; }
   if ((defined $ly) && ($ly =~ m'^[\d\-\.]+$'o))
   { $genLowerY = $ly; } 
   if ((defined $ux) && ($ux =~ m'^[\d\-\.]+$'o))
   { $genUpperX = $ux; } 
   if ((defined $uy) && ($uy =~ m'^[\d\-\.]+$'o))
   { $genUpperY = $uy; } 
   if ($runfil)
   {  $log .= "Mbox~$lx~$ly~$ux~$uy\n";
   }
   if (! $pos)
   {  errLog("No output file, you have to call prFile first");
   }
   1;
}

sub prField
{  my ($fieldName, $fieldValue) = @_;
   if (($interAktivSida) || ($interActive))
   {  errLog("Too late, has already tried to INITIATE FIELDS within an interactive page");
   }
   elsif (! $pos)
   {  errLog("Too early INITIATE FIELDS, create a file first");
   }
   $fields{$fieldName} = $fieldValue;
   if ($fieldValue =~ m'^\s*js\s*\:(.*)'oi)
   {  my $code = $1;
      my @fall = ($code =~ m'([\w\d\_\$]+)\s*\(.*?\)'gs);
      for (@fall)
      {  if (! exists $initScript{$_})
         { $initScript{$_} = 0; 
         }
      }
   }
   if ($runfil)
   {   $fieldName  = prep($fieldName);
       $fieldValue = prep($fieldValue);
       $log .= "Field~$fieldName~$fieldValue\n";
   } 
   1;
}
############################################################
sub prBar
{ my ($xPos, $yPos, $TxT) = @_; 
 
  $TxT   =~ tr/G/2/;
    
  my @fontSpar = @aktuellFont;
         
  findBarFont();
  
  my $Font = $aktuellFont[foINTNAMN];                # Namn i strömmen
  
  if (($xPos) && ($yPos))
  {  $stream .= "\nBT /$Font $fontSize Tf ";
     $stream .= "$xPos $yPos Td \($TxT\) Tj ET\n";
  }
  if ($runfil)
  {  $log .= "Bar~$xPos~$yPos~$TxT\n";
  }
  if (! $pos)
  {  errLog("No output file, you have to call prFile first");
  }
  @aktuellFont = @fontSpar;
  return $Font;
  
}


sub prExtract
{  my $name = shift;
   my $form = shift;
   my $page = shift || 1;
   if ($name =~ m'^/(\w+)'o)
   {  $name = $1;
   }
   my $fullName = "$name~$form~$page";
   if (exists $knownToFile{$fullName})
   {   return $knownToFile{$fullName};
   }
   else
   {   if ($runfil)
       {  $log = "Extract~$fullName\n";
       }
       if (! $pos)
       {  errLog("No output file, you have to call prFile first");
       }
   
       if (! exists $form{$form . '_' . $page})
       {  prForm($form, $page, undef, 'load', 1);
       }
       $name = extractName($form, $page, $name);
       if ($name)
       {  $knownToFile{$fullName} = $name;
       }
       return $name;
   }
}


########## Extrahera ett dokument ####################       
sub prDoc
{ my ($infil, $first, $last); 
  my $param = shift;
  if (ref($param) eq 'HASH')
  {  $infil = $param->{'file'};
     $first = $param->{'first'} || 1;
     $last  = $param->{'last'} || '';
  }
  else
  {  $infil = $param;
     $first = shift || 1;
     $last  = shift || '';     
  }
  
  
  my ($sidor, $Names, $AARoot, $AcroForm) = analysera($infil, $first, $last);
  if (($Names) || ($AARoot) || ($AcroForm))
  { $NamesSaved     = $Names;
    $AARootSaved    = $AARoot;
    $AcroFormSaved  = $AcroForm;
    $interActive    = 1;
  }
  if ($runfil)
  {   $infil = prep($infil);
      $log .= "Doc~$infil~$first~$last\n";
  }
  if (! $pos)
  {  errLog("No output file, you have to call prFile first");
  }
  return $sidor;
}

############# Ett interaktivt + grafiskt "formulär" ##########

sub prDocForm
{my ($sidnr, $adjust, $effect, $tolerant, $infil, $x, $y, $size, $xsize,
      $ysize, $rotate);
  my $param = shift;
  if (ref($param) eq 'HASH')
  {  $infil    = $param->{'file'};
     $sidnr    = $param->{'page'} || 1;
     $adjust   = $param->{'adjust'} || '';
     $effect   = $param->{'effect'} || 'print';
     $tolerant = $param->{'tolerant'} || '';
     $x        = $param->{'x'} || 0;
     $y        = $param->{'y'} || 0;
     $rotate   = $param->{'rotate'} || 0;
     $size     = $param->{'size'} || 1;
     $xsize    = $param->{'xsize'} || 1;
     $ysize    = $param->{'ysize'} || 1;
  }
  else
  {  $infil    = $param;
     $sidnr    = shift || 1;
     $adjust   = shift || '';
     $effect   = shift || 'print';
     $tolerant = shift || '';
     $x        = shift || 0;
     $y        = shift || 0;
     $rotate   = shift || 0;
     $size     = shift || 1;
     $xsize    = shift || 1;
     $ysize    = shift || 1;
  }
  my $namn;
  my $refNr;
  $type = 'docform';
  my $fSource = $infil . '_' . $sidnr; 
  my $action;
  if (! exists $form{$fSource})
  {  $formNr++;
     $namn = 'Fm' . $formNr;
     $knownToFile{$fSource} = $namn;
     if ($effect eq 'load')
     {  $action = 'load'
     }
     else
     {  $action = 'print'
     }     
     $refNr         = getPage($infil, $sidnr, $action);
     if ($refNr)
     {  $objRef{$namn} = $refNr; 
     }
     else
     {  if ($tolerant)
        {  if ((defined $refNr) && ($refNr eq '0'))   # Sidnumret existerar inte, men ok
           {   $namn = '0';
           }
           else
           {   undef $namn;   # Sidan kan inte användas som form
           }
        }
        elsif (! defined $refNr)
        {  my $mess = "$fSource can't be used as a form. See the documentation\n"
                    . "under prForm how to concatenate streams\n";
           errLog($mess);
        }
        else
        {  errLog("File : $infil  Page: $sidnr  doesn't exist");
        }
     }
  }
  else
  {  if (exists $knownToFile{$fSource})
     {   $namn = $knownToFile{$fSource};
     }
     else
     {  $formNr++;
        $namn = 'Fm' . $formNr;
        $knownToFile{$fSource} = $namn; 
     }
     if (exists $objRef{$namn})
     {  $refNr = $objRef{$namn};
     }
     else
     {  if (! $form{$fSource}[fVALID])
        {  my $mess = "$fSource can't be used as a form. See the documentation\n"
                    . "under prForm how to concatenate streams\n";
           if ($tolerant)
           {  cluck $mess;
              undef $namn;
           }
           else
           {  errLog($mess);
           }
        }
        elsif ($effect ne 'load')
        {  $refNr         =  byggForm($infil, $sidnr);
           $objRef{$namn} = $refNr;
        }
     }  
  }
  my @BBox = @{$form{$fSource}[fBBOX]} if ($refNr);
  if (($effect eq 'print') && ($form{$fSource}[fVALID]) && ($refNr))
  {   if ((! defined $interActive)
      && ($sidnr == 1)
      &&  (defined %{$intAct{$fSource}[0]}) )
      {  $interActive = $infil . ' ' . $sidnr;
         $interAktivSida = 1;
      }
      if (! defined $defGState)
      { prDefaultGrState();
      }
      if ($adjust)
      {   $stream .= "q\n";
          $stream .= fillTheForm(@BBox, $adjust);
          $stream .= "\n/Gs0 gs\n";
          $stream .= "/$namn Do\n";
          $stream .= "Q\n";
      }
      elsif (($x) || ($y) || ($rotate) || ($size != 1) 
                  || ($xsize != 1)     || ($ysize != 1))
      {   $stream .= "q\n";
          $stream .= calcMatrix($x, $y, $rotate, $size, 
                               $xsize, $ysize, $BBox[2], $BBox[3]);
          $stream .= "\n/Gs0 gs\n";
          $stream .= "/$namn Do\n";
          $stream .= "Q\n";
      }
      else
      {   $stream .= "\n/Gs0 gs\n";   
          $stream .= "/$namn Do\n";          
      }
      $sidXObject{$namn} = $refNr;
      $sidExtGState{'Gs0'} = $defGState;
  }
  if ($runfil)
  {   $infil = prep($infil); 
      $log .= "Form~$infil~$sidnr~$adjust~$effect~$tolerant";
      $log .= "~$x~$y~$rotate~$size~$xsize~$ysize\n";
  }
  if (! $pos)
  {  errLog("No output file, you have to call prFile first");
  }
  if (($effect ne 'print') && ($effect ne 'add'))
  {  undef $namn;
  }
  if (wantarray)
  {  my $images = 0;
     if (exists $form{$fSource}[fIMAGES])
     {  $images = scalar(@{$form{$fSource}[fIMAGES]});
     } 
     return ($namn, $BBox[0], $BBox[1], $BBox[2], 
             $BBox[3], $images);
  }
  else
  {  return $namn;
  }
}

sub calcMatrix
{  my ($x, $y, $rotate, $size, $xsize, $ysize, $upperX, $upperY) = @_;
   my ($str, $xSize, $ySize);
   $size  = 1 if ($size  == 0);
   $xsize = 1 if ($xsize == 0);
   $ysize = 1 if ($ysize == 0);
   $xSize = $xsize * $size;
   $ySize = $ysize * $size;   
   $str = "$xSize 0 0 $ySize $x $y cm\n";
   if ($rotate)
   {   if ($rotate =~ m'q(\d)'oi)
       {  my $tal = $1;
          if ($tal == 1)
          {  $upperY = $upperX;
             $upperX = 0;
             $rotate = 270;
          }
          elsif ($tal == 2)
          {  $rotate = 180;
          }
          else
          {  $rotate = 90;
             $upperX = $upperY;
             $upperY = 0;
          }
       }
       else
       {   $upperX = 0;
           $upperY = 0;
       }  
       my $radian = sprintf("%.6f", $rotate / 57.2957795);    # approx. 
       my $Cos    = sprintf("%.6f", cos($radian));
       my $Sin    = sprintf("%.6f", sin($radian));
       my $negSin = $Sin * -1;
       $str .= "$Cos $Sin $negSin $Cos $upperX $upperY cm\n";
   }
   return $str;
}

sub fillTheForm
{  my $left   = shift || 0;
   my $bottom = shift || 0;
   my $right  = shift || 0;
   my $top    = shift || 0; 
   my $how    = shift || 1;
   my $image  = shift;
   my $str;
   my $scaleX = 1;
   my $scaleY = 1; 
   
   my $xDim = $genUpperX - $genLowerX;
   my $yDim = $genUpperY - $genLowerY;
   my $xNy  = $right - $left;
   my $yNy  = $top - $bottom;
   $scaleX  = $xDim / $xNy;
   $scaleY  = $yDim / $yNy;
   if ($how == 1)
   {  if ($scaleX < $scaleY)
      {  $scaleY = $scaleX;
      }
      else
      {  $scaleX = $scaleY;
      }
   }
   $str = "$scaleX 0 0 $scaleY $left $bottom cm\n";
   return $str;
}

sub prJpeg
{  my ($iFile, $iWidth, $iHeight) = @_;
   my ($iLangd, $namnet, $utrad);
   if (! $pos)                    # If no output is active, it is no use to continue
   {   return undef;
   }
   my $checkidOld = $checkId;
   ($iFile, $checkId) = findGet($iFile, $checkidOld);
   if ($iFile)
   {  $iLangd = (stat($iFile))[7];
      $imageNr++;
      $namnet = 'Ig' . $imageNr;
      $objNr++;
      $objekt[$objNr] = $pos;
      open (BILDFIL, "<$iFile") || errLog("Couldn't open $iFile, $!, aborts");
      binmode BILDFIL;
      my $iStream;
      sysread BILDFIL, $iStream, $iLangd;
      $utrad = "$objNr 0 obj\n<</Type/XObject/Subtype/Image/Name/$namnet" .
                "/Width $iWidth /Height $iHeight /BitsPerComponent 8 /Filter/DCTDecode/ColorSpace/DeviceRGB"
                . "/Length $iLangd >>stream\n$iStream\nendstream\nendobj\n";
      close BILDFIL;
      $pos += syswrite UTFIL, $utrad;
      if ($runfil)
      {  $log .= "Cid~$checkId\n";
         $log .= "Jpeg~$iFile~$iWidth~$iHeight\n";
      }
      $objRef{$namnet} = $objNr;
   }
   if (! $pos)
   {  errLog("No output file, you have to call prFile first");
   }
   undef $checkId;
   return $namnet;
}

sub checkContentStream
{  for (@_)
   {  if (my $value = $objRef{$_})
      {   my $typ = substr($_, 0, 2);
          if ($typ eq 'Ft')
          {  $sidFont{$_} = $value;
          }
          elsif ($typ eq 'Gs')
          {  $sidExtGState{$_} = $value;
          }
          elsif ($typ eq 'Pt')
          {  $sidPattern{$_} = $value;
          }
          elsif ($typ eq 'Sh')
          {  $sidShading{$_} = $value;
          }
          elsif ($typ eq 'Cs')
          {  $sidColorSpace{$_} = $value;
          }
          else
          {  $sidXObject{$_} = $value;
          }
      }
      elsif (($_ eq 'Gs0') && (! defined $defGState))
      {  my ($dummy, $oNr) = prDefaultGrState();
         $sidExtGState{'Gs0'} = $oNr;
      }
   }    
}

sub prGraphState
{  my $string = shift;
   $gSNr++;
   my $name = 'Gs' . $gSNr ;
   $objNr++;
   $objekt[$objNr] = $pos;
   my $utrad = "$objNr 0 obj\n" . $string  . "\nendobj\n";
   $pos += syswrite UTFIL, $utrad;
   $objRef{$name} = $objNr;
   if ($runfil)
   {  $log .= "GraphStat~$string\n";
   }
   if (! $pos)
   {  errLog("No output file, you have to call prFile first");
   }
   return $name;
}

##############################################################
# Streckkods fonten lokaliseras och objekten skrivs ev. ut
##############################################################

sub findBarFont()
{  my $Font = 'Bar';
   
   if (exists $font{$Font})              #  Objekt är redan definierat
   {  $aktuellFont[foEXTNAMN]   = $Font;
      $aktuellFont[foREFOBJ]    = $font{$Font}[foREFOBJ];
      $aktuellFont[foINTNAMN]   = $font{$Font}[foINTNAMN];
   }
   else
   {  $objNr++;
      $objekt[$objNr]  = $pos;
      my $encodObj     = $objNr;
      my $fontObjekt   = "$objNr 0 obj\n<< /Type /Encoding\n" .
                         '/Differences [48 /tomt /streck /lstreck]' . "\n>>\nendobj\n";
      $pos += syswrite UTFIL, $fontObjekt;
      my $charProcsObj = createCharProcs();
      $objNr++;
      $objekt[$objNr]  = $pos;
      $fontNr++;
      my $fontAbbr     = 'Ft' . $fontNr; 
      $fontObjekt      = "$objNr 0 obj\n<</Type/Font/Subtype/Type3\n" .
                         '/FontBBox [0 -250 75 2000]' . "\n" .
                         '/FontMatrix [0.001 0 0 0.001 0 0]' . "\n" .
                         "\/CharProcs $charProcsObj 0 R\n" .
                         "\/Encoding $encodObj 0 R\n" .
                         '/FirstChar 48' . "\n" .
                         '/LastChar 50' . "\n" .
                         '/Widths [75 75 75]' . "\n>>\nendobj\n";

      $font{$Font}[foINTNAMN]  = $fontAbbr; 
      $font{$Font}[foREFOBJ]   = $objNr;
      $objRef{$fontAbbr}       = $objNr;
      $objekt[$objNr]          = $pos;
      $aktuellFont[foEXTNAMN]  = $Font;
      $aktuellFont[foREFOBJ]   = $objNr;
      $aktuellFont[foINTNAMN]  = $fontAbbr;
      $pos += syswrite UTFIL, $fontObjekt;
   }
   if (! $pos)
   {  errLog("No output file, you have to call prFile first");
   }
      
   $sidFont{$aktuellFont[foINTNAMN]} = $aktuellFont[foREFOBJ];
}

sub createCharProcs()
{   #################################
    # Fonten (objektet) för 0 skapas
    #################################
    
    $objNr++;
    $objekt[$objNr]  = $pos;
    my $tomtObj = $objNr;
    my $str = "\n75 0 d0\n6 0 69 2000 re\n1.0 g\nf\n";
    my $strLength = length($str);
    my $obj = "$objNr 0 obj\n<< /Length $strLength >>\nstream" .
           $str . "\nendstream\nendobj\n";
    $pos += syswrite UTFIL, $obj;

    #################################
    # Fonten (objektet) för 1 skapas
    #################################

    $objNr++;
    $objekt[$objNr]  = $pos;
    my $streckObj = $objNr;
    $str = "\n75 0 d0\n4 0 71 2000 re\n0.0 g\nf\n";
    $strLength = length($str);
    $obj = "$objNr 0 obj\n<< /Length $strLength >>\nstream" .
           $str . "\nendstream\nendobj\n";
    $pos += syswrite UTFIL, $obj;

    ###################################################
    # Fonten (objektet) för 2, ett långt streck skapas
    ###################################################

    $objNr++;
    $objekt[$objNr]  = $pos;
    my $lStreckObj = $objNr;
    $str = "\n75 0 d0\n4 -250 71 2250 re\n0.0 g\nf\n";
    $strLength = length($str);
    $obj = "$objNr 0 obj\n<< /Length $strLength >>\nstream" .
           $str . "\nendstream\nendobj\n";
    $pos += syswrite UTFIL, $obj;
   
    #####################################################
    # Objektet för "CharProcs" skapas
    #####################################################

    $objNr++;
    $objekt[$objNr]  = $pos;
    my $charProcsObj = $objNr;
    $obj = "$objNr 0 obj\n<</tomt $tomtObj 0 R\n/streck $streckObj 0 R\n" .
           "/lstreck $lStreckObj 0 R>>\nendobj\n";
    $pos += syswrite UTFIL, $obj;
    return $charProcsObj;
}



sub prCid
{   $checkId = shift;
    if ($runfil)
    {  $log .= "Cid~$checkId\n";
    }
    1;    
}
    
sub prIdType
{   $idTyp = shift;
    if ($runfil)
    {  $log .= "IdType~rep\n";
    }
    1;
}
         
    
sub prId
{   $id = shift;
    if ($runfil)
    {  $log .= "Id~$id\n";
    }
    if (! $pos)
    {  errLog("No output file, you have to call prFile first");
    }
    1;
}

sub prJs
{   my $filNamnIn = shift;
    my $filNamn;
    if ($filNamnIn !~ m'\{'os)
    {  my $checkIdOld = $checkId;
       ($filNamn, $checkId) = findGet($filNamnIn, $checkIdOld);
       if (($runfil) && ($checkId) && ($checkId ne $checkIdOld))
       {  $log .= "Cid~$checkId\n";
       }
       $checkId = '';
    }
    else
    {  $filNamn = $filNamnIn;
    }
    if ($runfil)
    {  my $filnamn = prep($filNamn);
       $log .= "Js~$filnamn\n";
    }
    if (($interAktivSida) || ($interActive))
    {  errLog("Too late, has already tried to merge JAVA SCRIPTS within an interactive page");
    }
    elsif (! $pos)
    {  errLog("Too early for JAVA SCRIPTS, create a file first"); 
    }
    push @jsfiler, $filNamn;
    1;
}

sub prInit
{   my $initText  = shift;
    my $duplicate = shift || '';
    my @fall = ($initText =~ m'([\w\d\_\$]+)\s*\(.*?\)'gs);
    for (@fall)
    {  if (! exists $initScript{$_})
       { $initScript{$_} = 0; 
       }
    }
    if ($duplicate)
    {  $duplicateInits = 1;
    }
    push @inits, $initText;
    if ($runfil)
    {   $initText = prep($initText);
        $log .= "Init~$initText~$duplicate\n";
    }
    if (($interAktivSida) || ($interActive))
    {  errLog("Too late, has already tried to create INITIAL JAVA SCRIPTS within an interactive page");
    }
    elsif (! $pos)
    {  errLog("Too early for INITIAL JAVA SCRIPTS, create a file first");
    }
    1;
    
}

sub prVers
{   my $vers = shift;            
    ############################################################
    # Om programmet körs om så kontrolleras VERSION
    ############################################################
    if ($vers ne $VERSION)
    {  warn  "$vers \<\> $VERSION might give different results, if comparing two runs \n";
       return undef;
    }
    else
    {  return 1;
    }
}

sub prDocDir
{  $ddir = findDir(shift);
   1;
}

sub prLogDir
{  $ldir = findDir(shift);
   1;
}

sub prLog
{  my $mess = shift;
   if ($runfil)
   {  $mess  = prep($mess);
      $log .= "Log~$mess\n";
      return 1;
   }
   else
   {  errLog("You have to give a directory for the logfiles first : prLogDir <dir> , aborts");
   }
   
}

sub prGetLogBuffer
{  
   return $log;
}

sub findDir
{ my $dir = shift;
  if ($dir eq '.')
  { return undef; }
  if (! -e $dir)
   {  mkdir $dir || errLog("Couldn't create directory $dir, $!");
   }

  if ((-e $dir) && (-d $dir))
  {  if (substr($dir, length($dir), 1) eq '/')
     {  return $dir; }
     else
     {  return ($dir . '/');
     }
  }
  else
  { errLog("Error finding/creating directory $dir, $!");
  }
}

sub prTouchUp
{ $touchUp = shift;
  if ($runfil)
  {  $log .= "TouchUp~$touchUp\n";
  }
  if (! $pos)
  {  errLog("No output file, you have to call prFile first");
  }
  1;
}

sub prCompress
{ $compress = shift;
  if ($runfil)
  {  $log .= "Compress~$compress\n";
  }
  if (! $pos)
  {  errLog("No output file, you have to call prFile first");
  }
  1;

}

sub prep
{  my $indata = shift;
   $indata =~ s/[\n\r]+/ /sgo;
   $indata =~ s/~/<tilde>/sgo;
   return $indata;
} 


sub xRefs
{  my ($bytes, $infil) = @_;
   my ($j, $nr, $xref, $i, $antal, $inrad, $Root, $tempRoot, $referens);
   my $buf = '';
   %embedded =();

   my $res = sysseek INFIL, -50, 2;
   if ($res)
   {  sysread INFIL, $buf, 100;
      if ($buf =~ m'Encrypt'o)
      {  errLog("The file $infil is encrypted, cannot be used, aborts");
      }
      if ($buf =~ m'\bstartxref\s+(\d+)'o)
      {  $xref = $1;
         while ($xref)
         {  $res = sysseek INFIL, $xref, 0;
            $res = sysread INFIL, $buf, 200;
            if ($buf =~ m '^\d+\s\d+\sobj'os)
            {  ($xref, $tempRoot, $nr) = crossrefObj($nr, $xref);
            }
            else
            {  ($xref, $tempRoot, $nr) = xrefSection($nr, $xref, $infil);
            }
            if (($tempRoot) && (! $Root))
            {  $Root = $tempRoot;
            }
         }
      }
   }

   ($Root) || errLog("The Root object in $infil couldn't be found, aborting");

   ##############################################################
   # Objekten sorteras i fallande ordning (efter offset i filen)
   ##############################################################

   my @offset = sort { $oldObject{$b} <=> $oldObject{$a} } keys %oldObject;

   my $saved;

   for (@offset)
   {   $saved  = $oldObject{$_};
       $bytes -= $saved;
       
       if ($_ !~ m'^xref'o)
       {   if ($saved == 0)
           {   $oldObject{$_} = [ 0, 0, $embedded{$_}];
           }
           else
           {   $oldObject{$_} = [ $saved, $bytes];
           }
       }
       $bytes = $saved;
   } 
   %embedded = ();
   return $Root;
}

sub crossrefObj
{   my ($nr, $xref) = @_;
    my ($buf, %param, $len, $tempRoot);
    my $from = $xref;
    sysseek INFIL, $xref, 0;
    sysread INFIL, $buf, 400;
    my $str;
    if ($buf =~ m'^(.+>>\s*)stream'os)
    {  $str = $1;
       $from = length($str) + 7;
       if (substr($buf, $from, 1) eq "\n")
       {  $from++;
       }
       $from += $xref;
    }
    
    for (split('/',$str))
    {  if ($_ =~ m'^(\w+)(.*)'o)
       {  $param{$1} = $2 || ' ';
       }
    }
    if ((exists $param{'Root'}) && ($param{'Root'} =~ m'^\s*(\d+)'o))
    {  $tempRoot = $1;
    }
    my @keys = ($param{'W'} =~ m'(\d+)'og);
    my $keyLength = 0;
    for (@keys)
    {  $keyLength += $_;
    }
    my $recLength = $keyLength + 1;
    my $upTo = 1 + $keys[0] + $keys[1];
    if ((exists $param{'Length'}) && ($param{'Length'} =~ m'(\d+)'o))
    {  $len = $1;
       sysseek INFIL, $from, 0;
       sysread INFIL, $buf, $len;
       my $x = inflateInit()
               || die "Cannot create an inflation stream\n" ;
       my ($output, $status) = $x->inflate(\$buf) ;
       die "inflation failed\n"
                     unless $status == 1;
       
       my $i = 0;
       my @last = (0, 0, 0, 0, 0, 0, 0);
       my @word = ('0', '0', '0', '0', '0', '0', '0');
       my $recTyp;
       my @intervall = ($param{'Index'} =~ m'(\d+)\D'osg);
       my $m = 0;
       my $currObj = $intervall[$m];
       $m++;
       my $max     = $currObj + $intervall[$m];   
       
       for (unpack ("C*", $output))
       {  if (($_ != 0) && ($i > 0) && ($i < $upTo))
          {   my $tal = $_ + $last[$i] ;
              if ($tal > 255)
              {$tal -= 256;
              }
          
              $last[$i] = $tal;
              $word[$i] = sprintf("%x", $tal);
              if (length($word[$i]) == 1)
              {  $word[$i] = '0' . $word[$i];
              }
          }                    
          $i++;
          if ($i == $recLength)
          {  $i = 0;
             my $j = 0;
             my $offsObj;               # offset or object
             if ($keys[0] == 0)
             {  $recTyp = 1;
                $j = 1;
             }
             else
             {  $recTyp = $word[1];
                $j = 2;
             }
             my $k = 0;
             while ($k < $keys[1])
             {  $offsObj .= $word[$j];
                $k++;
                $j++;
             }
                       
             if ($recTyp == 1)
             {   if (! (exists $oldObject{$currObj}))
                 {  $oldObject{$currObj} = hex($offsObj); }
                 else
                 {  $nr++;
                    $oldObject{'xref' . "$nr"} = hex($offsObj);
                 }
             }
             elsif ($recTyp == 2)
             {   if (! (exists $oldObject{$currObj}))
                 {  $oldObject{$currObj} = 0; 
                 }
                 $embedded{$currObj} = hex($offsObj);
             }
             if ($currObj < $max)
             {  $currObj++;
             }
             else
             {  $m++;
                $currObj = $intervall[$m];
                $m++;
                $max     = $currObj + $intervall[$m];
             } 
          }
       }       
    }
    return ($param{'Prev'}, $tempRoot, $nr);
}
 
sub xrefSection
{   my ($nr, $xref, $infil) = @_;
    my ($i, $root, $antal);    
    $nr++;
    $oldObject{('xref' . "$nr")} = $xref;  # Offset för xref sparas 
    $xref += 5;
    sysseek INFIL, $xref, 0;      
    $xref  = 0;
    my $inrad = '';
    my $buf   = '';
    my $c;
    sysread INFIL, $c, 1;
    while ($c =~ m!\s!s)   
    {  sysread INFIL, $c, 1; }

    while ( (defined $c)
    &&   ($c ne "\n")
    &&   ($c ne "\r") )   
    {    $inrad .= $c;
         sysread INFIL, $c, 1;
    }

    if ($inrad =~ m'^(\d+)\s+(\d+)'o)
    {   $i     = $1;
        $antal = $2;
    }
            
    while ($antal)
    {   for (my $l = 1; $l <= $antal; $l++)
        {  sysread INFIL, $inrad, 20;
           if ($inrad =~ m'^\s?(\d+) \d+ (\w)\s*'o)
           {  if ($2 eq 'n')
              {  if (! (exists $oldObject{$i}))
                 {  $oldObject{$i} = int($1); }
                 else
                 {  $nr++;
                    $oldObject{'xref' . "$nr"} = int($1);
                 }
              } 
           }
           $i++;
        }
        undef $antal;
        undef $inrad;
        sysread INFIL, $c, 1;
        while ($c =~ m!\s!s)   
        {  sysread INFIL, $c, 1; }

        while ( (defined $c)
        &&   ($c ne "\n")
        &&   ($c ne "\r") )   
        {    $inrad .= $c;
             sysread INFIL, $c, 1;
        }
        if ($inrad =~ m'^(\d+)\s+(\d+)'o)
        {   $i     = $1;
            $antal = $2;
        }

    }
             
    while ($inrad)
    {   if ($buf =~ m'Encrypt'o)
        {  errLog("The file $infil is encrypted, cannot be used, aborts");
        }
        if ((! $root) && ($buf =~ m'\/Root\s+(\d+)\s{1,2}\d+\s{1,2}R'so))
        {  $root = $1;
           if ($xref)
           { last; }
        }

        if ((! $xref) && ($buf =~ m'\/Prev\s+(\d+)\D'so))
        {  $xref = $1;
           if ($root)
           { last; }
        }
                
        if ($buf =~ m'xref'so)
        {  last; }
                
        sysread INFIL, $inrad, 30;
        $buf .= $inrad;
    }
    return ($xref, $root, $nr);
}
 
sub getObject
{   my ($nr, $noId, $noEnd) = @_;
    
    my $buf;
    my ($offs, $siz, $embedded) = @{$oldObject{$nr}};
    
    if ($offs)
    {  sysseek INFIL, $offs, 0;
       sysread INFIL, $buf, $siz;
       if (($noId) && ($noEnd))
       {   if ($buf =~ m'^\d+ \d+ obj\s*(.*)endobj'os)
           {   if (wantarray)
               {   return ($1, $offs, $siz, $embedded);
               }
               else
               {   return $1;
               } 
           }
       }
       elsif ($noId)
       {   if ($buf =~ m'^\d+ \d+ obj\s*(.*)'os)
           {   if (wantarray)
               {   return ($1, $offs, $siz, $embedded);
               }
               else
               {   return $1;
               } 
           }
       }
       if (wantarray)
       {   return ($buf, $offs, $siz, $embedded)
       }
       else
       {   return $buf;
       } 
    }
    elsif (exists $unZipped{$nr})
    {  ;
    }
    elsif ($embedded)
    {   unZipPrepare($embedded);
    }
    if ($noEnd)
    {   if (wantarray)
        {   return ($unZipped{$nr}, $offs, $siz, $embedded)
        }
        else
        {   return $unZipped{$nr};
        }
    }
    else
    {   if (wantarray)
        {   return ("$unZipped{$nr}endobj\n", $offs, $siz, $embedded)
        }
        else
        {   return "$unZipped{$nr}endobj\n";
        }
    } 
}

sub getKnown
{   my ($p, $nr) = @_;
    my ($del1, $del2);
    my @objData = @{$$$p[0]->{$nr}};
    if (defined $objData[oSTREAMP])
    {  sysseek INFIL, ($objData[oNR][0] + $objData[oPOS]), 0;
       sysread INFIL, $del1, ($objData[oSTREAMP] - $objData[oPOS]);
       sysread INFIL, $del2, ($objData[oNR][1]   - $objData[oSTREAMP]);
    }
    else
    {  my $buf;
       my ($offs, $siz, $embedded) = @{$objData[oNR]};
       if ($offs)
       {  sysseek INFIL, $offs, 0;
          sysread INFIL, $buf, $siz;
          if ($buf =~ m'^\d+ \d+ obj\s*(.*)'os)
          {   $del1 = $1;
          }  
       }
       elsif (exists $unZipped{$nr})
       {  $del1 = "$unZipped{$nr} endobj";
       }
       elsif ($embedded)
       {   @objData = @{$$$p[0]->{$embedded}};
           unZipPrepare($embedded, $objData[oNR][0], $objData[oNR][1]);
           $del1 = "$unZipped{$nr} endobj"; 
       }        
    }
    return (\$del1, \$del2, $objData[oKIDS], $objData[oTYPE]);
}


sub unZipPrepare
{  my ($nr, $offs, $size) = @_;
   my $buf;
   if ($offs)
   {   sysseek INFIL, $offs, 0;
       sysread INFIL, $buf, $size;
   }
   else
   {   $buf = getObject($nr);
   }
   my (%param, $stream, $str);
   
   if ($buf =~ m'^(\d+ \d+ obj\s*<<[\w\d\/\s\[\]<>]+)stream\b'os)
   {  $str  = $1;
      $offs = length($str) + 7;
      if (substr($buf, $offs, 1) eq "\n")
      {  $offs++;
      }

      for (split('/',$str))
      {  if ($_ =~ m'^(\w+)(.*)'o)
         {  $param{$1} = $2 || ' ';
         }
      }
      $stream = substr($buf, $offs, $param{'Length'});
      my $x = inflateInit()
           || die "Cannot create an inflation stream\n";
      my ($output, $status) = $x->inflate($stream);
      die "inflation failed\n"
                     unless $status == 1;

      my $first = $param{'First'};
      my @oOffsets = (substr($output, 0, $first) =~ m'(\d+)\b'osg);
      my $i = 0;
      my $j = 1;
      my $bytes;
      while ($oOffsets[$i])
      {  my $k = $j + 2;
         if ($oOffsets[$k])
         {  $bytes = $oOffsets[$k] - $oOffsets[$j];
         }
         else 
         {  $bytes = length($output) - $first - $oOffsets[$j];
         }         
         $unZipped{$oOffsets[$i]} = substr($output,($first + $oOffsets[$j]), $bytes); 
         $i += 2;
         $j += 2;
      }
   }
}
         
############################################
# En definitionerna för en sida extraheras
############################################

sub getPage
{  my ($infil, $sidnr, $action)  = @_;

   my ($res, $i, $referens,$objNrSaved,$validStream, $formRes, @objData, 
       @underObjekt, @sidObj, $strPos, $startSida, $sidor, $filId, $del1, $del2,
       $offs, $siz, $embedded, $vektor, $utrad, $robj, $valid, $Annots, $Names,
       $AcroForm, $AARoot, $AAPage);

   my $sidAcc = 0;
   my $seq    = 0;
   $imSeq     = 0;
   @skapa     = ();   
   undef $formCont;
   
   
   $objNrSaved = $objNr;   
   my $fSource = $infil . '_' . $sidnr;
   my $checkidOld = $checkId;
   ($infil, $checkId) = findGet($infil, $checkidOld);
   if (($ldir) && ($checkId) && ($checkId ne $checkidOld))
   {  $log .= "Cid~$checkId\n";
   }
   $form{$fSource}[fID] =  $checkId;
   $checkId = '';
   $behandlad{$infil}->{old} = {} 
        unless (defined $behandlad{$infil}->{old});
   $processed{$infil}->{oldObject} = {} 
        unless (defined $processed{$infil}->{oldObject});   
   $processed{$infil}->{unZipped} = {} 
        unless (defined $processed{$infil}->{unZipped});

   if ($action eq 'print')
   {  *old = $behandlad{$infil}->{old};
   }
   else
   {  $behandlad{$infil}->{dummy} = {};
      *old = $behandlad{$infil}->{dummy};
   }
   
   *oldObject =  $processed{$infil}->{oldObject};
   *unZipped  = $processed{$infil}->{unZipped};
   $root      = (exists $processed{$infil}->{root}) 
                    ? $processed{$infil}->{root} : 0;
   
   
   my @stati = stat($infil);
   open (INFIL, "<$infil") || errLog("Couldn't open $infil, $!");
   binmode INFIL;

   if (! $root)
   {  $root = xRefs($stati[7], $infil);
   }

   #############
   # Hitta root
   #############           

   my $objektet = getObject($root);;
   
   if ($sidnr == 1) 
   {  if ($objektet =~ m'/AcroForm(\s+\d+\s{1,2}\d+\s{1,2}R)'so)
      {  $AcroForm = $1;
      }
      if ($objektet =~ m'/Names\s+(\d+)\s{1,2}\d+\s{1,2}R'so)
      {  $Names = $1;
      } 
      #################################################
      #  Finns ett dictionary för Additional Actions ?
      #################################################
      if ($objektet =~ m'/AA\s*\<\<\s*[^\>]+[^\>]+'so) # AA är ett dictionary
      {  my $k;
         my ($dummy, $obj) = split /\/AA/, $objektet;
         $obj =~ s/\<\</\#\<\</gs;
         $obj =~ s/\>\>/\>\>\#/gs;
         my @ord = split /\#/, $obj;
         for ($i = 0; $i <= $#ord; $i++)
         {   $AARoot .= $ord[$i];
             if ($ord[$i] =~ m'\S+'os)
             {  if ($ord[$i] =~ m'<<'os)
                {  $k++; }
                if ($ord[$i] =~ m'>>'os)
                {  $k--; }
                if ($k == 0)
                {  last; }
             } 
          }
      }
   }
     
   #
   # Hitta pages
   #
 
   if ($objektet =~ m'/Pages\s+(\d+)\s{1,2}\d+\s{1,2}R'os)
   {  $objektet = getObject($1);
      if ($objektet =~ m'/Count\s+(\d+)'os)
      {  $sidor = $1;
         if ($sidnr <= $sidor)
         {  ($formRes, $valid) = kolla($objektet); 
         }
         else
         {   return 0;
         }
         if ($sidor > 1)
         {   undef $AcroForm;
             undef $Names;
             undef $AARoot;
             if ($type eq 'docform')
             {  errLog("prDocForm can only be used for single page documents - try prDoc or reformat $infil");
             }
         }
      }
   }
   else
   { errLog("Didn't find Pages in $infil - aborting"); }

   if ($objektet =~ m'/Kids\s*\[([^\]]+)'os)
   {  $vektor = $1; } 
   while ($vektor =~ m'(\d+)\s{1,2}\d+\s{1,2}R'go)
   {   push @sidObj, $1;       
   }

   my $bryt1 = -20;                     # Hängslen
   my $bryt2 = -20;                     # Svångrem för att undvika oändliga loopar
   
   while ($sidAcc < $sidnr)
   {  @underObjekt = @sidObj;
      @sidObj     = ();
      $bryt1++;
      for my $uO (@underObjekt)
      {  $objektet = getObject($uO);
         if ($objektet =~ m'/Count\s+(\d+)'os)
         {  if (($sidAcc + $1) < $sidnr)
            {  $sidAcc += $1; }
            else
            {  ($formRes, $valid) = kolla($objektet, $formRes);
               if ($objektet =~ m'/Kids\s*\[([^\]]+)'os)
               {  $vektor = $1; } 
               while ($vektor =~ m'(\d+)\s{1,2}\d+\s{1,2}R'gso)
               {   push @sidObj, $1;  }
               last; 
            }
         }
         else
         {  $sidAcc++; }
         if ($sidAcc == $sidnr)
         {   $seq = $uO;
             last;  }
         $bryt2++;
      }
      if (($bryt1 > $sidnr) || ($bryt2 > $sidnr))   # Bryt oändliga loopar 
      {  last; } 
   }    

   ($formRes, $validStream) = kolla($objektet, $formRes);
   $startSida = $seq;
       
   if ($sidor == 1)
   {  #################################################
      # Kontrollera Page-objektet för annoteringar
      #################################################

      if ($objektet =~ m'/Annots\s*([^\/]+)'so)
      {  $Annots = $1;
      } 
      #################################################
      #  Finns ett dictionary för Additional Actions ?
      #################################################
      if ($objektet =~ m'/AA\s*\<\<\s*[^\>]+[^\>]+'so)  # AA är ett dictionary. Hela kopieras
      {  my $k;
         my ($dummy, $obj) = split /\/AA/, $objektet;
         $obj =~ s/\<\</\#\<\</gs;
         $obj =~ s/\>\>/\>\>\#/gs;
         my @ord = split /\#/, $obj;
         for ($i = 0; $i <= $#ord; $i++)
         {   $AAPage .= $ord[$i];
             if ($ord[$i] =~ m'\S+'s)
             {  if ($ord[$i] =~ m'<<'s)
                {  $k++; }
                if ($ord[$i] =~ m'>>'s)
                {  $k--; }
                if ($k == 0)
                {  last; }
             } 
          }
      }      
   }

   my $rform = \$form{$fSource};
   @$$rform[fRESOURCE]  = $formRes;
   my @BBox;
   if (defined $formBox[0])
   {  $BBox[0] = $formBox[0]; }
   else
   {  $BBox[0] = $genLowerX; }
 
   if (defined $formBox[1])
   {  $BBox[1] = $formBox[1]; }
   else
   {  $BBox[1] = $genLowerY; }
 
   if (defined $formBox[2])
   {  $BBox[2] = $formBox[2]; }
   else
   {  $BBox[2] = $genUpperX; }
 
   if (defined $formBox[3])
   {  $BBox[3] = $formBox[3]; }
   else
   {  $BBox[3] = $genUpperY; }
 
   @{$form{$fSource}[fBBOX]} = @BBox;

   if ($formCont) 
   {   $seq = $formCont;
       ($objektet, $offs, $siz, $embedded) = getObject($seq);
       
       $robj  = \$$$rform[fOBJ]->{$seq};
       @{$$$robj[oNR]} = ($offs, $siz, $embedded);
       $$$robj[oFORM] = 'Y';
       $form{$fSource}[fMAIN] = $seq;
       if ($objektet =~ m'^(\d+ \d+ obj\s*<<)(.+)(>>\s*stream)'so)
       {  $del1   = $2;
          $strPos           = length($1) + length($2) + length($3);
          $$$robj[oPOS]     = length($1);      
          $$$robj[oSTREAMP] = $strPos; 
          my $nyDel1;
          $nyDel1 = '<</Type/XObject/Subtype/Form/FormType 1'; 
          $nyDel1 .= "/Resources $formRes" .
                     "/BBox \[ $BBox[0] $BBox[1] $BBox[2] $BBox[3]\]" .
                     # "/Matrix \[ 1 0 0 1 0 0 \]" .
                     $del1;
          if ($action eq 'print')
          {  $objNr++;
             $objekt[$objNr] = $pos;
          }
          $referens = $objNr;

          $res = ($nyDel1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs);
          if ($res)
          { $$$robj[oKIDS] = 1; }
          if ($action eq 'print')
          {   $utrad  = "$referens 0 obj\n" . "$nyDel1" . ">>\nstream";
              $del2   = substr($objektet, $strPos);
              $utrad .= $del2;
              $pos   += syswrite UTFIL, $utrad;
          }
          $form{$fSource}[fVALID] = $validStream;
      }
      else                              # Endast resurserna kan behandlas
      {   $formRes =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;  
      }
   }
   else                                # Endast resurserna kan behandlas
   {  $formRes =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
   } 
      
   my $preLength;
   while (scalar @skapa)
   {  my @process = @skapa;
      @skapa = ();
      for (@process)
      {  my $Font;
         my $gammal = $$_[0];
         my $ny     = $$_[1];
         ($objektet, $offs, $siz, $embedded)  = getObject($gammal);
         $robj      = \$$$rform[fOBJ]->{$gammal};
         @{$$$robj[oNR]} = ($offs, $siz, $embedded);      
         if ($objektet =~ m'^(\d+ \d+ obj\s*<<)(.+)(>>\s*stream)'os)
         {  $del1             = $2;
            $strPos           = length ($1) + length($2) + length($3);
            $$$robj[oPOS]     = length($1);
            $$$robj[oSTREAMP] = $strPos;
 
            ######## En bild ########
            if ($del1 =~ m'/Subtype\s*/Image'so)
            {  $imSeq++;
               $$$robj[oIMAGENR] = $imSeq;
               push @{$$$rform[fIMAGES]}, $gammal;

               if ($del1 =~ m'/Width\s+(\d+)'os)
               {  $$$robj[oWIDTH] = $1; }
               if ($del1 =~ m'/Height\s+(\d+)'os)
               {  $$$robj[oHEIGHT] = $1; }
            }     
            $res = ($del1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs);
            if ($res)
            { $$$robj[oKIDS] = 1; }            
            if ($action eq 'print')
            {   $objekt[$ny] = $pos;
                $utrad  = "$ny 0 obj\n<<" . "$del1" . '>>stream';
                $del2   = substr($objektet, $strPos);
                $utrad .= $del2; 
            }
         }
         else
         {  if ($objektet =~ m'^(\d+ \d+ obj\s*)'os)
            {  $preLength = length($1);
               $$$robj[oPOS] = $preLength;               
               $objektet     = substr($objektet, $preLength);
            }
            else
            {  $$$robj[oPOS] = 0;
            }
            $res = ($objektet =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs);
            if ($res)
            { $$$robj[oKIDS] = 1; }
            if ($objektet =~ m'/Subtype\s*/Image'so)
            {  $imSeq++;
               $$$robj[oIMAGENR] = $imSeq;
               push @{$$$rform[fIMAGES]}, $gammal;
               ###################################
               # Sparar dimensionerna för bilden
               ###################################
               if ($del1 =~ m'/Width\s+(\d+)'os)
               {  $$$robj[oWIDTH] = $1; }
      
               if ($del1 =~ m'/Height\s+(\d+)'os)
               {  $$$robj[oHEIGHT] = $1; }
            }
            elsif ($objektet =~ m'/BaseFont\s*/([^\s\/]+)'os)
            {  $Font = $1;
               $$$robj[oTYPE] = 'Font';
               $$$robj[oNAME] = $Font;
               if ((! exists $font{$Font}) 
               && ($action))
               {  $fontNr++;
                  $font{$Font}[foINTNAMN]          = 'Ft' . $fontNr;
                  $font{$Font}[foORIGINALNR]       = $gammal;
                  $fontSource{$Font}[foSOURCE]     = $fSource;
                  $fontSource{$Font}[foORIGINALNR] = $gammal;
                  if ($objektet =~ m'/Subtype\s*/Type0'os)
                  {  $font{$Font}[foTYP] = 1;
                  }
                  if ($action eq 'print')
                  {  $font{$Font}[foREFOBJ]  = $ny;
                     $objRef{'Ft' . $fontNr} = $ny;
                  }
               }   
            }
               
            if ($action eq 'print')
            {   $objekt[$ny] = $pos;
                $utrad = "$ny 0 obj $objektet";
            }
         }
         if ($action eq 'print')
         {   $pos += syswrite UTFIL, $utrad;
         }
       }
   }
   
   my $ref = \$form{$fSource};
   my @kids;
   my @nokids;  
   
   #################################################################
   # lägg upp vektorer över vilka objekt som har KIDS eller NOKIDS
   #################################################################   

   for my $key (keys %{$$$ref[fOBJ]})
   {   $robj  = \$$$ref[fOBJ]->{$key};
       if (! defined  $$$robj[oFORM])
       {   if (defined  $$$robj[oKIDS])
           {   push @kids, $key; }
           else
           {   push @nokids, $key; }
       }
       if ((defined $$$robj[0]->[2]) && (! exists $$$ref[fOBJ]->{$$$robj[0]->[2]}))
       {  $$$ref[fOBJ]->{$$$robj[0]->[2]}->[0] = $oldObject{$$$robj[0]->[2]};
       }
   }
   if (scalar @kids)
   {  $form{$fSource}[fKIDS] = \@kids; 
   } 
   if (scalar @nokids)
   {  $form{$fSource}[fNOKIDS] = \@nokids; 
   } 
   
   if ($action ne 'print')
   {  $objNr = $objNrSaved;            # Restore objNo if nothing was printed
   }

   $behandlad{$infil}->{dummy} = {};
   *old = $behandlad{$infil}->{dummy};
    
   $objNrSaved = $objNr;               # Save objNo

   if ($sidor == 1)
   {   @skapa = ();
       $old{$startSida} = $sidObjNr;
       my $ref = \$intAct{$fSource};
       @$$ref[iSTARTSIDA] = $startSida;
       if (defined $Names)
       {   @$$ref[iNAMES] = $Names;
           quickxform($Names);
       }
       if (defined $AcroForm)
       {   @$$ref[iACROFORM] = $AcroForm;
           $AcroForm =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
       }
       if (defined $AARoot)
       {   @$$ref[iAAROOT] = $AARoot;
           $AARoot =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
       }
       if (defined $AAPage)
       {   @$$ref[iAAPAGE] = $AAPage;
           $AAPage =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
       }
       if (defined $Annots)
       {   my @array;
           if ($Annots =~ m'\[([^\[\]]*)\]'os)
           {  $Annots = $1;
              @array = ($Annots =~ m'\b(\d+)\s{1,2}\d+\s{1,2}R\b'ogs);  
           }
           else
           {  if ($Annots =~ m'\b(\d+)\s{1,2}\d+\s{1,2}R\b'os)
              {  $Annots = getObject($1);
                 @array = ($Annots =~ m'\b(\d+)\s{1,2}\d+\s{1,2}R\b'ogs);
              }
           }             
           @$$ref[iANNOTS] = \@array;
           $Annots =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
       }
      
      while (scalar @skapa)
      {  my @process = @skapa;
         @skapa = ();
         for (@process)
         {  my $gammal = $$_[0];
            my $ny     = $$_[1];
            ($objektet, $offs, $siz, $embedded) = getObject($gammal);
            $robj  = \$$$ref[fOBJ]->{$gammal};
            @{$$$robj[oNR]} = ($offs, $siz, $embedded);
            if ($objektet =~ m'^(\d+ \d+ obj\s*<<)(.+)(>>\s*stream)'os)
            {  $del1             = $2;
               $$$robj[oPOS]     = length($1);
               $$$robj[oSTREAMP] = length($1) + length($2) + length($3);
                  
               $res = ($del1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs);
               if ($res)
               { $$$robj[oKIDS] = 1; }  
            }
            else
            {  if ($objektet =~ m'^(\d+ \d+ obj)'os)
               {  my $preLength = length($1);
                  $$$robj[oPOS] = $preLength;
                  $objektet = substr($objektet, $preLength);
                                 
                  $res = ($objektet =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs);
                  if ($res)
                  { $$$robj[oKIDS] = 1; }
                }
             }
         }
      }
      for my $key (keys %{$$$ref[fOBJ]})
      {   $robj  = \$$$ref[fOBJ]->{$key};
          if ((defined $$$robj[0]->[2]) && (! exists $$$ref[fOBJ]->{$$$robj[0]->[2]}))
          {  $$$ref[fOBJ]->{$$$robj[0]->[2]}->[0] = $oldObject{$$$robj[0]->[2]};
          }
      }
  }

  $objNr = $objNrSaved;
  $processed{$infil}->{root}         = $root;
  close INFIL;
  return $referens;
}  

##################################################
# Översätter ett gammalt objektnr till ett nytt
# och sparar en tabell med vad som skall skapas
##################################################

sub xform
{  if (exists $old{$1})
   {  $old{$1}; 
   }
   else
   {  push @skapa, [$1, ++$objNr];
      $old{$1} = $objNr;                   
   } 
}
 
sub kolla
{  #
   # Resurser
   #
   my $obj       = shift;
   my $resources = shift;
   my $valid;
    
   if ($obj =~ m'MediaBox\s*\[\s*([\-\.\d]+)\s+([\-\.\d]+)\s+([\-\.\d]+)\s+([\-\.\d]+)'os)
   { $formBox[0] = $1;
     $formBox[1] = $2;
     $formBox[2] = $3;
     $formBox[3] = $4;
   }
  
   if ($obj =~ m'/Contents\s+(\d+)'so)
   {  $formCont = $1;
      my $cObj = getObject($formCont, 1, 1);
      if ($cObj =~ m'^\s*\[[^\]]+\]\s*$'os)
      {   $valid = 0;
          undef $formCont;
      }
      else
      {   $valid    = 1;
      }
   }
   elsif ($obj =~ m'/Contents\s*\[\s*(\d+)\s{1,2}\d+\s{1,2}R\s*\]'so)
   { $formCont = $1;
     $valid    = 1;
   }
   
   if ($obj =~ m'^(.+/Resources)'so)
   {  if ($obj =~ m'Resources(\s+\d+\s{1,2}\d+\s{1,2}R)'os)   # Hänvisning
      {  $resources = $1; }
      else                 # Resurserna är ett dictionary. Hela kopieras
      {  my $dummy;
         my $i;
         my $k;
         undef $resources;
         ($dummy, $obj) = split /\/Resources/, $obj;
         $obj =~ s/\<\</\#\<\</gs;
         $obj =~ s/\>\>/\>\>\#/gs;
         my @ord = split /\#/, $obj;
         for ($i = 0; $i <= $#ord; $i++)
         {   $resources .= $ord[$i];
             if ($ord[$i] =~ m'\S+'s)
             {  if ($ord[$i] =~ m'<<'s)
                {  $k++; }
                if ($ord[$i] =~ m'>>'s)
                {  $k--; }
                if ($k == 0)
                {  last; }
             } 
          }
       }
    }
    return ($resources, $valid);
}

##############################
# Ett formulär (åter)skapas
##############################

sub byggForm
{  no warnings; 
   my ($infil, $sidnr) = @_;
   
   my ($res, $corr, $nyDel1, $formRes, $del1, $del2, $kids, $typ, $nr,
       $utrad);
      
   my $fSource = $infil . '_' . $sidnr;
   my @stati = stat($infil);

   $behandlad{$infil}->{old} = {} 
        unless (defined $behandlad{$infil}->{old});
   $processed{$infil}->{oldObject} = {} 
        unless (defined $processed{$infil}->{oldObject});   
   $processed{$infil}->{unZipped} = {} 
        unless (defined $processed{$infil}->{unZipped});

   *old       = $behandlad{$infil}->{old};
   *oldObject = $processed{$infil}->{oldObject};
   *unZipped  = $processed{$infil}->{unZipped};
      
   if ($form{$fSource}[fID] != $stati[9])
   {    errLog("$stati[9] ne $form{$fSource}[fID] aborts");
   }
   if ($checkId) 
   {  if ($checkId ne $stati[9])
      {  my $mess =  "$checkId \<\> $stati[9] \n"
                  . "The Pdf-file $fSource has not the correct modification time. \n"
                  .  "The program is aborted";
         errLog($mess);
      }
      undef $checkId;
    }
    if ($ldir)
    {  $log .= "Cid~$stati[9]\n";
    }

   open (INFIL, "<$infil") || errLog("The file $infil couldn't be opened, aborting $!");
   binmode INFIL;

   ####################################################
   # Objekt utan referenser  kopieras och skrivs
   ####################################################   

   for my $key (@{$form{$fSource}->[fNOKIDS]})
   {   if ((defined $old{$key}) && ($objekt[$old{$key}]))    # already processed
       {  next;
       }
              
       if (! defined $old{$key})
       {  $old{$key} = ++$objNr;
       }
       $nr = $old{$key};
       $objekt[$nr] = $pos;
     
       ($del1, $del2, $kids, $typ) = getKnown(\$form{$fSource},$key);
             
       if ($typ eq 'Font')
       {  my $Font = ${$form{$fSource}}[0]->{$key}->[oNAME];
          if (! defined $font{$Font}[foINTNAMN])
          {  $fontNr++;
             $font{$Font}[foINTNAMN]  = 'Ft' . $fontNr;
             $font{$Font}[foREFOBJ]   = $nr;
             $objRef{'Ft' . $fontNr}  = $nr;
          }
       }
       if (! defined $$del2)
       {   $utrad = "$nr 0 obj " . $$del1;
       }
       else
       {   $utrad = "$nr 0 obj\n<<" . $$del1 . $$del2;
       }     
       $pos += syswrite UTFIL, $utrad;     
   }

   #######################################################
   # Objekt med referenser kopieras, behandlas och skrivs
   #######################################################
   for my $key (@{$form{$fSource}->[fKIDS]})
   {   if ((defined $old{$key}) && ($objekt[$old{$key}]))  # already processed
       {  next;
       }
        
       if (! defined $old{$key})
       {  $old{$key} = ++$objNr;
       }
       $nr = $old{$key};
       
       $objekt[$nr] = $pos;
       
       ($del1, $del2, $kids, $typ) = getKnown(\$form{$fSource},$key);

       $$del1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/translate() . ' 0 R'/oegs;
       
       if (defined $$del2)          
       {  $utrad = "$nr 0 obj\n<<" . $$del1 . $$del2;
       }
       else
       {  $utrad = "$nr 0 obj " . $$del1;
       } 
       
       if (($typ) && ($typ eq 'Font'))
       {  my $Font = $form{$fSource}[0]->{$key}->[oNAME];
          if (! defined $font{$Font}[foINTNAMN])
          {  $fontNr++;
             $font{$Font}[foINTNAMN]  = 'Ft' . $fontNr;
             $font{$Font}[foREFOBJ]   = $nr;
             $objRef{'Ft' . $fontNr} = $nr;
          }
       }   
       
       $pos += syswrite UTFIL, $utrad;                
   }

   #################################
   # Formulärobjektet behandlas 
   #################################
   
   my $key = $form{$fSource}->[fMAIN];
   if (! defined $key)
   {  return undef;
   }

   if (exists $old{$key})                      # already processed
   {  close INFIL;
      return $old{$key}; 
   }

   $nr = ++$objNr;
   
   $objekt[$nr] = $pos;
   
   $formRes = $form{$fSource}->[fRESOURCE];   
    
   ($del1, $del2) = getKnown(\$form{$fSource}, $key);  

   $nyDel1 = '<</Type/XObject/Subtype/Form/FormType 1'; 
   $nyDel1 .= "/Resources $formRes" .
                 '/BBox [' .
                 $form{$fSource}->[fBBOX]->[0]  . ' ' .
                 $form{$fSource}->[fBBOX]->[1]  . ' ' .
                 $form{$fSource}->[fBBOX]->[2]  . ' ' .
                 $form{$fSource}->[fBBOX]->[3]  . ' ]' .  
                 # "\]/Matrix \[ $sX 0 0 $sX $tX $tY \]" .
                 $$del1;
   $nyDel1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/translate() . ' 0 R'/oegs;

   $utrad = "$nr 0 obj" . $nyDel1 . $$del2;
   
   $pos += syswrite UTFIL, $utrad;                    
   close INFIL;

   return $nr;   
}

##################
#  En bild läses
##################

sub getImage
{  my ($infil, $sidnr, $bildnr, $key) =  @_;
   if (! defined $key)
   {  errLog("Can't find image $bildnr on page $sidnr in file $infil, aborts");
   } 
   
   @skapa = ();
   my ($res, $corr, $nyDel1, $del1, $del2, $nr, $utrad);
   my $fSource = $infil . '_' . $sidnr;
   my $iSource = $fSource . '_' . $bildnr;

   $behandlad{$infil}->{old} = {} 
        unless (defined $behandlad{$infil}->{old});
   $processed{$infil}->{oldObject} = {} 
        unless (defined $processed{$infil}->{oldObject});   
   $processed{$infil}->{unZipped} = {} 
        unless (defined $processed{$infil}->{unZipped});  

   *old       = $behandlad{$infil}->{old};
   *oldObject = $processed{$infil}->{oldObject};
   *unZipped  = $processed{$infil}->{unZipped};
      
   my @stati = stat($infil);

   if ($form{$fSource}[fID] != $stati[9])
   {    errLog("$stati[9] ne $form{$fSource}[fID], modification time has changed, aborting");
   }

   if (exists $old{$key})
   {  return $old{$key}; 
   }

   open (INFIL, "<$infil") || errLog("The file $infil couldn't be opened, $!");
   binmode INFIL; 

   #########################################################
   # En bild med referenser kopieras, behandlas och skrivs
   #########################################################

   $nr = ++$objNr;
   $old{$key} = $nr;
   
   $objekt[$nr] = $pos;

   ($del1, $del2) = getKnown(\$form{$fSource}, $key);

   $$del1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;      
   if (defined $$del2)
   {  $utrad = "$nr 0 obj\n<<" . $$del1 . $$del2;
   }
   else
   {  $utrad = "$nr 0 obj " . $$del1;
   }
   $pos += syswrite UTFIL, $utrad;
   ##################################
   #  Skriv ut underordnade objekt
   ################################## 
   while (scalar @skapa)
   {  my @process = @skapa;
      @skapa = ();
      for (@process)
      {  my $gammal = $$_[0];
         my $ny     = $$_[1];

         ($del1, $del2) = getKnown(\$form{$fSource}, $gammal);

         $$del1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;      
         if (defined $$del2)
         {  $utrad = "$ny 0 obj\n<<" . $$del1 . $$del2;
         }
         else
         {  $utrad = "$ny 0 obj " . $$del1;
         }
         $objekt[$ny] = $pos;
         $pos += syswrite UTFIL, $utrad;
      }
   }
        
   close INFIL;
   return $nr;   
   
}

##############################################################
#  Interaktiva funktioner knutna till ett formulär återskapas
##############################################################

sub AcroFormsEtc
{  my ($infil, $sidnr) =  @_;
   
   my ($Names, $AARoot, $AAPage, $AcroForm);
   @skapa = ();
   
   my ($res, $corr, $nyDel1, @objData, $del1, $del2, $utrad);
   my $fSource = $infil . '_' . $sidnr;

   $behandlad{$infil}->{old} = {} 
        unless (defined $behandlad{$infil}->{old});
   $processed{$infil}->{oldObject} = {} 
        unless (defined $processed{$infil}->{oldObject});   
   $processed{$infil}->{unZipped} = {} 
        unless (defined $processed{$infil}->{unZipped});   

   *old       = $behandlad{$infil}->{old};
   *oldObject = $processed{$infil}->{oldObject};
   *unZipped  = $processed{$infil}->{unZipped};
        
   my @stati = stat($infil);
   if ($form{$fSource}[fID] != $stati[9])
   {    print "$stati[9] ne $form{$fSource}[fID]\n";
        errLog("Modification time for $fSource has changed, aborting");
   }
    
   open (INFIL, "<$infil") || errLog("The file $infil couldn't be opened, aborting $!");
   binmode INFIL;

   my $fdSidnr = $intAct{$fSource}[iSTARTSIDA];
   $old{$fdSidnr} = $sidObjNr;

   if (($intAct{$fSource}[iNAMES]) ||(scalar @jsfiler) || (scalar @inits) || (scalar %fields))
   {  $Names  = behandlaNames($intAct{$fSource}[iNAMES], $fSource);
   }
   
   ##################################
   # Referenser behandlas och skrivs
   ##################################
         
   if (defined $intAct{$fSource}[iACROFORM])
   {   $AcroForm = $intAct{$fSource}[iACROFORM];
       $AcroForm =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
   }
   if (defined $intAct{$fSource}[iAAROOT])
   {  $AARoot = $intAct{$fSource}[iAAROOT];
      $AARoot =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
   }
   
   if (defined $intAct{$fSource}[iAAPAGE])
   {   $AAPage = $intAct{$fSource}[iAAPAGE];
       $AAPage =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
   }
   if (defined $intAct{$fSource}[iANNOTS])
   {  for (@{$intAct{$fSource}[iANNOTS]})
      {  push @annots, quickxform($_);
      }
   }

   ##################################
   #  Skriv ut underordnade objekt
   ################################## 
   while (scalar @skapa)
   {  my @process = @skapa;
      @skapa = ();
      for (@process)
      {  my $gammal = $$_[0];
         my $ny     = $$_[1];
         
         my $oD   = \@{$intAct{$fSource}[0]->{$gammal}};
         @objData = @{$$oD[oNR]};

         if (defined $$oD[oSTREAMP])
         {  $res = sysseek INFIL, ($objData[0] + $$oD[oPOS]), 0;
            $corr = sysread INFIL, $del1, ($$oD[oSTREAMP] - $$oD[oPOS]) ;
            if (defined  $$oD[oKIDS]) 
            {   $del1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
            }
            $res = sysread INFIL, $del2, ($objData[1] - $corr); 
            $utrad = "$ny 0 obj\n<<" . $del1 . $del2;
         }
         else
         {  $del1 = getObject($gammal);
            $del1 = substr($del1, $$oD[oPOS]);
            if (defined  $$oD[oKIDS])
            {   $del1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
            }
            $utrad = "$ny 0 obj " . $del1;
         }

         $objekt[$ny] = $pos;
         $pos += syswrite UTFIL, $utrad;
      }
   }
    
   close INFIL;
   return ($Names, $AARoot, $AAPage, $AcroForm);
} 

##############################
# Ett namnobjekt extraheras
##############################

sub extractName
{  my ($infil, $sidnr, $namn) = @_;
   
   my ($res, $del1, $resType, $key, $corr, $formRes, $kids, $nr, $utrad);
   my $del2 = '';
   @skapa = ();
   
   $behandlad{$infil}->{old} = {} 
        unless (defined $behandlad{$infil}->{old});
   $processed{$infil}->{oldObject} = {} 
        unless (defined $processed{$infil}->{oldObject});   
   $processed{$infil}->{unZipped} = {} 
        unless (defined $processed{$infil}->{unZipped});

   *old       = $behandlad{$infil}->{old};
   *oldObject = $processed{$infil}->{oldObject};
   *unZipped  = $processed{$infil}->{unZipped};
   
   my $fSource = $infil . '_' . $sidnr;

   my @stati = stat($infil);

   if ($form{$fSource}[fID] != $stati[9])
   {    errLog("$stati[9] ne $form{$fSource}[fID] aborts");
   }
   if ($checkId) 
   {  if ($checkId ne $stati[9])
      {  my $mess =  "$checkId \<\> $stati[9] \n"
                  . "The Pdf-file $fSource has not the correct modification time. \n"
                  .  "The program is aborted";
         errLog($mess);
      }
      undef $checkId;
    }
    if ($ldir)
    {  $log .= "Cid~$stati[9]\n";
    }

   open (INFIL, "<$infil") || errLog("The file $infil couldn't be opened, aborting $!");
   binmode INFIL;

   #################################
   # Resurserna läses
   #################################

   $formRes = $form{$fSource}->[fRESOURCE];
   
   if ($formRes !~ m'<<.*>>'os)                   # If not a directory, get it
   {   if ($formRes =~ m'\b(\d+)\s{1,2}\d+\s{1,2}R'o)
       {  $key   = $1;
          $formRes = getKnown(\$form{$fSource}, $key);
       }
       else
       {  return undef;
       }
   }
   undef $key;
   while ($formRes =~ m'\/(\w+)\s*\<\<([^>]+)\>\>'osg)
   {   $resType = $1;
       my $str  = $2;
       if ($str =~ m|$namn\s+(\d+)\s{1,2}\d+\s{1,2}R|s)
       {   $key = $1;
           last;
       }
   }
   if (! defined $key)                      # Try to expand the references
   {   my ($str, $del1, $del2);
       while ($formRes =~ m'(\/\w+)\s+(\d+)\s{1,2}\d+\s{1,2}R'ogs)
       { $str .= $1 . ' ';
         ($del1, $del2) = getKnown(\$form{$fSource}, $2);
         my $string =  $$del1;
         $str .= $string . ' ';
       }
       $formRes = $str;
       while ($formRes =~ m'\/(\w+)\s*\<\<([^>]+)\>\>'osg)
       {   $resType = $1;
           my $str  = $2;
           if ($str =~ m|$namn (\d+)\s{1,2}\d+\s{1,2}R|s)
           {   $key = $1;
               last;
           }
       }
       return undef unless $key;
   }
    
   ########################################
   #  Read the top object of the hierarchy
   ########################################

   ($del1, $del2) = getKnown(\$form{$fSource}, $key);

   $objNr++;
   $nr = $objNr;

   if ($resType eq 'Font')
   {  my ($Font, $extNamn);
      if ($$del1 =~ m'/BaseFont\s*/([^\s\/]+)'os)
      {  $extNamn = $1;
         if (! exists $font{$extNamn})
         {  $fontNr++;
            $Font = 'Ft' . $fontNr;
            $font{$extNamn}[foINTNAMN]       = $Font;
            $font{$extNamn}[foORIGINALNR]    = $nr;
            if ($del1 =~ m'/Subtype\s*/Type0'os)
            {  $font{$extNamn}[foTYP] = 1;
            }
            $fontSource{$Font}[foSOURCE]     = $fSource;
            $fontSource{$Font}[foORIGINALNR] = $nr;            
         }
         $font{$extNamn}[foREFOBJ]   = $nr;
         $Font = $font{$extNamn}[foINTNAMN];
         $namn = $Font;
         $objRef{$Font}  = $nr;
      }
      else
      {  errLog("Inconsitency in $fSource, font $namn can't be found, aborting");
      }
   }
   elsif ($resType eq 'ColorSpace')
   {  $colorSpace++;
      $namn = 'Cs' . $colorSpace;
      $objRef{$namn} = $nr;
   }
   elsif ($resType eq 'Pattern')
   {  $pattern++;
      $namn = 'Pt' . $pattern;
      $objRef{$namn} = $nr;
   }
   elsif ($resType eq 'Shading')
   {  $shading++;
      $namn = 'Sh' . $shading;
      $objRef{$namn} = $nr;
   }
   elsif ($resType eq 'ExtGState')
   {  $gSNr++;
      $namn = 'Gs' . $gSNr;
      $objRef{$namn} = $nr;
   }
   elsif ($resType eq 'XObject')
   {  if (defined $form{$fSource}->[0]->{$nr}->[oIMAGENR])
      {  $namn = 'Ig' . $form{$fSource}->[0]->{$nr}->[oIMAGENR];
      }
      else
      {  $formNr++;
         $namn = 'Fo' . $formNr;
      }
      
      $objRef{$namn} = $nr;
   }

   $$del1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;

   if (defined $$del2)
   {  $utrad = "$nr 0 obj\n<<" . $$del1 . $$del2;
   }
   else
   {  $utrad = "$nr 0 obj " . $$del1;
   }
   $objekt[$nr] = $pos;
   $pos += syswrite UTFIL, $utrad;

   ##################################
   #  Skriv ut underordnade objekt
   ##################################
 
   while (scalar @skapa)
   {  my @process = @skapa;
      @skapa = ();
      for (@process)
      {  my $gammal = $$_[0];
         my $ny     = $$_[1];
         
         ($del1, $del2, $kids) = getKnown(\$form{$fSource}, $gammal);
         
         $$del1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs
                                     unless (! defined $kids);      
         if (defined $$del2)
         {  $utrad = "$ny 0 obj\n<<" . $$del1 . $$del2;
         }
         else
         {  $utrad = "$ny 0 obj " . $$del1;
         }
         $objekt[$ny] = $pos;
         $pos += syswrite UTFIL, $utrad;
      }
   }
   close INFIL;
   
   return $namn;   
 
}
 
########################
# Ett objekt extraheras
########################

sub extractObject
{  no warnings;
   my ($infil, $sidnr, $key, $typ) = @_;
   
   my ($res, $del1, $corr, $namn, $kids, $nr, $utrad);
   my $del2 = '';
   @skapa = ();

   $behandlad{$infil}->{old} = {} 
        unless (defined $behandlad{$infil}->{old});
   $processed{$infil}->{oldObject} = {} 
        unless (defined $processed{$infil}->{oldObject});   
   $processed{$infil}->{unZipped} = {} 
        unless (defined $processed{$infil}->{unZipped});

   *old       = $behandlad{$infil}->{old};
   *oldObject = $processed{$infil}->{oldObject};
   *unZipped  = $processed{$infil}->{unZipped};
   
   my $fSource = $infil . '_' . $sidnr;
   my @stati = stat($infil);

   if ($form{$fSource}[fID] != $stati[9])
   {    errLog("$stati[9] ne $form{$fSource}[fID] aborts");
   }
   if ($checkId) 
   {  if ($checkId ne $stati[9])
      {  my $mess =  "$checkId \<\> $stati[9] \n"
                  . "The Pdf-file $fSource has not the correct modification time. \n"
                  .  "The program is aborted";
         errLog($mess);
      }
      undef $checkId;
    }
    if ($ldir)
    {  $log .= "Cid~$stati[9]\n";
       my $indata = prep($infil);
       $log .= "Form~$indata~$sidnr~~load~1\n";
    }

   open (INFIL, "<$infil") || errLog("The file $infil couldn't be opened, aborting $!");
   binmode INFIL;

   ########################################
   #  Read the top object of the hierarchy
   ########################################

   ($del1, $del2, $kids) = getKnown(\$form{$fSource}, $key);
        
   if (exists $old{$key})
   {  $nr = $old{$key}; }
   else
   {  $old{$key} = ++$objNr;
      $nr = $objNr;
   }     
 
   if ($typ eq 'Font')
   {  my ($Font, $extNamn);
      if ($$del1 =~ m'/BaseFont\s*/([^\s\/]+)'os)
      {  $extNamn = $1;
         $fontNr++;
         $Font = 'Ft' . $fontNr;
         $font{$extNamn}[foINTNAMN]    = $Font;
         $font{$extNamn}[foORIGINALNR] = $key;
         if ($del1 =~ m'/Subtype\s*/Type0'os)
         {  $font{$extNamn}[foTYP] = 1;
         }
         if ( ! defined $fontSource{$extNamn}[foSOURCE])
         {  $fontSource{$extNamn}[foSOURCE]     = $fSource;
            $fontSource{$extNamn}[foORIGINALNR] = $key;            
         }
         $font{$extNamn}[foREFOBJ]   = $nr;
         $Font = $font{$extNamn}[foINTNAMN];
         $namn = $Font;
         $objRef{$Font}  = $nr;
      }
      else
      {  errLog("Error in $fSource, $key is not a font, aborting");
      }
   }
   elsif ($typ eq 'ColorSpace')
   {  $colorSpace++;
      $namn = 'Cs' . $colorSpace;
      $objRef{$namn} = $nr;
   }
   elsif ($typ eq 'Pattern')
   {  $pattern++;
      $namn = 'Pt' . $pattern;
      $objRef{$namn} = $nr;
   }
   elsif ($typ eq 'Shading')
   {  $shading++;
      $namn = 'Sh' . $shading;
      $objRef{$namn} = $nr;
   }
   elsif ($typ eq 'ExtGState')
   {  $gSNr++;
      $namn = 'Gs' . $gSNr;
      $objRef{$namn} = $nr;
   }
   elsif ($typ eq 'XObject')
   {  if (defined $form{$fSource}->[0]->{$nr}->[oIMAGENR])
      {  $namn = 'Ig' . $form{$fSource}->[0]->{$nr}->[oIMAGENR];
      }
      else
      {  $formNr++;
         $namn = 'Fo' . $formNr;
      }
      
      $objRef{$namn} = $nr;
   }

   $$del1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs 
                                  unless (! defined $kids);      
   if (defined $$del2)
   {  $utrad = "$nr 0 obj\n<<" . $$del1 . $$del2;
   }
   else
   {  $utrad = "$nr 0 obj " . $$del1;
   }

   $objekt[$nr] = $pos;
   $pos += syswrite UTFIL, $utrad;

   ##################################
   #  Skriv ut underordnade objekt
   ##################################
 
   while (scalar @skapa)
   {  my @process = @skapa;
      @skapa = ();
      for (@process)
      {  my $gammal = $$_[0];
         my $ny     = $$_[1];
         
         ($del1, $del2, $kids) = getKnown(\$form{$fSource}, $gammal);

         $$del1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs
                                 unless (! defined  $kids);
       
         if (defined $$del2)          
         {  $utrad = "$ny 0 obj<<" . $$del1 . $$del2;
         }
         else
         {  $utrad = "$ny 0 obj " . $$del1;
         } 

         $objekt[$ny] = $pos;
         $pos += syswrite UTFIL, $utrad;
      }
   }
   close INFIL;
   return $namn;      
}
 

##########################################
# En fil analyseras och sidorna kopieras
##########################################

sub analysera
{  my $infil = shift;
   my $from  = shift || 1;
   my $to    = shift || 0;
   my $singlePage = shift;
   my ($i, $res, @underObjekt, @sidObj, $vektor, $resources, $valid,
       $strPos, $sidor, $filId, $Root, $del1, $del2, $utrad);

   my $extraherade = 0;
   my $sidAcc = 0;
   @skapa     = ();
  
   $behandlad{$infil}->{old} = {}
        unless (defined $behandlad{$infil}->{old});
   $processed{$infil}->{oldObject} = {} 
        unless (defined $processed{$infil}->{oldObject});   
   $processed{$infil}->{unZipped} = {} 
        unless (defined $processed{$infil}->{unZipped});
   *old       = $behandlad{$infil}->{old};
   *oldObject = $processed{$infil}->{oldObject};
   *unZipped  = $processed{$infil}->{unZipped};

   $root      = (exists $processed{$infil}->{root}) 
                    ? $processed{$infil}->{root} : 0;
             
   my ($AcroForm, $Annots, $Names, $AARoot);
   undef $taInterAkt;
   undef %script;
   
   my $checkIdOld = $checkId;
   ($infil, $checkId) = findGet($infil, $checkIdOld);
   if (($ldir) && ($checkId) && ($checkId ne $checkIdOld))
   {  $log .= "Cid~$checkId\n";
   }
   undef $checkId;
   my @stati = stat($infil);
   open (INFIL, "<$infil") || errLog("Couldn't open $infil,aborting.  $!");
   binmode INFIL;
  
   if (! $root)
   {  $root      = xRefs($stati[7], $infil);
   }   
   #############
   # Hitta root
   #############           

   my $offSet;
   my $bytes;
   my $objektet = getObject($root);
   
   if ((! $interActive) && ( ! $to) && ($from == 1))
   {  if ($objektet =~ m'/AcroForm(\s+\d+\s{1,2}\d+\s{1,2}R)'so)
      {  $AcroForm = $1;
      }      
      if ($objektet =~ m'/Names\s+(\d+)\s{1,2}\d+\s{1,2}R'so)
      {  $Names = $1;
      }
      if ((scalar %fields) || (scalar @jsfiler) || (scalar @inits))
      {   $Names  = behandlaNames($Names);
      }
      elsif ($Names)
      {  $Names = quickxform($Names);
      }

      #################################################
      #  Finns ett dictionary för Additional Actions ?
      #################################################
      if ($objektet =~ m'/AA(\s+\d+\s{1,2}\d+\s{1,2}R)'os)   # Hänvisning
      {  $AARoot = $1; }
      elsif ($objektet =~ m'/AA\s*\<\<\s*[^\>]+[^\>]+'so) # AA är ett dictionary
      {  my $k;
         my ($dummy, $obj) = split /\/AA/, $objektet;
         $obj =~ s/\<\</\#\<\</gs;
         $obj =~ s/\>\>/\>\>\#/gs;
         my @ord = split /\#/, $obj;
         for ($i = 0; $i <= $#ord; $i++)
         {   $AARoot .= $ord[$i];
             if ($ord[$i] =~ m'\S+'os)
             {  if ($ord[$i] =~ m'<<'os)
                {  $k++; }
                if ($ord[$i] =~ m'>>'os)
                {  $k--; }
                if ($k == 0)
                {  last; }
             } 
          }
       }
       $taInterAkt = 1;   # Flagga att ta med interaktiva funktioner
   } 
   
   #
   # Hitta pages
   #
 
   if ($objektet =~ m'/Pages\s+(\d+)\s{1,2}\d+\s{1,2}R'os)
   {  $objektet = getObject($1);
      $resources = checkResources($objektet, $resources);
      if ($objektet =~ m'/Count\s+(\d+)'os)
      {  $sidor = $1;
         $behandlad{$infil}->{sidor} = $sidor;
      }   
   }
   else
   { errLog("Didn't find pages "); }

   my @levels; my %kids;
   my $li = -1;

   if ($objektet =~ m'/Kids\s*\[([^\]]+)'os)
   {  $vektor = $1;  
      while ($vektor =~ m'(\d+)\s{1,2}\d+\s{1,2}R'go)
      {   push @sidObj, $1;       
      }
      $li++;
      $levels[$li] = \@sidObj;
   }

   while (($li > -1) && ($sidAcc < $sidor))
   {  if (scalar @{$levels[$li]})
      {   my $j = shift @{$levels[$li]};
          $objektet = getObject($j);
          if ($objektet =~ m'/Kids\s*\[([^\]]+)'os)
          {  $resources = checkResources($objektet, $resources);
             $vektor = $1; 
             my @sObj; 
             while ($vektor =~ m'(\d+)\s{1,2}\d+\s{1,2}R'go)
             {   push @sObj, $1 if !$kids{$1}; $kids{$1}=1;       
             }
               if(@sObj)
               {  $li++;
                  $levels[$li] = \@sObj;
               }
          }
          else
          {  $sidAcc++;
             if ($sidAcc >= $from)
             {   if ($to)
                 {  if ($sidAcc <= $to)
                    {  sidAnalys($j, $objektet, $resources);
                       $extraherade++;
                       $sida++;
                    }
                    else
                    {  $sidAcc = $sidor;
                    }
                 }
                 else
                 {  sidAnalys($j, $objektet, $resources);
                    $extraherade++;
                    $sida++;
                 }
              }
          }
      }
      else
      {  $li--;
      }
   }
   
   if (defined $AcroForm)
   {  $AcroForm =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
   }
   if (defined $AARoot)
   {  $AARoot =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
   }
   
   while (scalar @skapa)
   {  my @process = @skapa;
      @skapa = ();
      for (@process)
      {  my $gammal = $$_[0];
         my $ny     = $$_[1];
         $objektet  = getObject($gammal);         

         if ($objektet =~ m'^(\d+ \d+ obj\s*<<)(.+)(>>\s*stream)'os)
         {  $del1 = $2;
            $strPos = length($2) + length($3) + length($1);
            $del1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
            $objekt[$ny] = $pos;
            $utrad = "$ny 0 obj<<" . "$del1" . '>>stream';
            $del2   = substr($objektet, $strPos);
            $utrad .= $del2; 

            $pos += syswrite UTFIL, $utrad;
         }
         else
         {  if ($objektet =~ m'^(\d+ \d+ obj)'os)
            {  my $preLength = length($1);
               $objektet = substr($objektet, $preLength);
            }
            $objektet =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
            $objekt[$ny] = $pos;
            $utrad = "$ny 0 obj$objektet";
            $pos += syswrite UTFIL, $utrad;
         }
      }
  }
  close INFIL;
  $processed{$infil}->{root}         = $root;
  
  if (! $singlePage)
  {   return ($extraherade, $Names, $AARoot, $AcroForm);
  }
  else
  {   if ($extraherade)
      {   my $kvar = $behandlad{$infil}->{sidor} - $from;
          return ($kvar, $Names, $AARoot, $AcroForm);
      }
      else
      {   return (undef, undef, undef, undef);
      }
  }
}

sub sidAnalys
{  my ($oNr, $obj, $resources) = @_;
   my ($ny, $strPos, $spar, $closeProc, $del1, $del2, $utrad, $Annots,
   $resursObjekt, $streamObjekt, @extObj, $langd);

   if ((defined $stream) && (length($stream) > 0))
   {               
       if ($checkCs)
       {  @extObj = ($stream =~ m'/(\S+)\s*'gso);
          checkContentStream(@extObj);
       }

       $objNr++;
       $objekt[$objNr] = $pos; 

       if (( $compress ) && ( length($stream)  > 99 ))
       {   my $output = compress($stream);
           if ((length($output) > 25) && (length($output) < (length($stream))))
           {  $stream = $output;
           }
           $langd = length($stream);
           $stream = "\n" . $stream . "\n";
           $langd++;
           $streamObjekt  = "$objNr 0 obj<</Filter/FlateDecode"
                             . "/Length $langd>>stream" . $stream;
           $streamObjekt .= "endstream\nendobj\n";
       
       }
       else
       {  $langd = length($stream);
          $streamObjekt  = "$objNr 0 obj<</Length $langd>>stream\n" . $stream;
          $streamObjekt .= "\nendstream\nendobj\n";
       }
       $pos += syswrite UTFIL, $streamObjekt;
       $streamObjekt = "$objNr 0 R ";

       ########################################################################
       # Sometimes the contents reference is a ref to an object which 
       # contains an array of content streams. Replace the ref with the array 
       ########################################################################

       if ($obj =~ m'/Contents\s+(\d+)\s{1,2}\d+\s{1,2}R'os)
       {   my $cObj = getObject($1, 1, 1);
           if ($cObj =~ m'^\s*\[[^\]]+\]\s*$'os)
           {   $obj =~ s|/Contents\s+\d+\s{1,2}\d+\s{1,2}R|'/Contents ' . $cObj|oes;
           }
       }

       my ($from, $to); 
       
       ($resources, $from, $to) = checkResources ($obj, $resources);
       if ($from && $to)
       {   $obj = substr($obj, 0, $from) . substr($obj, $to);
       }

       
       ##########################
       # Hitta resursdictionary
       ##########################
       my $i = 0;
       while (($resources !~ m'\/'os) && ($i < 10))
       {   $i++;
           if ($resources =~ m'\s+(\d+)\s{1,2}\d+\s{1,2}R'os)
           {   $resources = getObject($1, 1, 1);
           }
       }
       if ($i > 7)
       {  errLog("Couldn't find resources to merge");
       } 
       if ($resources =~ m'\s*\<\<(.*)\>\>'os)
       {  $resources = $1;
       }
        
       if ($resources !~ m'/ProcSet')
       {  $resources =  '/ProcSet[/PDF/Text] ' . $resources;
       }
       
       ###############################################################
       # Läsa ev. referenser och skapa ett resursobjekt bestående av
       # dictionaries (för utvalda resurser)
       ###############################################################

       if (scalar %sidFont)
       {  if ($resources =~ m'/Font\s+(\d+)\s{1,2}\d+\s{1,2}R'os)
          {   my $dict = getObject($1, 1, 1);
              $resources =~ s"/Font\s+\d+\s{1,2}\d+\s{1,2}R"'/Font' . $dict"ose;
          }
       }
       
       if (scalar %sidXObject)
       {  if ($resources =~ m'/XObject\s+(\d+)\s{1,2}\d+\s{1,2}R'os)
          {   my $dict = getObject($1, 1, 1);
              $resources =~ s"/XObject\s+\d+\s{1,2}\d+\s{1,2}R"'/XObject' . $dict"ose;
          }
       }

       if (scalar %sidExtGState)
       {  if ($resources =~ m'/ExtGState\s+(\d+)\s{1,2}\d+\s{1,2}R'os)
          {   my $dict = getObject($1, 1, 1);
              $resources =~ s"/ExtGState\s+\d+\s{1,2}\d+\s{1,2}R"'/ExtGState' . $dict"ose;
          }
       }
 
       if (scalar %sidPattern)
       {  if ($resources =~ m'/Pattern\s+(\d+)\s{1,2}\d+\s{1,2}R'os)
          {   my $dict = getObject($1, 1, 1);
              $resources =~ s"/Pattern\s+\d+\s{1,2}\d+\s{1,2}R"'/Pattern' . $dict"ose;
          }
       }

       if (scalar %sidShading)
       {  if ($resources =~ m'/Shading\s+(\d+)\s{1,2}\d+\s{1,2}R'os)
          {   my $dict = getObject($1, 1, 1);
              $resources =~ s"/Shading\s+\d+\s{1,2}\d+\s{1,2}R"'/Shading' . $dict"ose;
          }
       }

       if (scalar %sidColorSpace)
       {  if ($resources =~ m'/ColorSpace\s+(\d+)\s{1,2}\d+\s{1,2}R'os)
          {   my $dict = getObject($1, 1, 1);
              $resources =~ s"/ColorSpace\s+\d+\s{1,2}\d+\s{1,2}R"'/ColorSpace' . $dict"ose;
          }
       }
       ####################################################
       # Nu är resurserna "normaliserade" med ursprungliga
       # värden. Spara värden för "översättning"
       ####################################################
       
       $resources =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;

       ###############################
       # Komplettera med nya resurser
       ###############################

       if (scalar %sidFont)
       {  my $str = '';
          for (keys %sidFont)
          {  $str .= "/$_ $sidFont{$_} 0 R";
          }
          if ($resources !~ m'\/Font'os)
          {   $resources =  "/Font << $str >> " . $resources;
          }
          else
          {   $resources =~ s"/Font\s*<<"'/Font<<' . $str"oges;
          }
       }

       if (scalar %sidXObject)
       {  my $str = '';
          for (keys %sidXObject)
          {  $str .= "/$_ $sidXObject{$_} 0 R";
          }
          if ($resources !~ m'\/XObject'os)
          {   $resources =  "/XObject << $str >> " . $resources;
          }
          else
          {   $resources =~ s"/XObject\s*<<"'/XObject<<' . $str"oges;
          }
       }
       
       if (scalar %sidExtGState)
       {  my $str = '';
          for (keys %sidExtGState)
          {  $str .= "/$_ $sidExtGState{$_} 0 R";
          }
          if ($resources !~ m'\/ExtGState'os)
          {   $resources =  "/ExtGState << $str >> " . $resources;
          }
          else
          {   $resources =~ s"/ExtGState\s*<<"'/ExtGState<<' . $str"oges;
          }
       }
   
       if (scalar %sidPattern)
       {  my $str = '';
          for (keys %sidPattern)
          {  $str .= "/$_ $sidPattern{$_} 0 R";
          }
          if ($resources !~ m'\/Pattern'os)
          {   $resources =  "/Pattern << $str >> " . $resources;
          }
          else
          {   $resources =~ s"/Pattern\s*<<"'/Pattern<<' . $str"oges;
          }
       }

       if (scalar %sidShading)
       {  my $str = '';
          for (keys %sidShading)
          {  $str .= "/$_ $sidShading{$_} 0 R";
          }
          if ($resources !~ m'\/Shading'os)
          {   $resources =  "/Shading << $str >> " . $resources;
          }
          else
          {   $resources =~ s"/Shading\s*<<"'/Shading<<' . $str"oges;
          }
       }

       if (scalar %sidColorSpace)
       {  my $str = '';
          for (keys %sidColorSpace)
          {  $str .= "/$_ $sidColorSpace{$_} 0 R";
          }
          if ($resources !~ m'\/ColorSpace'os)
          {   $resources =  "/ColorSpace << $str >> " . $resources;
          }
          else
          {   $resources =~ s"/ColorSpace\s*<<"'/ColorSpace<<' . $str"oges;
          }
       }

       if (exists $resurser{$resources})
       {  $resources = "$resurser{$resources} 0 R\n";  # Fanns ett identiskt,
       }                                               # använd det
       else
       {   $objNr++;
           if ( keys(%resurser) < 10)
           {  $resurser{$resources} = $objNr;     # Spara 10 första resursobjekten
           }
           $objekt[$objNr] = $pos;
           $resursObjekt   = "$objNr 0 obj<<$resources>>endobj\n";
           $pos += syswrite UTFIL, $resursObjekt ;
           $resources      = "$objNr 0 R\n";
       }
   
       %sidXObject    = ();
       %sidExtGState  = ();
       %sidFont       = ();
       %sidPattern    = ();
       %sidShading    = ();
       %sidColorSpace = ();
       undef $checkCs;
    
       $stream     = '';
   }

   if (! $parents[0])
   { $objNr++;
     $parents[0] = $objNr;
   }
   my $parent = $parents[0];

   if (($sidObjNr) && (! defined $objekt[$sidObjNr]))
   {  $ny = $sidObjNr;
   }
   else
   {  $objNr++;
      $ny = $objNr;
   } 

   $old{$oNr} = $ny;
     
   if ($obj =~ m'/Parent\s+(\d+)\s{1,2}\d+\s{1,2}R\b'os)
   {  $old{$1} = $parent;
   }
   
   if ($obj =~ m'^\d+ \d+ obj\s*<<(.+)>>\s*endobj'os)
   {  $del1 = $1;
   }
   
   if (%links)
   {   my $tSida = $sida + 1;
       if (defined (@{$links{'-1'}}) || (defined @{$links{$tSida}}))
       {   if ($del1 =~ m'/Annots\s*([^\/\<\>]+)'os)
           {  $Annots  = $1;
              @annots = (); 
              if ($Annots =~ m'\[([^\[\]]*)\]'os)
              {  ; }
              else
              {  if ($Annots =~ m'\b(\d+)\s{1,2}\d+\s{1,2}R\b'os)
                 {  $Annots = getObject($1);
                 }
              }
              while ($Annots =~ m'\b(\d+)\s{1,2}\d+\s{1,2}R\b'ogs)
              {   push @annots, xform();
              }
              $del1 =~ s?/Annots\s*([^\/\<\>]+)??os;
           }
           $Annots = '/Annots ' . mergeLinks() . ' 0 R';
       }
   }

   if (! $taInterAkt)
   {  $del1 =~ s?\s*/AA\s*<<[^>]*>>??os;
   }
          
   $del1 =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
   
   if ($del1 !~ m'/Resources'o)
   {  $del1 .= "/Resources $resources";
   }

   if (defined $streamObjekt)     # En ny ström ska läggas till
   {  if ($del1 =~ m'/Contents\s+(\d+)\s{1,2}\d+\s{1,2}R'os)
      {  my $oldCont = $1;
         $del1 =~ s|/Contents\s+(\d+)\s{1,2}\d+\s{1,2}R|'/Contents [' . "$oldCont 0 R $streamObjekt" . ']'|oes;
      }
      elsif ($del1 =~ m'/Contents\s*\['os)
      {   $del1 =~ s|/Contents\s*\[([^\]]+)|'/Contents [' . $1 ." $streamObjekt"|oes;
      }
      else
      {   $del1 .= "/Contents $streamObjekt\n";
      }
   }

   if ($Annots)
   {  $del1 .= $Annots;
   }

   $utrad = "$ny 0 obj<<$del1>>";
   if (defined $del2)
   {   $utrad .= "stream\n$del2";
   }
   else
   {  $utrad .= "endobj\n";
   }

   $objekt[$ny] = $pos;
   $pos += syswrite UTFIL, $utrad;
     
   push @{$kids[0]}, $ny;
   $counts[0]++;
   if ($counts[0] > 9)
   {  ordnaNoder(8); 
   }
}  


sub checkResources
{   my $pObj  = shift;
    my $reStr = shift;
    my $to;

    my $p = index($pObj, '/Resources');
    if ( $p < 0)
    {  ;
    }
    elsif ($pObj =~ m'/Resources(\s+\d+\s{1,2}\d+\s{1,2}R)'os)
    {   $reStr = $1;
        $to = $p + 10 + length($reStr);
    }
    else
    {  my $t = length($pObj);
       my $i = $p + 10;
       my $j = $i;
       my $k = 0;
       my $c;
       while ($i < $t)
       {   $c = substr($pObj,$i,1);
           if (($c eq '<' )
           ||  ($c eq '>'))
           {   if ($c eq '<' )
               {  $k++;
               }
               else
               {  $k--;
               }
               last if ($k == 0);
           }
           $i++;
       }
       if ($i != $t)
       {  $i++;
          $reStr = substr($pObj, $j, ($i - $j));
          $to = $i;
       }
   }

   if (wantarray)
   {  return ($reStr, $p, $to);
   }
   else
   {  return $reStr;
   }
}


sub translate
{ if (exists $old{$1})
  { $old{$1}; }
  else
  {  $old{$1} = ++$objNr;
  }     
}  

sub behandlaNames
{  my ($namnObj, $iForm) = @_;
   
   my ($low, $high, $antNod0, $entry, $nyttNr, $ny, $obj,
       $fObjnr, $offSet, $bytes, $res, $key, $func, $corr, @objData);
   my (@nod0, @nodUpp, @kid, @soek, %nytt);
   
   my $objektet  = '';
   my $vektor    = '';   
   my $antal     = 0;
   my $antNodUpp = 0;
   if ($namnObj)
   {  if ($iForm)                                # Läsning via interntabell
      {   $objektet = getObject($namnObj, 1);

          if ($objektet =~ m'<<(.+)>>'ogs)
          { $objektet = $1; }
          if ($objektet =~ s'/JavaScript\s+(\d+)\s{1,2}\d+\s{1,2}R''os)
          {  my $byt = $1; 
             push @kid, $1;
             while (scalar @kid)
             {  @soek = @kid;
                @kid = ();
                for my $sObj (@soek)
                {  $obj = getObject($sObj, 1);
                   if ($obj =~ m'/Kids\s*\[([^]]+)'ogs)
                   {  $vektor = $1;
                   }
                   while ($vektor =~ m'\b(\d+)\s{1,2}\d+\s{1,2}R\b'ogs)
                   {  push @kid, $1;
                   }
                   $vektor = '';
                   if ($obj =~ m'/Names\s*\[([^]]+)'ogs)
                   {   $vektor = $1;
                   }
                   while ($vektor =~ m'\(([^\)]+)\)\s*(\d+) \d R'gos)
                   {   $script{$1} = $2;                
                   }
                }
             }
          }
      }
      else                                #  Läsning av ett "doc"
      {  $objektet = getObject($namnObj);             
         if ($objektet =~ m'<<(.+)>>'ogs)
         {  $objektet = $1; }
         if ($objektet =~ s'/JavaScript\s+(\d+)\s{1,2}\d+\s{1,2}R''os)
         {  my $byt = $1; 
            push @kid, $1;
            while (scalar @kid)
            {  @soek = @kid;
               @kid = ();
               for my $sObj (@soek)
               {  $obj = getObject($sObj);  
                  if ($obj =~ m'/Kids\s*\[([^]]+)'ogs)
                  {  $vektor = $1;
                  }
                  while ($vektor =~ m'\b(\d+)\s{1,2}\d+\s{1,2}R\b'ogs)
                  {  push @kid, $1;
                  }
                  undef $vektor;
                  if ($obj =~ m'/Names\s*\[([^]]+)'ogs)
                  {  $vektor = $1;
                  }
                  while ($vektor =~ m'\(([^\)]+)\)\s*(\d+) \d R'gos)
                  {   $script{$1} = $2;                
                  }
               }        
             }
          }
      } 
   }
   for my $filnamn (@jsfiler)
   {   inkludera($filnamn);
   }
   my @nya = (keys %nyaFunk);
   while (scalar @nya)
   {   my @behandla = @nya;
       @nya = ();
       for $key (@behandla)
       {   if (exists $initScript{$key})
           {  if (exists $nyaFunk{$key})
              {   $initScript{$key} = $nyaFunk{$key};
              }
              if (exists $script{$key})   # företräde för nya funktioner !
              {   delete $script{$key};    # gammalt script m samma namn plockas bort
              } 
              my @fall = ($initScript{$key} =~ m'([\w\d\_\$]+)\s*\('ogs);
              for (@fall)
              {   if (($_ ne $key) && (exists $nyaFunk{$_}))
                  {  $initScript{$_} = $nyaFunk{$_}; 
                     push @nya, $_; 
                  }
              }
           }
       }
   }
   while  (($key, $func) = each %nyaFunk)
   {  $fObjnr = skrivJS($func);
      $script{$key} = $fObjnr;
      $nytt{$key}   = $fObjnr;
   }
     
   if (scalar %fields)
   {  push @inits, 'Ladda();';
      $fObjnr = defLadda();
      if ($duplicateInits)
      {  $script{'Ladda'} = $fObjnr;
         $nytt{'Ladda'} = $fObjnr;
      }
   }

   if ((scalar @inits) && ($duplicateInits))
   {  $fObjnr = defInit();
      $script{'Init'} = $fObjnr;
      $nytt{'Init'} = $fObjnr;
   }
   undef @jsfiler;
 
   for my $key (sort (keys %script))
   {  if (! defined $low)
      {  $objNr++;
         $ny = $objNr;     
         $objekt[$ny] = $pos;
         $obj = "$ny 0 obj\n";
         $low  = $key;
         $obj .= '<< /Names [';
      }
      $high = $key;
      $obj .= '(' . "$key" . ')';
      if (! exists $nytt{$key})
      {  $nyttNr = quickxform($script{$key});
      }
      else
      {  $nyttNr = $script{$key};
      }
      $obj .= "$nyttNr 0 R\n";      
      $antal++;
      if ($antal > 9)
      {   $obj .= ' ]/Limits [(' . "$low" . ')(' . "$high" . ')] >>' . "endobj\n";
          $pos += syswrite UTFIL, $obj;
          push @nod0, \[$ny, $low, $high];
          $antNod0++; 
          undef $low;
          $antal = 0; 
      }
   }
   if ($antal)
   {   $obj .= ']/Limits [(' . $low . ')(' . $high . ')]>>' . "endobj\n";
       $pos += syswrite UTFIL, $obj;
       push @nod0, \[$ny, $low, $high];
       $antNod0++;
   }
   $antal = 0;

   while (scalar @nod0)
   {   for $entry (@nod0)
       {   if ($antal == 0)
           {   $objNr++;     
               $objekt[$objNr] = $pos;
               $obj = "$objNr 0 obj\n";
               $low  = $$entry->[1];
               $obj .= '<</Kids [';
           }
           $high = $$entry->[2];
           $obj .= " $$entry->[0] 0 R";
           $antal++;
           if ($antal > 9)
           {   $obj .= ']/Limits [(' . $low . ')(' . $high . ')]>>' . "endobj\n";
               $pos += syswrite UTFIL, $obj;
               push @nodUpp, \[$objNr, $low, $high];
               $antNodUpp++; 
               undef $low;
               $antal = 0; 
           } 
       }
       if ($antal > 0)
       {   if ($antNodUpp == 0)     # inget i noderna över
           {   $obj .= ']>>' . "endobj\n";
               $pos += syswrite UTFIL, $obj;
           }
           else
           {   $obj .= ']/Limits [(' . "$low" . ')(' . "$high" . ')]>>' . "endobj\n";
               $pos += syswrite UTFIL, $obj;
               push @nodUpp, \[$objNr, $low, $high];
               $antNodUpp++; 
               undef $low;
               $antal = 0; 
           }
       }
       @nod0    = @nodUpp;
       $antNod0 = $antNodUpp;
       undef @nodUpp;
       $antNodUpp = 0;
   }
      
  
   $ny = $objNr;
   $objektet =~ s|\s*/JavaScript\s*\d+\s{1,2}\d+\s{1,2}R||os;
   $objektet =~ s/\b(\d+)\s{1,2}\d+\s{1,2}R\b/xform() . ' 0 R'/oegs;
   if (scalar %script)
   {  $objektet .= "\n/JavaScript $ny 0 R\n";
   }
   $objNr++;
   $ny = $objNr;
   $objekt[$ny] = $pos;
   $objektet = "$ny 0 obj<<" . $objektet . ">>endobj\n";
   $pos += syswrite UTFIL, $objektet;
   return $ny;
}


sub quickxform
{  my $inNr = shift;
   if (exists $old{$inNr})
   {  $old{$inNr}; }
   else
   {  push @skapa, [$inNr, ++$objNr];
      $old{$inNr} = $objNr;                   
   } 
} 


sub skrivKedja
{  my $code = ' ';
   
   for (values %initScript)
   {   $code .= $_ . "\n";
   }
   $code .= "function Init() { ";
   $code .= 'if (typeof this.info.ModDate == "object")' . " { return true; }"; 
   for (@inits)
   {  $code .= $_ . "\n";
   }
   $code .= "} Init(); ";

   my $spar = skrivJS($code);
   undef @inits;
   undef %initScript;
   return $spar;
}



sub skrivJS
{  my $kod = shift;
   my $obj;
   if (($compress) && (length($kod) > 99))
   {  $objNr++;
      $objekt[$objNr] = $pos;
      my $spar = $objNr;
      $kod = compress($kod);
      my $langd = length($kod);
      $obj = "$objNr 0 obj<</Filter/FlateDecode"
                           .  "/Length $langd>>stream\n" . $kod 
                           .  "\nendstream\nendobj\n";
      $pos += syswrite UTFIL, $obj;
      $objNr++;
      $objekt[$objNr] = $pos;
      $obj = "$objNr 0 obj<</S/JavaScript/JS $spar 0 R >>endobj\n";
   }
   else
   {  $kod =~ s'\('\\('gso;
      $kod =~ s'\)'\\)'gso;
      $objNr++;
      $objekt[$objNr] = $pos;
      $obj = "$objNr 0 obj<</S/JavaScript/JS " . '(' . $kod . ')';
      $obj .= ">>endobj\n";
   }
   $pos += syswrite UTFIL, $obj;           
   return $objNr;
}

sub inkludera
{   my $jsfil = shift;
    my $fil;
    if ($jsfil !~ m'\{'os)
    {   open (JSFIL, "<$jsfil") || return;
        while (<JSFIL>)
        { $fil .= $_;}

        close JSFIL;
    }
    else
    {  $fil = $jsfil;
    }
    $fil =~ s|function\s+([\w\_\d\$]+)\s*\(|"zXyZcUt function $1 ("|sge;
    my @funcs = split/zXyZcUt /, $fil;
    for my $kod (@funcs)
    {   if ($kod =~ m'^function ([\w\_\d\$]+)'os)
        {   $nyaFunk{$1} = $kod;
        }
    }   
}


sub defLadda
{  my $code = "function Ladda() {";
   for (keys %fields)
   {  my $val = $fields{$_};
      if ($val =~ m'\s*js\s*\:(.+)'oi) 
      {   $val = $1;
          $code .= "if (this.getField('$_')) this.getField('$_').value = $val; ";
      }
      else
      {  $val =~ s/([^A-Za-z0-9\-_.!* ])/sprintf("%%%02X", ord($1))/ge;
         $code .= "if (this.getField('$_')) this.getField('$_').value = unescape('$val'); ";
      }

   }  
   $code .= " 1;} ";
   
   
   $initScript{'Ladda'} = $code;
   if ($duplicateInits) 
   {  my $ny = skrivJS($code);        
      return $ny;
   }
   else
   {  return 1;
   }
}

sub defInit
{  my $code = "function Init() { ";
   $code .= 'if (typeof this.info.ModDate == "object")' . " { return true; } "; 
   for (@inits)
   {  $code .= $_ . "\n";
   }
   $code .= '}';
             
   my $ny = skrivJS($code);        
   return $ny;

}



sub errLog
{   no strict 'refs';
    my $mess = shift;
    my $endMess  = " $mess \n More information might be found in"; 
    if ($runfil)
    {   $log .= "Log~Err: $mess\n";
        $endMess .= "\n   $runfil";
        if (! $pos)
        {  $log .= "Log~Err: No pdf-file has been initiated\n";
        }
        elsif ($pos > 15000000)
        {  $log .= "Log~Err: Current pdf-file is very big: $pos bytes, will not try to finish it\n"; 
        }
        else
        {  $log .= "Log~Err: Will try to finish current pdf-file\n";
           $endMess .= "\n   $utfil";
        }
    }
    my $errLog = 'error.log';
    my $now = localtime();
    my $lpos = $pos || 'undef';
    my $lobjNr = $objNr || 'undef';
    my $lutfil = $utfil || 'undef';
    
    my $lrunfil = $runfil || 'undef'; 
    open (ERRLOG, ">$errLog") || croak "$mess can't open an error logg, $!";
    print ERRLOG "\n$mess\n\n";
    print ERRLOG Carp::longmess("The error occurred when executing:\n");
    print ERRLOG "\nSituation when the error occurred\n\n";
    print ERRLOG "   Bytes written to the current pdf-file,    pos    = $lpos\n";
    print ERRLOG "   Object processed, not necessarily written objNr  = $lobjNr\n";
    print ERRLOG "   Current pdf-file,                         utfil  = $lutfil\n";
    print ERRLOG "   File logging the run,                     runfil = $lrunfil\n";
    print ERRLOG "   Local time                                       = $now\n"; 
    print ERRLOG "\n\n";    
    close ERRLOG;
    $endMess .= "\n   $errLog";
    if (($pos) && ($pos < 15000000))
    {  prEnd();
    }
    print STDERR Carp::shortmess("An error occurred \n");
    croak "$endMess\n";      
}